{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); ');\nglobal.window = global.document.defaultView;\nglobal.navigator = global.window.navigator;\nconst $ = _$(window);\n\nchaiJquery(chai, chai.util, $);\n\nfunction renderComponent(ComponentClass, props = {}, state = {}) {\n const componentInstance = TestUtils.renderIntoDocument(\n \n \n \n );\n\n return $(ReactDOM.findDOMNode(componentInstance));\n}\n\n$.fn.simulate = function(eventName, value) {\n if (value) {\n this.val(value);\n }\n TestUtils.Simulate[eventName](this[0]);\n};\n\nexport {renderComponent, expect};\n"}}},{"rowIdx":1053,"cells":{"path":{"kind":"string","value":"src/components/cart/cartCheckOut/CartCheckOutListItemComponent.js"},"repo_name":{"kind":"string","value":"bluebill1049/cart"},"content":{"kind":"string","value":"'use strict';\n\nimport React from 'react';\n\nrequire('styles/cart/cartCheckOut/CartCheckOutListItem.scss');\n\nclass CartCheckOutListItemComponent extends React.Component {\n constructor(props) {\n super(props)\n }\n\n render() {\n return (\n
  • \n \n
    \n

    {this.props.item.fields.itemName}

    \n

    {this.props.item.fields.itemShortDescription}

    \n

    ${this.props.item.fields.price}

    \n
    \n
    \n \n
    \n
  • \n );\n }\n}\n\nCartCheckOutListItemComponent.displayName = 'CartCartCheckOutCartCheckOutListItemComponent';\n\n// Uncomment properties you need\nCartCheckOutListItemComponent.propTypes = {\n item : React.PropTypes.object.isRequired,\n removeItem : React.PropTypes.func.isRequired,\n itemIndex : React.PropTypes.number.isRequired\n // viewDetail : React.PropTypes.func.isRequired\n};\n// CartCheckOutListItemComponent.defaultProps = {};\n\nexport default CartCheckOutListItemComponent;\n"}}},{"rowIdx":1054,"cells":{"path":{"kind":"string","value":"src/components/SegmentedControl.js"},"repo_name":{"kind":"string","value":"pairyo/elemental"},"content":{"kind":"string","value":"import classnames from 'classnames';\nimport React from 'react';\n\nmodule.exports = React.createClass({\n\tdisplayName: 'SegmentedControl',\n\n\tpropTypes: {\n\t\tclassName: React.PropTypes.string,\n\t\tequalWidthSegments: React.PropTypes.bool,\n\t\tonChange: React.PropTypes.func.isRequired,\n\t\toptions: React.PropTypes.array.isRequired,\n\t\ttype: React.PropTypes.oneOf(['default', 'muted', 'danger', 'info', 'primary', 'success', 'warning']),\n\t\tvalue: React.PropTypes.string\n\t},\n\n\tgetDefaultProps () {\n\t\treturn {\n\t\t\ttype: 'default'\n\t\t};\n\t},\n\n\tonChange (value) {\n\t\tthis.props.onChange(value);\n\t},\n\n\trender () {\n\t\tlet componentClassName = classnames('SegmentedControl', ('SegmentedControl--' + this.props.type), {\n\t\t\t'SegmentedControl--equal-widths': this.props.equalWidthSegments\n\t\t}, this.props.className);\n\n\t\tlet options = this.props.options.map((op) => {\n\n\t\t\tlet buttonClassName = classnames('SegmentedControl__button', {\n\t\t\t\t'is-selected': op.value === this.props.value\n\t\t\t});\n\n\t\t\treturn (\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t);\n\t\t});\n\n\t\treturn
    {options}
    ;\n\t}\n});\n"}}},{"rowIdx":1055,"cells":{"path":{"kind":"string","value":"src/app.react.js"},"repo_name":{"kind":"string","value":"JasonStoltz/test-runner-demo"},"content":{"kind":"string","value":"import {connect} from 'react-redux';\nimport {List} from 'immutable';\nimport React from 'react';\nimport Promise from 'bluebird';\nimport PureComponent from 'react-pure-render/component';\nimport TestsService from './model/test';\n\nimport mapStateToProps from './lib/mapStateToProps';\nimport mapDispatchToProps from './lib/mapDispatchToProps';\n\nimport * as actions from './store/tests/actions';\n\nimport * as TestConstants from './model/test';\nimport Test from './model/test';\nimport * as TestsConstants from './store/tests/reducers';\n\nimport Tests from './components/runner/tests.react.js';\nimport Status from './components/runner/status.react';\n\n@connect(mapStateToProps('tests'), mapDispatchToProps(actions))\nexport default class App extends PureComponent {\n static propTypes = {\n tests: React.PropTypes.object.isRequired,\n actions: React.PropTypes.object.isRequired\n };\n\n constructor() {\n super();\n this.run = this.run.bind(this); //So we don't break pure render\n }\n\n render() {\n const {tests} = this.props;\n\n return (\n
    \n
    \n

    Tests

    \n {tests.get('status') === TestsConstants.FINISHED &&\n
    FINISHED!
    \n }\n \n
    \n \n
    \n \n
    \n
    \n );\n }\n\n componentDidMount() {\n const {actions} = this.props;\n const tests = Test.all();\n actions.setTests(tests);\n }\n\n run(e) {\n e.preventDefault();\n\n const {actions} = this.props;\n const tests = this.props.tests.get('tests');\n\n tests.forEach(test => {\n actions.setStatus(test.get('id'), TestConstants.RUNNING);\n TestsService.run(test.get('id')).then(result => {\n actions.setStatus(test.get('id'), (result) ? TestConstants.PASSED : TestConstants.FAILED);\n });\n });\n }\n}\n"}}},{"rowIdx":1056,"cells":{"path":{"kind":"string","value":"src/components/Scheme/HypertensionC.js"},"repo_name":{"kind":"string","value":"lethecoa/work-order-pc"},"content":{"kind":"string","value":"import React from 'react';\nimport {Form, InputNumber, Row, Col} from 'antd';\nimport styles from './Scheme.less';\n\nconst FormItem = Form.Item;\nconst formItemLayout = {\n\tlabelCol: {\n\t\txs: { span: 24 },\n\t\tsm: { span: 8 },\n\t},\n\twrapperCol: {\n\t\txs: { span: 24 },\n\t\tsm: { span: 16 },\n\t},\n};\n\nclass HypertensionC extends React.Component {\n\tstate = {\n\t\tscheme: {},\n\t};\n\n\tcomponentWillMount() {\n\t\tthis.setState( { scheme: this.props.scheme } );\n\t}\n\n\tcomponentWillReceiveProps( nextProps ) {\n\t\tthis.setState( { scheme: nextProps.scheme } );\n\t}\n\n\trender() {\n\t\tconst { getFieldDecorator } = this.props.form;\n\t\tconst disabled = this.props.disabled;\n\t\tconst { scheme } = this.state;\n\t\treturn (\n\t\t\t
    \n\t\t\t\t
    随访项目
    \n\t\t\t\t
    \n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t{getFieldDecorator( 'sbp', {\n\t\t\t\t\t\t\t\t\tinitialValue: scheme.sbp\n\t\t\t\t\t\t\t\t} )(\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t{getFieldDecorator( 'dbp', {\n\t\t\t\t\t\t\t\t\tinitialValue: scheme.dbp\n\t\t\t\t\t\t\t\t} )(\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
    \n\t\t\t
    \n\t\t);\n\t}\n}\nexport default Form.create()( HypertensionC );\n\n"}}},{"rowIdx":1057,"cells":{"path":{"kind":"string","value":"src/components/pages/NotFoundPage.js"},"repo_name":{"kind":"string","value":"mm-taigarevolution/tas_web_app"},"content":{"kind":"string","value":"import React from 'react';\nimport { Link } from 'react-router-dom';\n\nconst NotFoundPage = () => {\n return (\n
    \n

    \n 404 Page Not Found\n

    \n Go back to homepage \n
    \n );\n};\n\nexport default NotFoundPage;\n"}}},{"rowIdx":1058,"cells":{"path":{"kind":"string","value":"app/views/Homepage/components/RetroTitanic.js"},"repo_name":{"kind":"string","value":"herereadthis/redwall"},"content":{"kind":"string","value":"import React from 'react';\nimport AppConstants from 'AppConstants';\n\nexport default class RetroTitantic extends React.Component {\n\n constructor() {\n super();\n }\n\n componentWillMount() {\n }\n\n componentDidMount() {\n }\n\n render() {\n var titanticStyle;\n\n titanticStyle = {\n paddingTop: '2rem',\n paddingBottom: '1rem'\n };\n\n return (\n
    \n

    Here are some awesome thing!

    \n
    \n

    1997 was the best year ever!

    \n\n
    \n {AppConstants.dataSprite('titanic_468x60')}\n
    \n
    \n
    \n );\n }\n}\n\n"}}},{"rowIdx":1059,"cells":{"path":{"kind":"string","value":"src/js/component/ClearCompleted.js"},"repo_name":{"kind":"string","value":"dtk0528/TODOs"},"content":{"kind":"string","value":"import React, { Component } from 'react';\n\nclass ClearCompleted extends Component {\n render() {\n let clearButton = null;\n\n if (this.props.itemCount > 0) {\n clearButton = (\n \n );\n }\n\n return (\n
    \n { clearButton }\n
    \n );\n }\n}\n\nexport default ClearCompleted;\n"}}},{"rowIdx":1060,"cells":{"path":{"kind":"string","value":"src/mobile/routes.js"},"repo_name":{"kind":"string","value":"Perslu/rerebrace"},"content":{"kind":"string","value":"import chalk from 'chalk';\nimport { injectReducer } from './redux/reducers';\n\nimport React from 'react';\nimport { Route, IndexRoute } from 'react-router/es6';\nimport App from './App'\nimport GalleryView from './public/containers/GalleryView';\nimport ProfileView from './public/containers/ProfileView';\n// import Home from './Home'\nimport UserInfo from './UserInfo'\nimport NotFound from './NotFound'\n\nconst errorLoading = (err) => {\n console.error(chalk.red(`==> 😭 Dynamic page loading failed ${err}`));\n};\n\nconst loadModule = cb => (Component) => {\n cb(null, Component.default);\n};\n\n\n\n\nexport default (\n \n \n \n \n \n \n)\n\n\n// export default function createRoutes(store) {\n// return {\n// path: '/',\n// component: App,\n// indexRoute: Home,\n// childRoutes: [\n// {\n// path: 'UserInfo/:id',\n//\n// getComponent(location, cb) {\n// const importModules = Promise.all([\n// System.import('./UserInfo'),\n// // System.import('./UserInfo/reducer'),\n// ]);\n//\n// const renderRoute = loadModule(cb);\n//\n// importModules\n// .then(([Component/*, reducer*/]) => {\n// // injectReducer(store, 'userInfo', reducer.default);\n//\n// renderRoute(Component);\n// })\n// .catch(errorLoading);\n// },\n// },\n// {\n// path: '*',\n// getComponent(location, cb) {\n// System.import('./NotFound')\n// .then(loadModule(cb))\n// .catch(errorLoading);\n// },\n// },\n// ],\n// };\n// }\n"}}},{"rowIdx":1061,"cells":{"path":{"kind":"string","value":"app/javascript/mastodon/components/radio_button.js"},"repo_name":{"kind":"string","value":"kirakiratter/mastodon"},"content":{"kind":"string","value":"import React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nexport default class RadioButton extends React.PureComponent {\n\n static propTypes = {\n value: PropTypes.string.isRequired,\n checked: PropTypes.bool,\n name: PropTypes.string.isRequired,\n onChange: PropTypes.func.isRequired,\n label: PropTypes.node.isRequired,\n };\n\n render () {\n const { name, value, checked, onChange, label } = this.props;\n\n return (\n \n );\n }\n\n}\n"}}},{"rowIdx":1062,"cells":{"path":{"kind":"string","value":"client/src/components/Polls.js"},"repo_name":{"kind":"string","value":"NicholasAsimov/voting-app"},"content":{"kind":"string","value":"import React from 'react';\nimport { connect } from 'react-redux';\nimport Poll from './Poll';\nimport { Link } from 'react-router';\nimport { LinkContainer } from 'react-router-bootstrap';\nimport { ListGroup, ListGroupItem } from 'react-bootstrap';\n\nclass Polls extends React.Component {\n render() {\n return (\n
    \n

    Public polls

    \n

    Select a poll to see the results and vote, or make a new poll!

    \n \n {this.props.polls.map((poll, index) => (\n \n {poll.title}\n \n ))}\n \n
    \n )\n }\n}\n\nfunction mapStateToProps(state) {\n return { polls: state.polls };\n}\n\nexport default connect(mapStateToProps)(Polls);\n"}}},{"rowIdx":1063,"cells":{"path":{"kind":"string","value":"src/icons/AndroidAdd.js"},"repo_name":{"kind":"string","value":"fbfeix/react-icons"},"content":{"kind":"string","value":"import React from 'react';\nimport IconBase from './../components/IconBase/IconBase';\n\nexport default class AndroidAdd extends React.Component {\n\trender() {\nif(this.props.bare) {\n\t\t\treturn \n\n\n\t\n\t\t\n\t\n\n\n\t\t\t;\n\t\t}\t\treturn \n\n\t\n\t\t\n\t\n\n;\n\t}\n};AndroidAdd.defaultProps = {bare: false}"}}},{"rowIdx":1064,"cells":{"path":{"kind":"string","value":"src/components/GroceryList.js"},"repo_name":{"kind":"string","value":"clayhan/reactserver"},"content":{"kind":"string","value":"import React from 'react';\n\nexport default class GroceryList extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n clickedItems: []\n };\n\n this.handleClick = this.handleClick.bind(this);\n }\n\n handleClick(e) {\n const clickedItems = this.state.clickedItems.slice();\n clickedItems.push(e.target.textContent);\n this.setState({ clickedItems: clickedItems });\n }\n\n render() {\n console.log('FE Render: GroceryList');\n return (\n
    \n
    GroceryList Component
    \n

    Ingredients:

    \n
    \n
      \n {this.props.ingredients.map((ingredient) => {\n return
    1. {ingredient}
    2. \n })}\n
    \n
    \n
    \n
    Things I need to buy:
    \n
      \n {this.state.clickedItems.map((item) => {\n return
    • {item}
    • \n })}\n
    \n
    \n
    \n );\n }\n}\n\n"}}},{"rowIdx":1065,"cells":{"path":{"kind":"string","value":"src/Containers/Top10/Top10.js"},"repo_name":{"kind":"string","value":"rahulp959/airstats.web"},"content":{"kind":"string","value":"import React from 'react'\nimport {connect} from 'react-redux'\nimport TableTop from './TableTop/TableTop'\nimport './Top10.scss'\n\nimport { fetchTop10 } from '../../ducks/top10.js'\n\nlet top10Dispatcher\nconst refreshTime = 60 * 30 * 1000 // Once per half-hour\n\nclass Top10 extends React.Component {\n componentDidMount () {\n this.props.dispatch(fetchTop10())\n\n top10Dispatcher = setInterval(() => this.props.dispatch(fetchTop10()), refreshTime)\n }\n\n componentWillUnmount () {\n clearInterval(top10Dispatcher)\n }\n\n render () {\n console.dir(this.props.top10)\n let html = ''\n if (this.props.top10.get('isFetching') === true) {\n html = 'Loading...'\n } else {\n html = (\n
    \n
    \n
    Top Departures
    \n \n
    \n
    \n
    Top Arrivals
    \n \n
    \n
    \n )\n }\n return (\n
    \n

    Top 10 airports by types of operations within the past 7 days.

    \n {html}\n

    Last updated: {this.props.top10.getIn(['data', 'updated'])}Z

    \n
    \n )\n }\n}\nconst mapStateToProps = state => {\n return {\n top10: state.get('top10')\n }\n}\n\nexport default connect(mapStateToProps)(Top10)\n"}}},{"rowIdx":1066,"cells":{"path":{"kind":"string","value":"src/router.js"},"repo_name":{"kind":"string","value":"ITenTeges/portfolioPage"},"content":{"kind":"string","value":"/**\n * React Static Boilerplate\n * https://github.com/kriasoft/react-static-boilerplate\n *\n * Copyright © 2015-present Kriasoft, LLC. All rights reserved.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.txt file in the root directory of this source tree.\n */\n\nimport React from 'react';\n\nfunction decodeParam(val) {\n if (!(typeof val === 'string' || val.length === 0)) {\n return val;\n }\n\n try {\n return decodeURIComponent(val);\n } catch (err) {\n if (err instanceof URIError) {\n err.message = `Failed to decode param '${val}'`;\n err.status = 400;\n }\n\n throw err;\n }\n}\n\n// Match the provided URL path pattern to an actual URI string. For example:\n// matchURI({ path: '/posts/:id' }, '/dummy') => null\n// matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 }\nfunction matchURI(route, path) {\n const match = route.pattern.exec(path);\n\n if (!match) {\n return null;\n }\n\n const params = Object.create(null);\n\n for (let i = 1; i < match.length; i += 1) {\n params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined;\n }\n\n return params;\n}\n\n// Find the route matching the specified location (context), fetch the required data,\n// instantiate and return a React component\nfunction resolve(routes, context) {\n for (const route of routes) { // eslint-disable-line no-restricted-syntax\n const params = matchURI(route, context.error ? '/error' : context.pathname);\n\n if (!params) {\n continue; // eslint-disable-line no-continue\n }\n\n // Check if the route has any data requirements, for example:\n // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' }\n if (route.data) {\n // Load page component and all required data in parallel\n const keys = Object.keys(route.data);\n return Promise.all([\n route.load(),\n ...keys.map((key) => {\n const query = route.data[key];\n const method = query.substring(0, query.indexOf(' ')); // GET\n let url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id\n // TODO: Optimize\n Object.keys(params).forEach((k) => {\n url = url.replace(`${k}`, params[k]);\n });\n return fetch(url, { method }).then(resp => resp.json());\n }),\n ]).then(([Page, ...data]) => {\n const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {});\n return ;\n });\n }\n\n return route.load().then(Page => );\n }\n\n const error = new Error('Page not found');\n error.status = 404;\n return Promise.reject(error);\n}\n\nexport default { resolve };\n"}}},{"rowIdx":1067,"cells":{"path":{"kind":"string","value":"examples/huge-apps/routes/Course/components/Course.js"},"repo_name":{"kind":"string","value":"AnSavvides/react-router"},"content":{"kind":"string","value":"import React from 'react';\nimport Dashboard from './Dashboard';\nimport Nav from './Nav';\n\nvar styles = {};\n\nstyles.sidebar = {\n float: 'left',\n width: 200,\n padding: 20,\n borderRight: '1px solid #aaa',\n marginRight: 20\n};\n\nclass Course extends React.Component {\n render () {\n let { children, params } = this.props;\n let course = COURSES[params.courseId];\n\n return (\n
    \n

    {course.name}

    \n
    \n );\n }\n}\n\nexport default Course;\n"}}},{"rowIdx":1068,"cells":{"path":{"kind":"string","value":"components/Login/ReviseUser.js"},"repo_name":{"kind":"string","value":"slidewiki/slidewiki-platform"},"content":{"kind":"string","value":"import PropTypes from 'prop-types';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport classNames from 'classnames';\nimport {navigateAction} from 'fluxible-router';\nimport {connectToStores} from 'fluxible-addons-react';\nimport checkEmail from '../../actions/user/registration/checkEmail';\nimport checkUsername from '../../actions/user/registration/checkUsername';\nimport UserRegistrationStore from '../../stores/UserRegistrationStore';\nimport SSOStore from '../../stores/SSOStore';\nimport common from '../../common';\nimport finalizeMergedUser from '../../actions/user/finalizeMergedUser';\nimport instances from '../../configs/instances.js';\nimport {FormattedMessage, defineMessages} from 'react-intl';\n\nconst headerStyle = {\n 'textAlign': 'center'\n};\nconst modalStyle = {\n top: '15%'\n};\n\nclass ReviseUser extends React.Component {\n constructor(props) {\n super(props);\n\n this.errorMessages = defineMessages({\n error409: {\n id: 'SSOSignIn.errormessage.isForbidden',\n defaultMessage: 'Migration is not possible with this user. Please start all over again.'\n },\n error404: {\n id: 'SSOSignIn.errormessage.accountNotFound',\n defaultMessage: 'This account was not prepared for migration. Please start all over again.'\n },\n error500: {\n id: 'SSOSignIn.errormessage.badImplementation',\n defaultMessage: 'An unknown error occurred.'\n }\n });\n }\n\n componentDidMount() {\n //Form validation\n const validationRules = {\n fields: {\n\n username: {\n identifier: 'username',\n rules: [{\n type: 'empty',\n prompt: 'Please select your username'\n }, {\n type: 'uniqueUsername',\n prompt: 'The username is already in use'\n }, {\n type : 'maxLength[64]',\n prompt : 'Your username can not be longer than 64 characters'\n }, {\n type : 'regExp[/^[a-zA-Z0-9-.~_]+$/i]',\n prompt : 'The username must contain only alphanumeric characters plus the following: _ . - ~'\n }]\n },\n email: {\n identifier: 'email',\n rules: [{\n type: 'empty',\n prompt: 'Please enter your email address'\n }, {\n type: 'email',\n prompt: 'Please enter a valid email address'\n }, {\n type: 'uniqueEmail',\n prompt: 'The email address is already in use'\n }]\n }\n },\n onSuccess: this.handleSignUp.bind(this)\n };\n\n $.fn.form.settings.rules.uniqueEmail = (() => {\n const emailNotAllowed = this.props.UserRegistrationStore.failures.emailNotAllowed;\n return (emailNotAllowed !== undefined) ? !emailNotAllowed : true;\n });\n $.fn.form.settings.rules.uniqueUsername = (() => {\n const usernameNotAllowed = this.props.UserRegistrationStore.failures.usernameNotAllowed;\n return (usernameNotAllowed !== undefined) ? !usernameNotAllowed : true;\n });\n\n $(ReactDOM.findDOMNode(this.refs.ReviseUser_form)).form(validationRules);\n\n }\n\n componentWillReceiveProps(nextProps) {\n console.log('ReviseUser componentWillReceiveProps()', this.props.UserRegistrationStore.socialuserdata, nextProps.UserRegistrationStore.socialuserdata, this.props.SSOStore.username, nextProps.SSOStore.username);\n if (nextProps.SSOStore.username !== this.props.SSOStore.username) {\n this.refs.username.value = nextProps.SSOStore.username;\n this.refs.email.value = nextProps.SSOStore.email;\n this.checkUsername();\n this.checkEmail();\n }\n }\n\n handleSignUp(e) {\n e.preventDefault();\n\n let user = {};\n user.email = this.refs.email.value;\n user.username = this.refs.username.value;\n user.hash = this.props.SSOStore.hash;\n\n let language = common.getIntlLanguage();\n user.language = language;\n\n user.url = instances[instances._self].finalize.replace('{hash}', user.hash);\n\n user.errorMessages = {\n error409: this.context.intl.formatMessage(this.errorMessages.error409),\n error404: this.context.intl.formatMessage(this.errorMessages.error404),\n error500: this.context.intl.formatMessage(this.errorMessages.error500)\n };\n\n this.context.executeAction(finalizeMergedUser, user);\n\n $(ReactDOM.findDOMNode(this.refs.ReviseUser_Modal)).modal('hide');\n\n return false;\n }\n\n checkEmail() {\n const email = this.refs.email.value;\n if (this.props.UserRegistrationStore.failures.usernameNotAllowed !== undefined || email !== '') {\n this.context.executeAction(checkEmail, {email: email});\n }\n }\n\n checkUsername() {\n const username = this.refs.username.value;\n if (this.props.UserRegistrationStore.failures.usernameNotAllowed !== undefined || username !== '') {\n this.context.executeAction(checkUsername, {username: username});\n }\n }\n\n render() {\n const signUpLabelStyle = {width: '150px'};\n\n const emailNotAllowed = this.props.UserRegistrationStore.failures.emailNotAllowed;\n let emailClasses = classNames({\n 'ui': true,\n 'field': true,\n 'inline': true,\n 'error': (emailNotAllowed !== undefined) ? emailNotAllowed : false\n });\n let emailIconClasses = classNames({\n 'icon': true,\n 'inverted circular red remove': (emailNotAllowed !== undefined) ? emailNotAllowed : false,\n 'inverted circular green checkmark': (emailNotAllowed !== undefined) ? !emailNotAllowed : false\n });\n let emailToolTipp = emailNotAllowed ? 'This E-Mail has already been used by someone else. Please choose another one.' : undefined;\n\n const usernameNotAllowed = this.props.UserRegistrationStore.failures.usernameNotAllowed;\n let usernameClasses = classNames({\n 'ui': true,\n 'field': true,\n 'inline': true,\n 'error': (usernameNotAllowed !== undefined) ? usernameNotAllowed : false\n });\n let usernameIconClasses = classNames({\n 'icon': true,\n 'inverted circular red remove': (usernameNotAllowed !== undefined) ? usernameNotAllowed : false,\n 'inverted circular green checkmark': (usernameNotAllowed !== undefined) ? !usernameNotAllowed : false\n });\n let usernameToolTipp = usernameNotAllowed ? 'This Username has already been used by someone else. Please choose another one.' : undefined;\n if (this.props.UserRegistrationStore.suggestedUsernames.length > 0) {\n usernameToolTipp += '\\n Here are some suggestions: ' + this.props.UserRegistrationStore.suggestedUsernames;\n }\n return (\n
    \n
    \n
    \n

    Validate user information

    \n

    Your account could not migrated automatically. In order to finialize the migration, please change the data which is already in use.

    \n

    Hint: if your email or username is already in use, it could be possible that you have already an stand-alone account on this SlideWiki instance. In this case close the window and do a sign in.

    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n
    \n \n \n
    \n
    \n
    Cancel
    \n
    \n
    \n
    \n );\n }\n}\n\nReviseUser.contextTypes = {\n executeAction: PropTypes.func.isRequired,\n intl: PropTypes.object.isRequired\n};\nReviseUser = connectToStores(ReviseUser, [UserRegistrationStore, SSOStore], (context, props) => {\n return {\n UserRegistrationStore: context.getStore(UserRegistrationStore).getState(),\n SSOStore: context.getStore(SSOStore).getState()\n };\n});\nexport default ReviseUser;\n"}}},{"rowIdx":1069,"cells":{"path":{"kind":"string","value":"Realization/frontend/czechidm-core/src/components/advanced/ProfileInfo/ProfileInfo.js"},"repo_name":{"kind":"string","value":"bcvsolutions/CzechIdMng"},"content":{"kind":"string","value":"import React from 'react';\nimport PropTypes from 'prop-types';\nimport { connect } from 'react-redux';\n//\nimport * as Basic from '../../basic';\nimport { ProfileManager } from '../../../redux';\nimport AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo';\nimport EntityInfo from '../EntityInfo/EntityInfo';\nimport TwoFactorAuthenticationTypeEnum from '../../../enums/TwoFactorAuthenticationTypeEnum';\n//\nconst manager = new ProfileManager();\n\n/**\n * Component for rendering information about identity profile.\n *\n * @author Radek Tomiška\n * @since 12.0.0\n */\nexport class ProfileInfo extends AbstractEntityInfo {\n\n getManager() {\n return manager;\n }\n\n showLink() {\n return false;\n }\n\n /**\n * Returns entity icon (null by default - icon will not be rendered)\n *\n * @param {object} entity\n */\n getEntityIcon() {\n return 'fa:cog';\n }\n\n getNiceLabel(entity) {\n const _entity = entity || this.getEntity();\n let label = this.i18n('entity.Profile._type');\n if (_entity && _entity._embedded && _entity._embedded.identity) {\n label = `${ label } - (${ _entity._embedded.identity.username })`;\n }\n return label;\n }\n\n /**\n * Returns popovers title\n *\n * @param {object} entity\n */\n getPopoverTitle() {\n return this.i18n('entity.Profile._type');\n }\n\n getTableChildren() {\n // component are used in #getPopoverContent => skip default column resolving\n return [\n ,\n \n ];\n }\n\n /**\n * Returns popover info content\n *\n * @param {array} table data\n */\n getPopoverContent(entity) {\n return [\n {\n label: this.i18n('entity.Identity._type'),\n value: (\n \n )\n },\n {\n label: this.i18n('entity.Profile.preferredLanguage.label'),\n value: entity.preferredLanguage\n },\n {\n label: this.i18n('entity.Profile.systemInformation.label'),\n value: (entity.systemInformation ? this.i18n('label.yes') : this.i18n('label.no'))\n },\n {\n label: this.i18n('entity.Profile.twoFactorAuthenticationType.label'),\n value: (\n \n )\n }\n ];\n }\n}\n\nProfileInfo.propTypes = {\n ...AbstractEntityInfo.propTypes,\n /**\n * Selected entity - has higher priority\n */\n entity: PropTypes.object,\n /**\n * Selected entity's id - entity will be loaded automatically\n */\n entityIdentifier: PropTypes.string,\n /**\n * Internal entity loaded by given identifier\n */\n _entity: PropTypes.object,\n _showLoading: PropTypes.bool\n};\nProfileInfo.defaultProps = {\n ...AbstractEntityInfo.defaultProps,\n entity: null,\n face: 'link',\n _showLoading: true\n};\n\nfunction select(state, component) {\n return {\n _entity: manager.getEntity(state, component.entityIdentifier),\n _showLoading: manager.isShowLoading(state, null, component.entityIdentifier)\n };\n}\nexport default connect(select)(ProfileInfo);\n"}}},{"rowIdx":1070,"cells":{"path":{"kind":"string","value":"app/components/App/App.js"},"repo_name":{"kind":"string","value":"Tonnu/workflows-ecs-ecr-demo"},"content":{"kind":"string","value":"import React from 'react';\n\nimport createStore from 'lib/createStore';\nimport { Provider } from 'react-redux';\n\nimport HelloApp from 'components/HelloApp/HelloApp';\n\nconst store = createStore();\n\nclass App extends React.Component {\n\n render() {\n return (\n \n \n \n );\n }\n}\n\nexport default App;\n"}}},{"rowIdx":1071,"cells":{"path":{"kind":"string","value":"src/containers/DevTools/DevTools.js"},"repo_name":{"kind":"string","value":"svsool/react-redux-universal-hot-example"},"content":{"kind":"string","value":"import React from 'react';\nimport { createDevTools } from 'redux-devtools';\nimport LogMonitor from 'redux-devtools-log-monitor';\nimport DockMonitor from 'redux-devtools-dock-monitor';\n\nexport default createDevTools(\n \n \n \n);\n"}}},{"rowIdx":1072,"cells":{"path":{"kind":"string","value":"app/javascript/mastodon/features/community_timeline/index.js"},"repo_name":{"kind":"string","value":"ebihara99999/mastodon"},"content":{"kind":"string","value":"import React from 'react';\nimport { connect } from 'react-redux';\nimport PropTypes from 'prop-types';\nimport StatusListContainer from '../ui/containers/status_list_container';\nimport Column from '../ui/components/column';\nimport {\n refreshTimeline,\n updateTimeline,\n deleteFromTimelines,\n connectTimeline,\n disconnectTimeline,\n} from '../../actions/timelines';\nimport { defineMessages, injectIntl, FormattedMessage } from 'react-intl';\nimport ColumnBackButtonSlim from '../../components/column_back_button_slim';\nimport createStream from '../../stream';\n\nconst messages = defineMessages({\n title: { id: 'column.community', defaultMessage: 'Local timeline' },\n});\n\nconst mapStateToProps = state => ({\n hasUnread: state.getIn(['timelines', 'community', 'unread']) > 0,\n streamingAPIBaseURL: state.getIn(['meta', 'streaming_api_base_url']),\n accessToken: state.getIn(['meta', 'access_token']),\n});\n\nlet subscription;\n\nclass CommunityTimeline extends React.PureComponent {\n\n static propTypes = {\n dispatch: PropTypes.func.isRequired,\n intl: PropTypes.object.isRequired,\n streamingAPIBaseURL: PropTypes.string.isRequired,\n accessToken: PropTypes.string.isRequired,\n hasUnread: PropTypes.bool,\n };\n\n componentDidMount () {\n const { dispatch, streamingAPIBaseURL, accessToken } = this.props;\n\n dispatch(refreshTimeline('community'));\n\n if (typeof subscription !== 'undefined') {\n return;\n }\n\n subscription = createStream(streamingAPIBaseURL, accessToken, 'public:local', {\n\n connected () {\n dispatch(connectTimeline('community'));\n },\n\n reconnected () {\n dispatch(connectTimeline('community'));\n },\n\n disconnected () {\n dispatch(disconnectTimeline('community'));\n },\n\n received (data) {\n switch(data.event) {\n case 'update':\n dispatch(updateTimeline('community', JSON.parse(data.payload)));\n break;\n case 'delete':\n dispatch(deleteFromTimelines(data.payload));\n break;\n }\n },\n\n });\n }\n\n componentWillUnmount () {\n // if (typeof subscription !== 'undefined') {\n // subscription.close();\n // subscription = null;\n // }\n }\n\n render () {\n const { intl, hasUnread } = this.props;\n\n return (\n \n \n } />\n \n );\n }\n\n}\n\nexport default connect(mapStateToProps)(injectIntl(CommunityTimeline));\n"}}},{"rowIdx":1073,"cells":{"path":{"kind":"string","value":"features/filmStrip/components/web/DominantSpeakerIndicator.js"},"repo_name":{"kind":"string","value":"jitsi/jitsi-meet-react"},"content":{"kind":"string","value":"import React, { Component } from 'react';\nimport Icon from 'react-fontawesome';\n\nimport { styles } from './styles';\n\n/**\n * Thumbnail badge showing that the participant is the dominant speaker in\n * the conference.\n */\nexport class DominantSpeakerIndicator extends Component {\n /**\n * Implements React's {@link Component#render()}.\n *\n * @inheritdoc\n */\n render() {\n return (\n
    \n \n
    \n );\n }\n}\n"}}},{"rowIdx":1074,"cells":{"path":{"kind":"string","value":"src/svg-icons/av/video-label.js"},"repo_name":{"kind":"string","value":"mtsandeep/material-ui"},"content":{"kind":"string","value":"import React from 'react';\nimport pure from 'recompose/pure';\nimport SvgIcon from '../../SvgIcon';\n\nlet AvVideoLabel = (props) => (\n \n \n \n);\nAvVideoLabel = pure(AvVideoLabel);\nAvVideoLabel.displayName = 'AvVideoLabel';\nAvVideoLabel.muiName = 'SvgIcon';\n\nexport default AvVideoLabel;\n"}}},{"rowIdx":1075,"cells":{"path":{"kind":"string","value":"examples/todomvc/containers/Root.js"},"repo_name":{"kind":"string","value":"dherault/redux"},"content":{"kind":"string","value":"import React, { Component } from 'react';\nimport TodoApp from './TodoApp';\nimport { createStore, combineReducers } from 'redux';\nimport { Provider } from 'react-redux';\nimport rootReducer from '../reducers';\n\nconst store = createStore(rootReducer);\n\nexport default class Root extends Component {\n render() {\n return (\n \n {() => }\n \n );\n }\n}\n"}}},{"rowIdx":1076,"cells":{"path":{"kind":"string","value":"packages/react-scripts/fixtures/kitchensink/src/features/syntax/AsyncAwait.js"},"repo_name":{"kind":"string","value":"timlogemann/create-react-app"},"content":{"kind":"string","value":"/**\n * Copyright (c) 2015-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport React, { Component } from 'react';\nimport PropTypes from 'prop-types';\n\nasync function load() {\n return [\n { id: 1, name: '1' },\n { id: 2, name: '2' },\n { id: 3, name: '3' },\n { id: 4, name: '4' },\n ];\n}\n\n/* eslint-disable */\n// Regression test for https://github.com/facebook/create-react-app/issues/3055\nconst x = async (\n /* prettier-ignore */\n y: void\n) => {\n const z = await y;\n};\n/* eslint-enable */\n\nexport default class extends Component {\n static propTypes = {\n onReady: PropTypes.func.isRequired,\n };\n\n constructor(props) {\n super(props);\n this.state = { users: [] };\n }\n\n async componentDidMount() {\n const users = await load();\n this.setState({ users });\n }\n\n componentDidUpdate() {\n this.props.onReady();\n }\n\n render() {\n return (\n
    \n {this.state.users.map(user => (\n
    {user.name}
    \n ))}\n
    \n );\n }\n}\n"}}},{"rowIdx":1077,"cells":{"path":{"kind":"string","value":"src/Components/SearchHeader.stories.js"},"repo_name":{"kind":"string","value":"elderfo/elderfo-react-native-components"},"content":{"kind":"string","value":"import React from 'react';\nimport { Text, View } from 'react-native';\nimport { storiesOf, action, linkTo, } from '@kadira/react-native-storybook';\n\nimport { Container, SearchHeader } from '../';\n\nstoriesOf('SearchHeader', module)\n .addDecorator(story => (\n \n {story()}\n \n ))\n .add('with left button', () => (\n \n ))\n .add('with right button', () => (\n \n ))\n .add('with both buttons', () => (\n \n ))\n .add('with custom placeholder', () => (\n \n ))\n .add('with a backgroundColor/foregroundColor', () => (\n \n ))"}}},{"rowIdx":1078,"cells":{"path":{"kind":"string","value":"examples/src/app.js"},"repo_name":{"kind":"string","value":"yonaichin/react-select"},"content":{"kind":"string","value":"/* eslint react/prop-types: 0 */\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport Select from 'react-select';\n\nimport Contributors from './components/Contributors';\nimport GithubUsers from './components/GithubUsers';\nimport CustomComponents from './components/CustomComponents';\nimport CustomRender from './components/CustomRender';\nimport Multiselect from './components/Multiselect';\nimport NumericSelect from './components/NumericSelect';\nimport Virtualized from './components/Virtualized';\nimport States from './components/States';\n\nReactDOM.render(\n\t
    \n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t{/*\n\t\t\n\t\t*/}\n\t
    ,\n\tdocument.getElementById('example')\n);\n"}}},{"rowIdx":1079,"cells":{"path":{"kind":"string","value":"src/app/components/team/TeamData/TeamDataComponent.js"},"repo_name":{"kind":"string","value":"meedan/check-web"},"content":{"kind":"string","value":"import React from 'react';\nimport PropTypes from 'prop-types';\nimport { FormattedMessage } from 'react-intl';\nimport Box from '@material-ui/core/Box';\nimport Button from '@material-ui/core/Button';\nimport Typography from '@material-ui/core/Typography';\nimport Card from '@material-ui/core/Card';\nimport CardContent from '@material-ui/core/CardContent';\nimport SettingsHeader from '../SettingsHeader';\nimport { ContentColumn } from '../../../styles/js/shared';\n\nconst TeamDataComponent = ({ dataReportUrl }) => (\n \n \n }\n subtitle={\n \n }\n helpUrl=\"https://help.checkmedia.org/en/articles/4511362\"\n />\n \n \n { dataReportUrl ?\n \n \n \n \n \n { window.open(dataReportUrl); }}\n >\n \n \n \n \n \n \n :\n \n \n \n \n \n ),\n }}\n />\n \n \n \n \n }\n \n \n \n);\n\nTeamDataComponent.defaultProps = {\n dataReportUrl: null,\n};\n\nTeamDataComponent.propTypes = {\n dataReportUrl: PropTypes.string, // or null\n};\n\nexport default TeamDataComponent;\n"}}},{"rowIdx":1080,"cells":{"path":{"kind":"string","value":"docs/src/NavMain.js"},"repo_name":{"kind":"string","value":"adampickeral/react-bootstrap"},"content":{"kind":"string","value":"import React from 'react';\nimport { Link } from 'react-router';\nimport Navbar from '../../src/Navbar';\nimport Nav from '../../src/Nav';\n\nconst NAV_LINKS = {\n 'introduction': {\n link: 'introduction',\n title: 'Introduction'\n },\n 'getting-started': {\n link: 'getting-started',\n title: 'Getting started'\n },\n 'components': {\n link: 'components',\n title: 'Components'\n },\n 'support': {\n link: 'support',\n title: 'Support'\n }\n};\n\nconst NavMain = React.createClass({\n propTypes: {\n activePage: React.PropTypes.string\n },\n\n render() {\n let brand = React-Bootstrap;\n let links = Object.keys(NAV_LINKS).map(this.renderNavItem).concat([\n
  • \n GitHub\n
  • \n ]);\n\n return (\n \n \n \n );\n },\n\n renderNavItem(linkName) {\n let link = NAV_LINKS[linkName];\n\n return (\n
  • \n {link.title}\n
  • \n );\n }\n});\n\nexport default NavMain;\n"}}},{"rowIdx":1081,"cells":{"path":{"kind":"string","value":"src/admin/BedChart.js"},"repo_name":{"kind":"string","value":"ocelotconsulting/global-hack-6"},"content":{"kind":"string","value":"/* eslint no-new: \"off\" */\nimport React from 'react'\nimport { v4 } from 'uuid'\nimport ChartKey from './ChartKey'\nimport Row from 'react-bootstrap/lib/Row'\nimport Col from 'react-bootstrap/lib/Col'\nimport ChartistGraph from 'react-chartist'\n\nexport default class BedChart extends React.Component {\n constructor(props) {\n super(props)\n this.state = {\n id: `chart_${v4().replace(/-/g, '')}`\n }\n }\n\n render() {\n const { total, available, pending } = this.props\n const data = {\n series: [total - available - pending, pending, available]\n }\n\n const options = {\n startAngle: 270,\n showLabel: false\n }\n\n return (\n
    \n \n \n \n \n \n \n \n \n
    \n )\n }\n}\n"}}},{"rowIdx":1082,"cells":{"path":{"kind":"string","value":"src/components/auth/accountpage.js"},"repo_name":{"kind":"string","value":"Hommasoft/wappuapp-adminpanel"},"content":{"kind":"string","value":"import React, { Component } from 'react';\nimport { Field, reduxForm } from 'redux-form';\nimport { connect } from 'react-redux';\n\nimport * as Auth from '../../actions/auth';\n\nclass AccountPage extends Component {\n handleFormSubmit({ newpassword, oldpassword }) {\n this.props.changepassword({ newpassword, oldpassword });\n }\n\n renderError() {\n if (this.props.errorMessage) {\n console.log(this.props.errorMessage);\n return
    {this.props.errorMessage}
    ;\n }\n }\n\n renderField({ input, label, type, meta: { error } }) {\n return (\n
    \n \n
    \n \n {error && {error}}\n
    \n
    \n );\n }\n\n render() {\n const { handleSubmit } = this.props;\n var accountType = localStorage.getItem('admin');\n if (accountType === 'true') {\n accountType = 'admin';\n } else {\n accountType = 'moderator';\n }\n return (\n
    \n
    \n

    User details

    \n Email: {localStorage.getItem('email')}
    \n Account type: {accountType}
    \n Activated: {localStorage.getItem('activated')}
    \n
    \n
    \n
    \n Change password\n
    \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n {this.renderError()}\n \n
    \n
    \n
    \n );\n }\n}\n\nconst validate = values => {\n const errors = {};\n //if (values.newpassword && values.newpassword.length < 8) {\n // errors.newpassword = 'Password has to be atleast 8 characters long'\n //}\n if (values.newpassword && values.oldpassword === values.newpassword) {\n errors.newpassword = 'New password can not be the same as old one';\n }\n if (values.newpasswordagain && values.newpassword !== values.newpasswordagain) {\n errors.newpasswordagain = 'New passwords need to match';\n }\n return errors;\n};\n\nconst mapStateToProps = state => {\n return { errorMessage: state.auth.error };\n};\n\nexport default reduxForm({\n form: 'auth',\n validate\n})(connect(mapStateToProps, Auth)(AccountPage));\n"}}},{"rowIdx":1083,"cells":{"path":{"kind":"string","value":"src/plugins/position/components/SpacerRow.js"},"repo_name":{"kind":"string","value":"joellanciaux/Griddle"},"content":{"kind":"string","value":"import React, { Component } from 'react';\nimport PropTypes from 'prop-types';\nimport { connect } from '../../../utils/griddleConnect';\nimport compose from 'recompose/compose';\nimport mapProps from 'recompose/mapProps';\nimport getContext from 'recompose/getContext';\nimport withHandlers from 'recompose/withHandlers';\n\nconst spacerRow = compose(\n getContext({\n selectors: PropTypes.object,\n }),\n connect((state, props) => {\n const { topSpacerSelector, bottomSpacerSelector } = props.selectors;\n const { placement } = props;\n\n return {\n spacerHeight: placement === 'top' ? topSpacerSelector(state, props) : bottomSpacerSelector(state, props),\n };\n }),\n mapProps(props => ({\n placement: props.placement,\n spacerHeight: props.spacerHeight,\n }))\n)(class extends Component {\n static propTypes = {\n placement: PropTypes.string,\n spacerHeight: PropTypes.number,\n }\n static defaultProps = {\n placement: 'top'\n }\n\n // shouldComponentUpdate(nextProps) {\n // const { currentPosition: oldPosition, placement: oldPlacement } = this.props;\n // const { currentPosition, placement } = nextProps;\n //\n // return oldPosition !== currentPosition || oldPlacement !== placement;\n // }\n\n render() {\n const { placement, spacerHeight } = this.props;\n let spacerRowStyle = {\n height: `${spacerHeight}px`,\n };\n\n return (\n \n );\n }\n});\n\nexport default spacerRow;\n"}}},{"rowIdx":1084,"cells":{"path":{"kind":"string","value":"node_modules/react-bootstrap/es/ModalBody.js"},"repo_name":{"kind":"string","value":"firdiansyah/crud-req"},"content":{"kind":"string","value":"import _extends from 'babel-runtime/helpers/extends';\nimport _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';\nimport _classCallCheck from 'babel-runtime/helpers/classCallCheck';\nimport _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';\nimport _inherits from 'babel-runtime/helpers/inherits';\nimport classNames from 'classnames';\nimport React from 'react';\nimport elementType from 'react-prop-types/lib/elementType';\n\nimport { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';\n\nvar propTypes = {\n componentClass: elementType\n};\n\nvar defaultProps = {\n componentClass: 'div'\n};\n\nvar ModalBody = function (_React$Component) {\n _inherits(ModalBody, _React$Component);\n\n function ModalBody() {\n _classCallCheck(this, ModalBody);\n\n return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));\n }\n\n ModalBody.prototype.render = function render() {\n var _props = this.props,\n Component = _props.componentClass,\n className = _props.className,\n props = _objectWithoutProperties(_props, ['componentClass', 'className']);\n\n var _splitBsProps = splitBsProps(props),\n bsProps = _splitBsProps[0],\n elementProps = _splitBsProps[1];\n\n var classes = getClassSet(bsProps);\n\n return React.createElement(Component, _extends({}, elementProps, {\n className: classNames(className, classes)\n }));\n };\n\n return ModalBody;\n}(React.Component);\n\nModalBody.propTypes = propTypes;\nModalBody.defaultProps = defaultProps;\n\nexport default bsClass('modal-body', ModalBody);"}}},{"rowIdx":1085,"cells":{"path":{"kind":"string","value":"imports/ui/components/Routes/Authenticated.js"},"repo_name":{"kind":"string","value":"haraneesh/mydev"},"content":{"kind":"string","value":"import React from 'react';\nimport PropTypes from 'prop-types';\nimport { Route, Redirect } from 'react-router-dom';\n\n/*\nconst Authenticated = ({ layout: Layout, roles, authenticated, component, ...rest }) => (\n (\n authenticated ?\n (\n {(React.createElement(component, { ...props, authenticated, ...rest }))}\n )\n :\n ()\n )}\n />\n);\n*/\n\nconst Authenticated = ({\n layout: Layout, roles, authenticated, component: Component, ...rest\n}) => (\n (\n authenticated\n ? (\n \n \n \n )\n : ()\n )}\n />\n);\n\nAuthenticated.propTypes = {\n routeName: PropTypes.string.isRequired,\n roles: PropTypes.array.isRequired,\n authenticated: PropTypes.bool.isRequired,\n component: PropTypes.func.isRequired,\n layout: PropTypes.node.isRequired,\n};\n\nexport default Authenticated;\n"}}},{"rowIdx":1086,"cells":{"path":{"kind":"string","value":"packages/mcs-lite-ui/src/DataChannelAdapter/DataChannelAdapter.example.js"},"repo_name":{"kind":"string","value":"MCS-Lite/mcs-lite"},"content":{"kind":"string","value":"import React from 'react';\nimport styled from 'styled-components';\nimport { storiesOf } from '@storybook/react';\nimport { withInfo } from '@storybook/addon-info';\nimport { action } from '@storybook/addon-actions';\nimport DataChannelCard from '../DataChannelCard';\nimport DATA_CHANNELS from './API';\nimport DataChannelAdapter from '.';\n\nconst CardWrapper = styled.div`\n display: flex;\n flex-wrap: wrap;\n\n > * {\n height: initial;\n padding: 8px 16px;\n margin: 4px;\n flex-basis: 100%;\n }\n\n > [data-width~=' half'] {\n flex-grow: 1;\n flex-basis: 40%;\n }\n`;\n\nstoriesOf('DataChannelAdapter', module).add(\n 'API',\n withInfo({\n text: `\n ~~~js\n type Event = {\n type: 'SUBMIT'|'CHANGE'|'CLEAR', // event type\n id: string, // data channel id\n values: { // datapoint values\n value: ?string|number,\n period: ?number,\n },\n }\n\n type DCEventHandler = DCEvent => void\n ~~~\n `,\n\n inline: true,\n })(() => (\n \n {DATA_CHANNELS.map(dataChannel => (\n Link}\n >\n \n \n ))}\n \n )),\n);\n"}}},{"rowIdx":1087,"cells":{"path":{"kind":"string","value":"src/docs/components/header/HeaderExamplesDoc.js"},"repo_name":{"kind":"string","value":"grommet/grommet-docs"},"content":{"kind":"string","value":"// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP\n\nimport React, { Component } from 'react';\nimport Header from 'grommet/components/Header';\nimport Title from 'grommet/components/Title';\nimport Search from 'grommet/components/Search';\nimport Menu from 'grommet/components/Menu';\nimport Box from 'grommet/components/Box';\nimport Anchor from 'grommet/components/Anchor';\nimport ActionsIcon from 'grommet/components/icons/base/Actions';\nimport InteractiveExample from '../../../components/InteractiveExample';\n\nconst PROPS_SCHEMA = {\n fixed: { value: true },\n float: { value: true },\n size: { options: ['small', 'medium', 'large', 'xlarge'] },\n splash: { value: true }\n};\n\nconst CONTENTS_SCHEMA = {\n title: { value: Sample Title, initial: true },\n search: { value: (\n \n ), initial: true },\n menu: { value: (\n } dropAlign={{right: 'right'}}>\n First\n Second\n Third\n \n ), initial: true }\n};\n\nexport default class HeaderExamplesDoc extends Component {\n\n constructor () {\n super();\n this.state = { contents: {}, elementProps: {} };\n }\n\n render () {\n let { contents, elementProps } = this.state;\n\n const element = (\n
    \n {contents.title}\n \n {contents.search}\n {contents.menu}\n \n
    \n );\n\n return (\n {\n this.setState({ elementProps, contents });\n }} />\n );\n }\n};\n"}}},{"rowIdx":1088,"cells":{"path":{"kind":"string","value":"packages/benchmarks/src/index.js"},"repo_name":{"kind":"string","value":"css-components/styled-components"},"content":{"kind":"string","value":"/* eslint-disable no-param-reassign */\n/* global document */\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './app/App';\nimport impl from './impl';\nimport Tree from './cases/Tree';\nimport SierpinskiTriangle from './cases/SierpinskiTriangle';\n\nconst implementations = impl;\nconst packageNames = Object.keys(implementations);\n\nconst createTestBlock = fn => {\n return packageNames.reduce((testSetups, packageName) => {\n const { name, components, version } = implementations[packageName];\n const { Component, getComponentProps, sampleCount, Provider, benchmarkType } = fn(components);\n\n testSetups[packageName] = {\n Component,\n getComponentProps,\n sampleCount,\n Provider,\n benchmarkType,\n version,\n name,\n };\n return testSetups;\n }, {});\n};\n\nconst tests = {\n 'Mount deep tree': createTestBlock(components => ({\n benchmarkType: 'mount',\n Component: Tree,\n getComponentProps: () => ({ breadth: 2, components, depth: 7, id: 0, wrap: 1 }),\n Provider: components.Provider,\n sampleCount: 500,\n })),\n 'Mount wide tree': createTestBlock(components => ({\n benchmarkType: 'mount',\n Component: Tree,\n getComponentProps: () => ({ breadth: 6, components, depth: 3, id: 0, wrap: 2 }),\n Provider: components.Provider,\n sampleCount: 500,\n })),\n 'Update dynamic styles': createTestBlock(components => ({\n benchmarkType: 'update',\n Component: SierpinskiTriangle,\n getComponentProps: ({ cycle }) => {\n return { components, s: 200, renderCount: cycle, x: 0, y: 0 };\n },\n Provider: components.Provider,\n sampleCount: 1000,\n })),\n};\n\nReactDOM.render(, document.querySelector('.root'));\n"}}},{"rowIdx":1089,"cells":{"path":{"kind":"string","value":"app/routes/routes/PaySuccess/components/PaySuccess.view.js"},"repo_name":{"kind":"string","value":"bugknightyyp/leyizhu"},"content":{"kind":"string","value":"import React from 'react'\nimport {observer} from 'mobx-react'\nimport {Route, Link} from 'react-router-dom'\nimport {IMAGE_DIR, TOKEN, GET_HOTEL_INFO, RESPONSE_CODE_SUCCESS} from 'macros'\nimport {setParamsToURL, dateToZh} from 'utils'\nimport './paySuccess.less'\n\nexport default observer(\n (props) => (\n
    \n
    \n \n

    支付成功

    \n
    {props.store.hotelName}
    \n
    {`酒店地址:${props.store.address}`}
    \n 前往酒店\n
    \n
    \n
    如何入住
    \n

    1.前往酒店,并找到自助入住登记机
    \n 2.在自助机登记证件,并进行脸部识别
    \n 3.收取入住短信通知(含房间号和密码)
    \n *房门还可通过网络开锁功能开启

    \n
    \n
    \n 根据公安部法律规定,住宿需登记身份证信息\n
    \n\n\n\n\n
    \n )\n)\n"}}},{"rowIdx":1090,"cells":{"path":{"kind":"string","value":"frontend/src/Factura/FacturaTable.js"},"repo_name":{"kind":"string","value":"GAumala/Facturacion"},"content":{"kind":"string","value":"import React from 'react';\nimport {\n Table,\n TableBody,\n TableHeader,\n TableHeaderColumn,\n TableRow,\n TableRowColumn\n} from 'material-ui/Table';\nimport TextField from 'material-ui/TextField';\nimport IconButton from 'material-ui/IconButton';\nimport Delete from 'material-ui/svg-icons/action/delete';\nimport Math from 'facturacion_common/src/Math.js';\n\nconst black54p = '#757575';\nconst noPaddingStyle = { padding: '0px' };\n\nconst RenderTableHeader = props => {\n let regSanCol = (\n \n Reg. Santario\n \n );\n let loteCol = (\n \n Lote\n \n );\n let fechaExpCol = (\n \n Fecha Exp.\n \n );\n\n if (props.isExamen) {\n //ocultar columnas que no se usan en examenes\n regSanCol = null;\n loteCol = null;\n fechaExpCol = null;\n }\n\n return (\n \n \n \n #\n \n {regSanCol}\n \n Nombre\n \n {loteCol}\n \n Cant.\n \n {fechaExpCol}\n \n Precio\n \n \n Importe\n \n \n \n \n );\n};\n\nexport default class FacturaTable extends React.Component {\n renderRow = (facturable, i) => {\n const { isExamen, onFacturableChanged, onFacturableDeleted } = this.props;\n\n let regSanCol = (\n \n {facturable.codigo}\n \n );\n let loteCol = (\n \n {\n onFacturableChanged(i, 'lote', event.target.value);\n }}\n />\n \n );\n let fechaExpCol = (\n \n {\n onFacturableChanged(i, 'fechaExp', date);\n }}\n />\n \n );\n\n if (isExamen) {\n //ocultar columnas que no se usan en examenes\n regSanCol = null;\n loteCol = null;\n fechaExpCol = null;\n }\n\n return (\n \n \n {i + 1}\n \n\n {regSanCol}\n\n \n {facturable.nombre}\n \n\n {loteCol}\n\n \n {\n onFacturableChanged(i, 'count', event.target.value);\n }}\n />\n \n\n {fechaExpCol}\n\n \n ${' '}\n {\n onFacturableChanged(i, 'precioVenta', event.target.value);\n }}\n inputStyle={{ fontSize: '13px' }}\n />\n \n\n \n \n $ {Math.calcularImporteFacturable(facturable)}\n \n \n\n \n onFacturableDeleted(i)}>\n \n \n \n \n );\n };\n\n render() {\n return (\n \n {RenderTableHeader(this.props)}\n \n {this.props.items.map(this.renderRow)}\n \n
    \n );\n }\n}\n\nFacturaTable.propTypes = {\n isExamen: React.PropTypes.bool,\n items: React.PropTypes.array.isRequired,\n onFacturableChanged: React.PropTypes.func.isRequired,\n onFacturableDeleted: React.PropTypes.func.isRequired\n};\n\nFacturaTable.defaultProps = {\n isExamen: false\n};\n"}}},{"rowIdx":1091,"cells":{"path":{"kind":"string","value":"lib/routes.js"},"repo_name":{"kind":"string","value":"codevlabs/filepizza"},"content":{"kind":"string","value":"import React from 'react'\nimport { Route, DefaultRoute, NotFoundRoute, RouteHandler } from 'react-router'\n\nimport App from './components/App'\nimport DownloadPage from './components/DownloadPage'\nimport UploadPage from './components/UploadPage'\nimport ErrorPage from './components/ErrorPage'\n\nexport default (\n \n \n \n \n \n \n)\n"}}},{"rowIdx":1092,"cells":{"path":{"kind":"string","value":"2016-04-declarative-charts/assets/highcharts.js"},"repo_name":{"kind":"string","value":"rosko/slides"},"content":{"kind":"string","value":"import React from 'react';\nimport IframeExample from '../components/IframeExample';\n\nfunction Highcharts() {\n return \n \n \n \n\n
    \n\n`}/>;\n}\n\nHighcharts.displayName = 'Highcharts';\n\nmodule.exports = Highcharts;\n"}}},{"rowIdx":1093,"cells":{"path":{"kind":"string","value":"node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js"},"repo_name":{"kind":"string","value":"Rmutek/rmutek.github.io"},"content":{"kind":"string","value":"import React from 'react';\nimport { render } from 'react-dom';\n// It's important to not define HelloWorld component right in this file\n// because in that case it will do full page reload on change\nimport HelloWorld from './HelloWorld.jsx';\n\nrender(, document.getElementById('react-root'));\n"}}},{"rowIdx":1094,"cells":{"path":{"kind":"string","value":"packages/ui/src/components/Sprinkle.stories.js"},"repo_name":{"kind":"string","value":"dino-dna/donut"},"content":{"kind":"string","value":"import React from 'react'\nimport { storiesOf } from '@storybook/react'\nimport Sprinkle from './Sprinkle'\n\nexport default storiesOf('Sprinkle', module)\n.add('basic', () => {\n return (\n \n \n \n )\n})\n.add('rotated', () => {\n return (\n \n \n \n )\n})\n.add('rotated & translated', () => {\n return (\n \n \n \n \n \n )\n})\n"}}},{"rowIdx":1095,"cells":{"path":{"kind":"string","value":"actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js"},"repo_name":{"kind":"string","value":"JeeLiu/actor-platform"},"content":{"kind":"string","value":"import _ from 'lodash';\n\nimport React from 'react';\nimport { PureRenderMixin } from 'react/addons';\n\nimport DialogActionCreators from 'actions/DialogActionCreators';\n\nimport LoginStore from 'stores/LoginStore';\n\nimport AvatarItem from 'components/common/AvatarItem.react';\n\nconst GroupProfileMembers = React.createClass({\n propTypes: {\n groupId: React.PropTypes.number,\n members: React.PropTypes.array.isRequired\n },\n\n mixins: [PureRenderMixin],\n\n onClick(id) {\n DialogActionCreators.selectDialogPeerUser(id);\n },\n\n onKickMemberClick(groupId, userId) {\n DialogActionCreators.kickMember(groupId, userId);\n },\n\n render() {\n let groupId = this.props.groupId;\n let members = this.props.members;\n let myId = LoginStore.getMyId();\n\n\n let membersList = _.map(members, (member, index) => {\n let controls;\n let canKick = member.canKick;\n\n if (canKick === true && member.peerInfo.peer.id !== myId) {\n controls = (\n
    \n Kick\n
    \n );\n }\n\n return (\n
  • \n \n \n \n\n \n
  • \n );\n }, this);\n\n return (\n
      \n
    • {members.length} members
    • \n {membersList}\n
    \n );\n }\n});\n\nexport default GroupProfileMembers;\n"}}},{"rowIdx":1096,"cells":{"path":{"kind":"string","value":"src/DataTables/DataTablesTableBody.js"},"repo_name":{"kind":"string","value":"hyojin/material-ui-datatables"},"content":{"kind":"string","value":"import React from 'react';\nimport PropTypes from 'prop-types';\nimport {TableBody} from 'material-ui/Table';\nimport ClickAwayListener from 'material-ui/internal/ClickAwayListener';\n\nclass DataTablesTableBody extends TableBody {\n static muiName = 'TableBody';\n\n static propTypes = {\n /**\n * @ignore\n * Set to true to indicate that all rows should be selected.\n */\n allRowsSelected: PropTypes.bool,\n /**\n * Children passed to table body.\n */\n children: PropTypes.node,\n /**\n * The css class name of the root element.\n */\n className: PropTypes.string,\n /**\n * Controls whether or not to deselect all selected\n * rows after clicking outside the table.\n */\n deselectOnClickaway: PropTypes.bool,\n /**\n * Controls the display of the row checkbox. The default value is true.\n */\n displayRowCheckbox: PropTypes.bool,\n /**\n * @ignore\n * If true, multiple table rows can be selected.\n * CTRL/CMD+Click and SHIFT+Click are valid actions.\n * The default value is false.\n */\n multiSelectable: PropTypes.bool,\n /**\n * @ignore\n * Callback function for when a cell is clicked.\n */\n onCellClick: PropTypes.func,\n /**\n * @ignore\n * Customized handler\n * Callback function for when a cell is double clicked.\n */\n onCellDoubleClick: PropTypes.func,\n /**\n * @ignore\n * Called when a table cell is hovered. rowNumber\n * is the row number of the hovered row and columnId\n * is the column number or the column key of the cell.\n */\n onCellHover: PropTypes.func,\n /**\n * @ignore\n * Called when a table cell is no longer hovered.\n * rowNumber is the row number of the row and columnId\n * is the column number or the column key of the cell.\n */\n onCellHoverExit: PropTypes.func,\n /**\n * @ignore\n * Called when a table row is hovered.\n * rowNumber is the row number of the hovered row.\n */\n onRowHover: PropTypes.func,\n /**\n * @ignore\n * Called when a table row is no longer\n * hovered. rowNumber is the row number of the row\n * that is no longer hovered.\n */\n onRowHoverExit: PropTypes.func,\n /**\n * @ignore\n * Called when a row is selected. selectedRows is an\n * array of all row selections. IF all rows have been selected,\n * the string \"all\" will be returned instead to indicate that\n * all rows have been selected.\n */\n onRowSelection: PropTypes.func,\n /**\n * Controls whether or not the rows are pre-scanned to determine\n * initial state. If your table has a large number of rows and\n * you are experiencing a delay in rendering, turn off this property.\n */\n preScanRows: PropTypes.bool,\n /**\n * @ignore\n * If true, table rows can be selected. If multiple\n * row selection is desired, enable multiSelectable.\n * The default value is true.\n */\n selectable: PropTypes.bool,\n /**\n * If true, table rows will be highlighted when\n * the cursor is hovering over the row. The default\n * value is false.\n */\n showRowHover: PropTypes.bool,\n /**\n * If true, every other table row starting\n * with the first row will be striped. The default value is false.\n */\n stripedRows: PropTypes.bool,\n /**\n * Override the inline-styles of the root element.\n */\n style: PropTypes.object,\n };\n\n createRows() {\n const numChildren = React.Children.count(this.props.children);\n let rowNumber = 0;\n const handlers = {\n onCellClick: this.onCellClick,\n onCellDoubleClick: this.onCellDoubleClick,\n onCellHover: this.onCellHover,\n onCellHoverExit: this.onCellHoverExit,\n onRowHover: this.onRowHover,\n onRowHoverExit: this.onRowHoverExit,\n onRowClick: this.onRowClick,\n };\n\n return React.Children.map(this.props.children, (child) => {\n if (React.isValidElement(child)) {\n const props = {\n hoverable: this.props.showRowHover,\n selected: this.isRowSelected(rowNumber),\n striped: this.props.stripedRows && (rowNumber % 2 === 0),\n rowNumber: rowNumber++,\n };\n\n if (rowNumber === numChildren) {\n props.displayBorder = false;\n }\n\n const children = [\n this.createRowCheckboxColumn(props),\n ];\n\n React.Children.forEach(child.props.children, (child) => {\n children.push(child);\n });\n\n return React.cloneElement(child, {...props, ...handlers}, children);\n }\n });\n }\n\n onCellDoubleClick = (event, rowNumber, columnNumber) => {\n event.stopPropagation();\n if (this.props.onCellDoubleClick) {\n this.props.onCellDoubleClick(rowNumber, this.getColumnId(columnNumber), event);\n }\n };\n\n render() {\n const {\n style,\n allRowsSelected, // eslint-disable-line no-unused-vars\n multiSelectable, // eslint-disable-line no-unused-vars\n onCellClick, // eslint-disable-line no-unused-vars\n onCellDoubleClick, // eslint-disable-line no-unused-vars\n onCellHover, // eslint-disable-line no-unused-vars\n onCellHoverExit, // eslint-disable-line no-unused-vars\n onRowHover, // eslint-disable-line no-unused-vars\n onRowHoverExit, // eslint-disable-line no-unused-vars\n onRowSelection, // eslint-disable-line no-unused-vars\n selectable, // eslint-disable-line no-unused-vars\n deselectOnClickaway, // eslint-disable-line no-unused-vars\n showRowHover, // eslint-disable-line no-unused-vars\n stripedRows, // eslint-disable-line no-unused-vars\n displayRowCheckbox, // eslint-disable-line no-unused-vars\n preScanRows, // eslint-disable-line no-unused-vars\n ...other\n } = this.props;\n\n const {prepareStyles} = this.context.muiTheme;\n\n return (\n \n \n {this.createRows()}\n \n \n );\n }\n}\n\nexport default DataTablesTableBody;\n"}}},{"rowIdx":1097,"cells":{"path":{"kind":"string","value":"src/svg-icons/action/settings-backup-restore.js"},"repo_name":{"kind":"string","value":"mit-cml/iot-website-source"},"content":{"kind":"string","value":"import React from 'react';\nimport pure from 'recompose/pure';\nimport SvgIcon from '../../SvgIcon';\n\nlet ActionSettingsBackupRestore = (props) => (\n \n \n \n);\nActionSettingsBackupRestore = pure(ActionSettingsBackupRestore);\nActionSettingsBackupRestore.displayName = 'ActionSettingsBackupRestore';\nActionSettingsBackupRestore.muiName = 'SvgIcon';\n\nexport default ActionSettingsBackupRestore;\n"}}},{"rowIdx":1098,"cells":{"path":{"kind":"string","value":"server/middleware/reactApplication/index.js"},"repo_name":{"kind":"string","value":"dariobanfi/react-avocado-starter"},"content":{"kind":"string","value":"import React from 'react';\nimport Helmet from 'react-helmet';\nimport { renderToString, renderToStaticMarkup } from 'react-dom/server';\nimport { StaticRouter } from 'react-router-dom';\nimport { ServerStyleSheet } from 'styled-components';\n\nimport config from '../../../config';\n\nimport ServerHTML from './ServerHTML';\nimport Application from '../../../app/components/Application';\n\nexport default function reactApplicationMiddleware(request, response) {\n // Ensure a nonce has been provided to us.\n // See the server/middleware/security.js for more info.\n if (typeof response.locals.nonce !== 'string') {\n throw new Error('A \"nonce\" value has not been attached to the response');\n }\n const nonce = response.locals.nonce;\n\n // It's possible to disable SSR, which can be useful in development mode.\n // In this case traditional client side only rendering will occur.\n if (config('disableSSR')) {\n if (process.env.BUILD_FLAG_IS_DEV === 'true') {\n // eslint-disable-next-line no-console\n console.log('==> Handling react route without SSR');\n }\n // SSR is disabled so we will return an \"empty\" html page and\n // rely on the client to initialize and render the react application.\n const html = renderToStaticMarkup();\n response.status(200).send(`${html}`);\n return;\n }\n\n // Create a context for , which will allow us to\n // query for the results of the render.\n const reactRouterContext = {};\n\n // Declare our React application.\n const app = (\n \n \n \n );\n\n\n const appString = renderToString(app);\n\n // Generate the html response.\n const html = renderToStaticMarkup(\n ,\n );\n\n // Check if the router context contains a redirect, if so we need to set\n // the specific status and redirect header and end the response.\n if (reactRouterContext.url) {\n response.status(302).setHeader('Location', reactRouterContext.url);\n response.end();\n return;\n }\n\n response\n .status(\n reactRouterContext.missed ? 404 : 200,\n )\n .send(`${html}`);\n}\n"}}},{"rowIdx":1099,"cells":{"path":{"kind":"string","value":"src/components/Feedback/Feedback.js"},"repo_name":{"kind":"string","value":"seriflafont/react-starter-kit"},"content":{"kind":"string","value":"/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */\n\nimport React, { Component } from 'react';\nimport styles from './Feedback.css';\nimport withStyles from '../../decorators/withStyles';\n\n@withStyles(styles)\nclass Feedback extends Component {\n\n render() {\n return (\n \n );\n }\n\n}\n\nexport default Feedback;\n"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":10,"numItemsPerPage":100,"numTotalItems":410387,"offset":1000,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjQ0MjYyNSwic3ViIjoiL2RhdGFzZXRzL2hjaGF1dHJhbi9yZWFjdF9yZXBvcyIsImV4cCI6MTc1NjQ0NjIyNSwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.42lFK6vJ7RPP4UjgjhVif4xFS6SpdyJW7NsupFibGYMq4X11mUFy9l_hcHR9qAzuD85esQfjhgXrrlkBMMA1Aw","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    path
    stringlengths
    5
    195
    repo_name
    stringlengths
    5
    79
    content
    stringlengths
    25
    1.01M
    src/router.js
    gusdewa/MultiStores
    import React from 'react'; /* eslint-disable */ function decodeParam(val) { if (!(typeof val === 'string' || val.length === 0)) { return val; } try { return decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { err.message = `Failed to decode param '${val}'`; err.status = 400; } throw err; } } // Match the provided URL path pattern to an actual URI string. For example: // matchURI({ path: '/posts/:id' }, '/dummy') => null // matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 } function matchURI(route, path) { const match = route.pattern.exec(path); if (!match) { return null; } const params = Object.create(null); for (let i = 1; i < match.length; i++) { params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined; } return params; } // Find the route matching the specified location (context), fetch the required data, // instantiate and return a React component function resolve(routes, context) { for (const route of routes) { const params = matchURI(route, context.error ? '/error' : context.pathname); if (!params) { continue; } // Check if the route has any data requirements, for example: // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' } if (route.data) { // Load page component and all required data in parallel const keys = Object.keys(route.data); return Promise.all([ route.load(), ...keys.map(key => { const query = route.data[key]; const method = query.substring(0, query.indexOf(' ')); // GET let url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id // TODO: Optimize Object.keys(params).forEach((k) => { url = url.replace(`${k}`, params[k]); }); return fetch(url, { method }).then(resp => resp.json()); }), ]).then(([Page, ...data]) => { const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {}); return <Page route={{ ...route, params }} error={context.error} {...props} />; }); } return route.load().then(Page => <Page route={{ ...route, params }} error={context.error} />); } const error = new Error('Page not found'); error.status = 404; return Promise.reject(error); } export default { resolve };
    pages/about.js
    willopez/project-seed
    import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import Layout from '../components/layout'; export default class About extends Component { static async getInitialProps({ req }) { if (req) { Helmet.renderStatic(); } return { title: 'About' }; } static propTypes = { title: PropTypes.string.isRequired }; render() { const { title } = this.props; return ( <Layout> <Helmet title={title} /> <h1 className="cover-heading">About</h1> <p className="lead"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </Layout> ); } }
    node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
    thuongho/dream-machine
    import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
    src/components/chrome/Chrome.js
    casesandberg/react-color
    import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Saturation, Hue, Alpha, Checkboard } from '../common' import ChromeFields from './ChromeFields' import ChromePointer from './ChromePointer' import ChromePointerCircle from './ChromePointerCircle' export const Chrome = ({ width, onChange, disableAlpha, rgb, hsl, hsv, hex, renderers, styles: passedStyles = {}, className = '', defaultView }) => { const styles = reactCSS(merge({ 'default': { picker: { width, background: '#fff', borderRadius: '2px', boxShadow: '0 0 2px rgba(0,0,0,.3), 0 4px 8px rgba(0,0,0,.3)', boxSizing: 'initial', fontFamily: 'Menlo', }, saturation: { width: '100%', paddingBottom: '55%', position: 'relative', borderRadius: '2px 2px 0 0', overflow: 'hidden', }, Saturation: { radius: '2px 2px 0 0', }, body: { padding: '16px 16px 12px', }, controls: { display: 'flex', }, color: { width: '32px', }, swatch: { marginTop: '6px', width: '16px', height: '16px', borderRadius: '8px', position: 'relative', overflow: 'hidden', }, active: { absolute: '0px 0px 0px 0px', borderRadius: '8px', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.1)', background: `rgba(${ rgb.r }, ${ rgb.g }, ${ rgb.b }, ${ rgb.a })`, zIndex: '2', }, toggles: { flex: '1', }, hue: { height: '10px', position: 'relative', marginBottom: '8px', }, Hue: { radius: '2px', }, alpha: { height: '10px', position: 'relative', }, Alpha: { radius: '2px', }, }, 'disableAlpha': { color: { width: '22px', }, alpha: { display: 'none', }, hue: { marginBottom: '0px', }, swatch: { width: '10px', height: '10px', marginTop: '0px', }, }, }, passedStyles), { disableAlpha }) return ( <div style={ styles.picker } className={ `chrome-picker ${ className }` }> <div style={ styles.saturation }> <Saturation style={ styles.Saturation } hsl={ hsl } hsv={ hsv } pointer={ ChromePointerCircle } onChange={ onChange } /> </div> <div style={ styles.body }> <div style={ styles.controls } className="flexbox-fix"> <div style={ styles.color }> <div style={ styles.swatch }> <div style={ styles.active } /> <Checkboard renderers={ renderers } /> </div> </div> <div style={ styles.toggles }> <div style={ styles.hue }> <Hue style={ styles.Hue } hsl={ hsl } pointer={ ChromePointer } onChange={ onChange } /> </div> <div style={ styles.alpha }> <Alpha style={ styles.Alpha } rgb={ rgb } hsl={ hsl } pointer={ ChromePointer } renderers={ renderers } onChange={ onChange } /> </div> </div> </div> <ChromeFields rgb={ rgb } hsl={ hsl } hex={ hex } view={ defaultView } onChange={ onChange } disableAlpha={ disableAlpha } /> </div> </div> ) } Chrome.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), disableAlpha: PropTypes.bool, styles: PropTypes.object, defaultView: PropTypes.oneOf([ "hex", "rgb", "hsl", ]), } Chrome.defaultProps = { width: 225, disableAlpha: false, styles: {}, } export default ColorWrap(Chrome)
    examples/transitions/app.js
    cold-brew-coding/react-router
    import React from 'react'; import { Router, Route, Link, History, Lifecycle } from 'react-router'; var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/dashboard">Dashboard</Link></li> <li><Link to="/form">Form</Link></li> </ul> {this.props.children} </div> ); } }); var Home = React.createClass({ render() { return <h1>Home</h1>; } }); var Dashboard = React.createClass({ render() { return <h1>Dashboard</h1>; } }); var Form = React.createClass({ mixins: [ Lifecycle, History ], getInitialState() { return { textValue: 'ohai' }; }, routerWillLeave(nextLocation) { if (this.state.textValue) return 'You have unsaved information, are you sure you want to leave this page?'; }, handleChange(event) { this.setState({ textValue: event.target.value }); }, handleSubmit(event) { event.preventDefault(); this.setState({ textValue: '' }, () => { this.history.pushState(null, '/'); }); }, render() { return ( <div> <form onSubmit={this.handleSubmit}> <p>Click the dashboard link with text in the input.</p> <input type="text" ref="userInput" value={this.state.textValue} onChange={this.handleChange} /> <button type="submit">Go</button> </form> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="dashboard" component={Dashboard} /> <Route path="form" component={Form} /> </Route> </Router> ), document.getElementById('example'));
    app/javascript/components/Accounts/Users/Password.js
    luckypike/mint
    import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import axios from 'axios' // import { deserialize } from 'jsonapi-deserializer' import { path } from '../../Routes' import { useI18n } from '../../I18n' import { useForm, Errors } from '../../Form' import styles from './Password.module.css' import page from '../../Page.module.css' import form from '../../Form.module.css' import buttons from '../../Buttons.module.css' Password.propTypes = { user: PropTypes.object.isRequired, locale: PropTypes.string.isRequired } export default function Password ({ user: userJSON, locale }) { const I18n = useI18n(locale) const { values, // setValues, // saved, // setSaved, handleInputChange, errors, pending, setErrors, onSubmit, cancelToken } = useForm({ password: '', password_confirmation: '' }) const handleSubmit = async e => { e.preventDefault() await axios.patch( path('account_user_path', { format: 'json' }), { user: values }, { cancelToken: cancelToken.current.token } ).then(res => { if (res.headers.location) window.location = res.headers.location // setSaved(true) }).catch(error => { setErrors(error.response.data) }) } return ( <div className={page.gray}> <div className={page.title}> <h1>{I18n.t('accounts.users.password')}</h1> </div> <div className={styles.root}> <div className={form.tight}> <form className={classNames(form.root, styles.form)} onSubmit={onSubmit(handleSubmit)}> <Errors errors={errors.reset_password_token} /> <div className={form.item}> <label> <div className={form.label}> {I18n.t('accounts.passwords.password')} </div> <div className={form.input}> <input type="password" autoFocus autoComplete="new-password" value={values.password} name="password" onChange={handleInputChange} /> </div> </label> <Errors errors={errors.password} /> </div> <div className={form.item}> <label> <div className={form.label}> {I18n.t('accounts.passwords.password_confirmation')} </div> <div className={form.input}> <input type="password" autoComplete="off" value={values.password_confirmation} name="password_confirmation" onChange={handleInputChange} /> </div> </label> <Errors errors={errors.password_confirmation} /> </div> <div className={classNames(form.submit, styles.submit)}> <input type="submit" value={pending ? I18n.t('accounts.passwords.submiting') : I18n.t('accounts.passwords.submit')} className={classNames(buttons.main, { [buttons.pending]: pending })} disabled={pending} /> </div> </form> </div> </div> </div> ) }
    src/ui/elements/logos/Backbone.js
    gouxlord/dev-insight
    import React from 'react' var Backbone = React.createClass({ render: function () { return ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 129.08 162" preserveAspectRatio="xMinYMin meet"> <polygon fill="#0071B5" points="108.083,64.441 108.083,39.751 85.755,51.576 64.33,39.25 129.08,0 129.08,76.5 "/> <polygon fill="#002A41" points="20.996,64.441 20.996,39.751 43.324,51.576 64.33,39.25 0,0 0,76.5 "/> <polygon fill="#0071B5" points="96.331,82.055 64.33,100.625 85.8,112.587 108.08,100.625 108.08,88.5 "/> <polygon fill="#002A41" points="32.329,82.055 64.33,100.625 42.859,112.587 20.58,100.625 20.58,88.5 "/> <polygon fill="#0071B5" points="0,162 0,76.5 64.33,39.25 64.75,64.5 21,88.5 21,125 64.33,100.625 64.33,126 "/> <polygon fill="#002A41" points="129.08,162 129.08,76.5 64.33,39.25 64.33,64.5 108.08,88.5 108.08,125 64.33,100.625 64.33,126 "/> </svg> ) } }); export default Backbone;
    app/js/components/content/DropFileComponent.js
    theappbusiness/tab-hq
    'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import GoogleDriveMixin from '../../mixins/GoogleDriveMixin'; const DropFileComponent = React.createClass({ mixins: [GoogleDriveMixin], uploadFile(e) { // console.log(e); }, addLinkFromDrive(elem, params) { this.props.addLinkFromDrive(elem, params); }, triggerFileUpload() { let uploadField = this.refs.upload; uploadField.click(); }, fileUploaded(event) { console.log(event); }, render() { let addLinkButton = ''; let googleDriveButton = ''; let classes = 'downloadButtons'; if (this.props.type === 'link') { addLinkButton = <button className='btn btn-default' onClick={this.props.addLink}>Add link</button>; classes += ' btn-group'; } googleDriveButton = <button id='google-button' className='btn btn-default' onClick={this.addFilesFromGoogleDrive}>Add from Google Drive</button>; if (this.props.userIsAdmin) { return ( <div className='text-center dropzone'> <a href='#'> <i className='fa fa-cloud-upload fa-3x' /> </a> <h3>Drag & Drop</h3> <input id='upload' onChange={this.fileUploaded} type='file' ref='upload' style={{display: 'none'}} /> <p>or <a href='#' onClick={this.triggerFileUpload}>browse</a></p> <div className={classes}> {addLinkButton} {googleDriveButton} </div> </div> ); } else { return null; } } }); module.exports = DropFileComponent;
    stories/default-size/percent-size.js
    pionl/react-resizable-box
    /* eslint-disable */ import React from 'react'; import Resizable from '../../src'; const style = { display: 'flex', alignItems: 'center', justifyContent: 'center', border: 'solid 1px #ddd', background: '#f0f0f0', }; export default () => ( <Resizable style={style} defaultSize={{ width: '30%', height: '20%', }} > 001 </Resizable> );
    src/svg-icons/action/build.js
    rhaedes/material-ui
    import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBuild = (props) => ( <SvgIcon {...props}> <path d="M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z"/> </SvgIcon> ); ActionBuild = pure(ActionBuild); ActionBuild.displayName = 'ActionBuild'; export default ActionBuild;
    packages/forms/src/UIForm/fields/FieldTemplate/FieldTemplate.component.js
    Talend/ui
    import PropTypes from 'prop-types'; import React from 'react'; import classNames from 'classnames'; import { useTranslation } from 'react-i18next'; import { Button } from 'react-bootstrap'; import OverlayTrigger from '@talend/react-components/lib/OverlayTrigger'; import Icon from '@talend/react-components/lib/Icon'; import Message from '../../Message'; import { I18N_DOMAIN_FORMS } from '../../../constants'; import theme from './FieldTemplate.scss'; function Label({ id, label, ...rest }) { return ( <label htmlFor={id} className="control-label" {...rest}> {label} </label> ); } if (process.env.NODE_ENV !== 'production') { Label.propTypes = { id: PropTypes.string, label: PropTypes.string, }; } function FieldTemplate(props) { const { t } = useTranslation(I18N_DOMAIN_FORMS); const groupsClassNames = classNames('form-group', theme.template, props.className, { 'has-error': !props.isValid, required: props.required, [theme.updating]: props.valueIsUpdating, }); let title = <Label id={props.id} label={props.label} {...props.labelProps} />; if (props.hint) { title = ( <div className={theme['field-template-title']}> {title} <OverlayTrigger overlayId={`${props.id}-hint-overlay`} overlayPlacement={props.hint.overlayPlacement || 'right'} overlayComponent={props.hint.overlayComponent} > <Button id={`${props.id}-hint`} bsStyle="link" className={props.hint.className} aria-label={t('FIELD_TEMPLATE_HINT_LABEL', { defaultValue: 'Display the input {{inputLabel}} hint', inputLabel: props.label, })} aria-haspopup > <Icon name={props.hint.icon || 'talend-info-circle'} /> </Button> </OverlayTrigger> </div> ); } const labelAfter = props.hint ? false : props.labelAfter; return ( <div className={groupsClassNames} aria-busy={props.valueIsUpdating}> {props.label && !labelAfter && title} {props.children} {props.label && labelAfter && title} <Message description={props.description} descriptionId={props.descriptionId} errorId={props.errorId} errorMessage={props.errorMessage} isValid={props.isValid} /> </div> ); } if (process.env.NODE_ENV !== 'production') { FieldTemplate.propTypes = { children: PropTypes.node, hint: PropTypes.shape({ icon: PropTypes.string, className: PropTypes.string, overlayComponent: PropTypes.oneOfType([PropTypes.node, PropTypes.string]).isRequired, overlayPlacement: PropTypes.string, }), className: PropTypes.string, description: PropTypes.string, descriptionId: PropTypes.string.isRequired, errorId: PropTypes.string.isRequired, errorMessage: PropTypes.string, id: PropTypes.string, isValid: PropTypes.bool, label: PropTypes.string, labelProps: PropTypes.object, labelAfter: PropTypes.bool, required: PropTypes.bool, valueIsUpdating: PropTypes.bool, }; } FieldTemplate.defaultProps = { isValid: true, }; FieldTemplate.displayName = 'FieldTemplate'; export default FieldTemplate;
    analysis/demonhuntervengeance/src/modules/talents/SpiritBombSoulsConsume.js
    yajinni/WoWAnalyzer
    import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import BoringSpellValueText from 'parser/ui/BoringSpellValueText'; import Statistic from 'parser/ui/Statistic'; import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import { formatPercentage } from 'common/format'; import { t } from '@lingui/macro'; import Events from 'parser/core/Events'; import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; const MS_BUFFER = 100; class SpiritBombSoulsConsume extends Analyzer { get totalGoodCasts() { return this.soulsConsumedByAmount[4] + this.soulsConsumedByAmount[5]; } get totalCasts() { return Object.values(this.soulsConsumedByAmount).reduce((total, casts) => total + casts, 0); } get percentGoodCasts() { return this.totalGoodCasts / this.totalCasts; } get suggestionThresholdsEfficiency() { return { actual: this.percentGoodCasts, isLessThan: { minor: 0.90, average: 0.85, major: .80, }, style: 'percentage', }; } castTimestamp = 0; castSoulsConsumed = 0; cast = 0; soulsConsumedByAmount = Array.from({ length: 6 }, x => 0); /* Feed The Demon talent is taken in defensive builds. In those cases you want to generate and consume souls as quickly as possible. So how you consume your souls down matter. If you dont take that talent your taking a more balanced build meaning you want to consume souls in a way that boosts your dps. That means feeding the souls into spirit bomb as efficiently as possible (cast at 4+ souls) for a dps boost and have soul cleave absorb souls as little as possible since it provides no extra dps. */ constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id) && !this.selectedCombatant.hasTalent(SPELLS.FEED_THE_DEMON_TALENT.id); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.SPIRIT_BOMB_TALENT), this.onCast); this.addEventListener(Events.changebuffstack.by(SELECTED_PLAYER).spell(SPELLS.SOUL_FRAGMENT_STACK), this.onChangeBuffStack); this.addEventListener(Events.fightend, this.onFightend); } onCast(event) { if (this.cast > 0) { this.countHits(); } this.castTimestamp = event.timestamp; this.cast += 1; } onChangeBuffStack(event) { if (event.oldStacks < event.newStacks) { return; } if (event.timestamp - this.castTimestamp < MS_BUFFER) { const soulsConsumed = event.oldStacks - event.newStacks; this.castSoulsConsumed += soulsConsumed; } } countHits() { if (!this.soulsConsumedByAmount[this.castSoulsConsumed]) { this.soulsConsumedByAmount[this.castSoulsConsumed] = 1; this.castSoulsConsumed = 0; return; } this.soulsConsumedByAmount[this.castSoulsConsumed] += 1; this.castSoulsConsumed = 0; } onFightend() { this.countHits(); } suggestions(when) { when(this.suggestionThresholdsEfficiency) .addSuggestion((suggest, actual, recommended) => suggest(<>Try to cast <SpellLink id={SPELLS.SPIRIT_BOMB_TALENT.id} /> at 4 or 5 souls.</>) .icon(SPELLS.SPIRIT_BOMB_TALENT.icon) .actual(t({ id: "demonhunter.vengeance.suggestions.spiritBomb.soulsConsumed", message: `${formatPercentage(this.percentGoodCasts)}% of casts at 4+ souls.` })) .recommended(`>${formatPercentage(recommended)}% is recommended`)); } statistic() { return ( <Statistic position={STATISTIC_ORDER.CORE(6)} category={STATISTIC_CATEGORY.TALENTS} size="flexible" dropdown={( <> <table className="table table-condensed"> <thead> <tr> <th>Stacks</th> <th>Casts</th> </tr> </thead> <tbody> {Object.values(this.soulsConsumedByAmount).map((castAmount, stackAmount) => ( <tr key={stackAmount}> <th>{stackAmount}</th> <td>{castAmount}</td> </tr> ))} </tbody> </table> </> )} > <BoringSpellValueText spell={SPELLS.SPIRIT_BOMB_TALENT}> <> {formatPercentage(this.percentGoodCasts)}% <small>good casts</small> </> </BoringSpellValueText> </Statistic> ); } } export default SpiritBombSoulsConsume;
    src/scenes/Home/Home.js
    strues/react-universal-boiler
    // @flow import React, { Component } from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import type { Connector } from 'react-redux'; import { fetchPosts, fetchPostsIfNeeded } from '../../state/modules/posts'; import Post from '../../components/Post'; import type { PostsReducer, Dispatch, Reducer } from '../../types'; // $FlowIssue import styles from './style.scss'; type Props = { posts: PostsReducer, fetchPostsIfNeeded: () => void, }; export class Home extends Component<Props, *> { static displayName = 'Home'; static fetchData({ store }) { return store.dispatch(fetchPosts()); } componentDidMount() { this.props.fetchPostsIfNeeded(); } render() { return ( <div> <Helmet title="Home" /> <div className="row"> <div className="column"> <div className={styles.hero}> <h1>React Universal Boiler</h1> <p>A server rendering React project.</p> </div> </div> </div> <div className="posts-list"> {this.props.posts.list.map(p => ( <div className="column column-30" key={p.id}> <Post title={p.title} body={p.body} /> </div> ))} </div> </div> ); } } const connector: Connector<{}, Props> = connect( ({ posts }: Reducer) => ({ posts }), (dispatch: Dispatch) => ({ fetchPostsIfNeeded: () => dispatch(fetchPostsIfNeeded()), }), ); export default connector(Home);
    app/components/H3/index.js
    Cherchercher/Wedding-Llama
    import React from 'react'; function H3(props) { return ( <h3 {...props} /> ); } export default H3;
    packages/mineral-ui-icons/src/IconAlarmAdd.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 IconAlarmAdd(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9a9 9 0 0 0 0-18zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/> </g> </Icon> ); } IconAlarmAdd.displayName = 'IconAlarmAdd'; IconAlarmAdd.category = 'action';
    src/src/Components/RulesEditor/components/CustomTime/index.js
    ioBroker/ioBroker.javascript
    import { TextField } from '@material-ui/core'; import React from 'react'; import cls from './style.module.scss'; import PropTypes from 'prop-types'; import clsx from 'clsx'; const CustomTime = ({ value, style, onChange, className }) => { return <TextField id="time" type="time" onChange={(e) => onChange(e.currentTarget.value)} value={value} className={clsx(cls.root, className)} fullWidth style={style} InputLabelProps={{ shrink: true, }} inputProps={{ step: 300, // 5 min }} />; } CustomTime.defaultProps = { value: '', className: null, table: false }; CustomTime.propTypes = { title: PropTypes.string, attr: PropTypes.string, style: PropTypes.object, onChange: PropTypes.func }; export default CustomTime;
    src/AffixMixin.js
    coderstudy/react-bootstrap
    import React from 'react'; import domUtils from './utils/domUtils'; import EventListener from './utils/EventListener'; const AffixMixin = { propTypes: { offset: React.PropTypes.number, offsetTop: React.PropTypes.number, offsetBottom: React.PropTypes.number }, getInitialState() { return { affixClass: 'affix-top' }; }, getPinnedOffset(DOMNode) { if (this.pinnedOffset) { return this.pinnedOffset; } DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, ''); DOMNode.className += DOMNode.className.length ? ' affix' : 'affix'; this.pinnedOffset = domUtils.getOffset(DOMNode).top - window.pageYOffset; return this.pinnedOffset; }, checkPosition() { let DOMNode, scrollHeight, scrollTop, position, offsetTop, offsetBottom, affix, affixType, affixPositionTop; // TODO: or not visible if (!this.isMounted()) { return; } DOMNode = React.findDOMNode(this); scrollHeight = document.documentElement.offsetHeight; scrollTop = window.pageYOffset; position = domUtils.getOffset(DOMNode); if (this.affixed === 'top') { position.top += scrollTop; } offsetTop = this.props.offsetTop != null ? this.props.offsetTop : this.props.offset; offsetBottom = this.props.offsetBottom != null ? this.props.offsetBottom : this.props.offset; if (offsetTop == null && offsetBottom == null) { return; } if (offsetTop == null) { offsetTop = 0; } if (offsetBottom == null) { offsetBottom = 0; } if (this.unpin != null && (scrollTop + this.unpin <= position.top)) { affix = false; } else if (offsetBottom != null && (position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom)) { affix = 'bottom'; } else if (offsetTop != null && (scrollTop <= offsetTop)) { affix = 'top'; } else { affix = false; } if (this.affixed === affix) { return; } if (this.unpin != null) { DOMNode.style.top = ''; } affixType = 'affix' + (affix ? '-' + affix : ''); this.affixed = affix; this.unpin = affix === 'bottom' ? this.getPinnedOffset(DOMNode) : null; if (affix === 'bottom') { DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom'); affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - domUtils.getOffset(DOMNode).top; } this.setState({ affixClass: affixType, affixPositionTop }); }, checkPositionWithEventLoop() { setTimeout(this.checkPosition, 0); }, componentDidMount() { this._onWindowScrollListener = EventListener.listen(window, 'scroll', this.checkPosition); this._onDocumentClickListener = EventListener.listen(domUtils.ownerDocument(this), 'click', this.checkPositionWithEventLoop); }, componentWillUnmount() { if (this._onWindowScrollListener) { this._onWindowScrollListener.remove(); } if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } }, componentDidUpdate(prevProps, prevState) { if (prevState.affixClass === this.state.affixClass) { this.checkPositionWithEventLoop(); } } }; export default AffixMixin;
    fields/types/name/NameColumn.js
    suryagh/keystone
    import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue'; import displayName from 'display-name'; var NameColumn = React.createClass({ displayName: 'NameColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, linkTo: React.PropTypes.string, }, renderValue () { var value = this.props.data.fields[this.props.col.path]; if (!value || (!value.first && !value.last)) return '(no name)'; return displayName(value.first, value.last); }, render () { return ( <ItemsTableCell> <ItemsTableValue href={this.props.linkTo} padded interior field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = NameColumn;
    test/fixtures/fragment.js
    zeit/styled-jsx
    import React from 'react' export default () => ( <> <p>Testing!!!</p> <p className="foo">Bar</p> <> <h3 id="head">Title...</h3> <React.Fragment> <p>hello</p> <> <p>foo</p> <p>bar</p> </> <p>world</p> </React.Fragment> </> <style jsx>{` p { color: cyan; } .foo { font-size: 18px; color: hotpink; } #head { text-decoration: underline; } `}</style> </> ) function Component1() { return ( <> <div>test</div> </> ) } function Component2() { return ( <div> <style jsx>{` div { color: red; } `}</style> </div> ) }
    app/javascript/mastodon/features/notifications/components/filter_bar.js
    danhunsaker/mastodon
    import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Icon from 'mastodon/components/icon'; const tooltips = defineMessages({ mentions: { id: 'notifications.filter.mentions', defaultMessage: 'Mentions' }, favourites: { id: 'notifications.filter.favourites', defaultMessage: 'Favourites' }, boosts: { id: 'notifications.filter.boosts', defaultMessage: 'Boosts' }, polls: { id: 'notifications.filter.polls', defaultMessage: 'Poll results' }, follows: { id: 'notifications.filter.follows', defaultMessage: 'Follows' }, statuses: { id: 'notifications.filter.statuses', defaultMessage: 'Updates from people you follow' }, }); export default @injectIntl class FilterBar extends React.PureComponent { static propTypes = { selectFilter: PropTypes.func.isRequired, selectedFilter: PropTypes.string.isRequired, advancedMode: PropTypes.bool.isRequired, intl: PropTypes.object.isRequired, }; onClick (notificationType) { return () => this.props.selectFilter(notificationType); } render () { const { selectedFilter, advancedMode, intl } = this.props; const renderedElement = !advancedMode ? ( <div className='notification__filter-bar'> <button className={selectedFilter === 'all' ? 'active' : ''} onClick={this.onClick('all')} > <FormattedMessage id='notifications.filter.all' defaultMessage='All' /> </button> <button className={selectedFilter === 'mention' ? 'active' : ''} onClick={this.onClick('mention')} > <FormattedMessage id='notifications.filter.mentions' defaultMessage='Mentions' /> </button> </div> ) : ( <div className='notification__filter-bar'> <button className={selectedFilter === 'all' ? 'active' : ''} onClick={this.onClick('all')} > <FormattedMessage id='notifications.filter.all' defaultMessage='All' /> </button> <button className={selectedFilter === 'mention' ? 'active' : ''} onClick={this.onClick('mention')} title={intl.formatMessage(tooltips.mentions)} > <Icon id='reply-all' fixedWidth /> </button> <button className={selectedFilter === 'favourite' ? 'active' : ''} onClick={this.onClick('favourite')} title={intl.formatMessage(tooltips.favourites)} > <Icon id='star' fixedWidth /> </button> <button className={selectedFilter === 'reblog' ? 'active' : ''} onClick={this.onClick('reblog')} title={intl.formatMessage(tooltips.boosts)} > <Icon id='retweet' fixedWidth /> </button> <button className={selectedFilter === 'poll' ? 'active' : ''} onClick={this.onClick('poll')} title={intl.formatMessage(tooltips.polls)} > <Icon id='tasks' fixedWidth /> </button> <button className={selectedFilter === 'status' ? 'active' : ''} onClick={this.onClick('status')} title={intl.formatMessage(tooltips.statuses)} > <Icon id='home' fixedWidth /> </button> <button className={selectedFilter === 'follow' ? 'active' : ''} onClick={this.onClick('follow')} title={intl.formatMessage(tooltips.follows)} > <Icon id='user-plus' fixedWidth /> </button> </div> ); return renderedElement; } }
    src/svg-icons/device/signal-cellular-3-bar.js
    hai-cea/material-ui
    import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellular3Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z"/><path d="M17 7L2 22h15z"/> </SvgIcon> ); DeviceSignalCellular3Bar = pure(DeviceSignalCellular3Bar); DeviceSignalCellular3Bar.displayName = 'DeviceSignalCellular3Bar'; DeviceSignalCellular3Bar.muiName = 'SvgIcon'; export default DeviceSignalCellular3Bar;
    src/pages/Registry.js
    btthomas/blakeandanna
    import React from 'react' import popup from '../popup.js'; const links = [ { url: 'https://www.crateandbarrel.com/gift-registry/anna-hunter-and-blake-thomas/r5729048', imgSrc: 'https://images.crateandbarrel.com/is/image/Crate/WebsiteHeaderLogo/fmt=png-alpha/170805043136/WebsiteHeaderLogo.jpg' }, { url: 'https://www.bedbathandbeyond.com/store/giftregistry/view_registry_guest.jsp?registryId=544926178&eventType=Wedding&pwsurl=&eventType=Wedding', imgSrc: 'https://www.bedbathandbeyond.com/_assets/global/images/logo/logo_bbb.png', id: 'bath' }, ]; const RegistryPage = () => { return ( <div className="registry"> {links.map(link => { return ( <a key={link.url} href={link.url} onClick={popup.bind(null, link.url)}> <img src={link.imgSrc} id={link.id}/> </a> ); })} </div> ); } export default RegistryPage;
    client/react/panel/inputs/InputEditableDateTimeField.js
    uclaradio/uclaradio
    // InputEditableDateTimeField.js import React from 'react'; import { ButtonGroup, DropdownButton, MenuItem, Input, Glyphicon, } from 'react-bootstrap'; import Dates from '../../common/Dates'; /** * Show current saved value for day/time and let user update data and submit changes * * @prop title: form title of the element * @prop placeholder: placeholder to show in field * @prop verified: should show indicator that the value was successfully... whatever * * @prop day: current saved day value * @prop time: current saved time value * @prop onDateSubmit -> function(day, time): parent's function to be called if 'Submit' is hit * * @state day: current day value being entered * @state time: current time value being entered * @state editable: should let the user edit the field */ const InputEditableDateTimeField = React.createClass({ getInitialState() { return { day: 'Mon', time: '10am', editable: false }; }, handleDayChange(e, day) { this.setState({ day }); }, handleTimeChange(e, time) { this.setState({ time }); }, toggleEditableField(e) { this.setState({ day: this.props.day, time: this.props.time, editable: !this.state.editable, }); }, handleSubmit(e) { e.preventDefault(); const day = this.state.day.trim(); const time = this.state.time.trim(); if (day && time) { this.props.onDateSubmit(day, time); this.setState({ day: 'Mon', time: '10am', editable: false }); } }, render() { const editButton = ( <a className="customInput" onClick={this.toggleEditableField}> Edit </a> ); // var cancelButton = <Button className="cancelLink" onClick={this.toggleEditableField}>Cancel</Button>; const actionButton = ( <span> <a onClick={this.handleSubmit}>{this.props.buttonTitle || 'Update'}</a> &emsp;&emsp;&emsp;<a className="cancelLink" onClick={this.toggleEditableField}> Cancel </a> </span> ); const days = Dates.availableDays.map(day => ( <MenuItem key={day} eventKey={day}> {Dates.dayFromVar(day)} </MenuItem> )); const times = Dates.availableTimes.map(time => ( <MenuItem key={time} eventKey={time}> {time} </MenuItem> )); return ( <div className="inputEditableDateTimeField"> <form className="form-horizontal"> <Input label={this.props.title} labelClassName="col-xs-3" wrapperClassName="inputEditWrapper col-xs-9" addonAfter={this.state.editable ? actionButton : editButton}> {this.state.editable ? ( // field edit/submittable <ButtonGroup> <DropdownButton id="day" title={ Dates.dayFromVar(this.state.day) || ( <span className="placeholder">Day</span> ) } onSelect={this.handleDayChange} key={this.state.day}> {days} </DropdownButton> <DropdownButton id="time" title={ this.state.time || <span className="placeholder">Time</span> } onSelect={this.handleTimeChange} key={this.state.time}> {times} </DropdownButton> </ButtonGroup> ) : ( // locked to user input <span className="customInput"> {this.props.day && this.props.time ? ( <span> {Dates.dayFromVar(this.props.day)} {this.props.time}{' '} {this.props.verified ? ( <Glyphicon className="verifiedGlyph" glyph="ok" /> ) : ( '' )} </span> ) : ( <span className="placeholder">{this.props.placeholder}</span> )} </span> )} </Input> </form> </div> ); }, }); export default InputEditableDateTimeField;
    server/sonar-web/src/main/js/apps/account/components/Password.js
    joansmith/sonarqube
    /* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React, { Component } from 'react'; import { changePassword } from '../../../api/users'; import { translate } from '../../../helpers/l10n'; export default class Password extends Component { state = { success: false, errors: null }; handleSuccessfulChange () { this.refs.oldPassword.value = ''; this.refs.password.value = ''; this.refs.passwordConfirmation.value = ''; this.setState({ success: true, errors: null }); } handleFailedChange (e) { e.response.json().then(r => { this.refs.oldPassword.focus(); this.setErrors(r.errors.map(e => e.msg)); }); } setErrors (errors) { this.setState({ success: false, errors }); } handleChangePassword (e) { e.preventDefault(); const { user } = this.props; const oldPassword = this.refs.oldPassword.value; const password = this.refs.password.value; const passwordConfirmation = this.refs.passwordConfirmation.value; if (password !== passwordConfirmation) { this.refs.password.focus(); this.setErrors([translate('user.password_doesnt_match_confirmation')]); } else { changePassword(user.login, password, oldPassword) .then(this.handleSuccessfulChange.bind(this)) .catch(this.handleFailedChange.bind(this)); } } render () { const { success, errors } = this.state; return ( <section> <h2 className="spacer-bottom"> {translate('my_profile.password.title')} </h2> <form onSubmit={this.handleChangePassword.bind(this)}> {success && ( <div className="alert alert-success"> {translate('my_profile.password.changed')} </div> )} {errors && errors.map((e, i) => ( <div key={i} className="alert alert-danger">{e}</div> ))} <div className="modal-field"> <label htmlFor="old_password"> {translate('my_profile.password.old')} <em className="mandatory">*</em> </label> <input ref="oldPassword" autoComplete="off" id="old_password" name="old_password" required={true} type="password"/> </div> <div className="modal-field"> <label htmlFor="password"> {translate('my_profile.password.new')} <em className="mandatory">*</em> </label> <input ref="password" autoComplete="off" id="password" name="password" required={true} type="password"/> </div> <div className="modal-field"> <label htmlFor="password_confirmation"> {translate('my_profile.password.confirm')} <em className="mandatory">*</em> </label> <input ref="passwordConfirmation" autoComplete="off" id="password_confirmation" name="password_confirmation" required={true} type="password"/> </div> <div className="modal-field"> <button id="change-password" type="submit"> {translate('my_profile.password.submit')} </button> </div> </form> </section> ); } }
    docs/app/Examples/views/Item/Content/ItemExampleLink.js
    aabustamante/Semantic-UI-React
    import React from 'react' import { Image as ImageComponent, Item } from 'semantic-ui-react' const paragraph = <ImageComponent src='/assets/images/wireframe/short-paragraph.png' /> const ItemExampleLink = () => ( <Item.Group> <Item> <Item.Image size='tiny' src='/assets/images/wireframe/image.png' /> <Item.Content> <Item.Header>Arrowhead Valley Camp</Item.Header> <Item.Meta> <span className='price'>$1200</span> <span className='stay'>1 Month</span> </Item.Meta> <Item.Description>{paragraph}</Item.Description> </Item.Content> </Item> <Item> <Item.Image size='tiny' src='/assets/images/wireframe/image.png' /> <Item.Content> <Item.Header>Buck's Homebrew Stayaway</Item.Header> <Item.Meta content='$1000 2 Weeks' /> <Item.Description>{paragraph}</Item.Description> </Item.Content> </Item> <Item> <Item.Image size='tiny' src='/assets/images/wireframe/image.png' /> <Item.Content header='Arrowhead Valley Camp' meta='$1200 1 Month' /> </Item> </Item.Group> ) export default ItemExampleLink
    tp-3/euge/src/index.js
    jpgonzalezquinteros/sovos-reactivo-2017
    /* eslint-disable import/default */ import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import Root from './components/Root'; require('./favicon.ico'); // Tell webpack to load favicon.ico render( <AppContainer> <Root/> </AppContainer>, document.getElementById('app') ); if (module.hot) { module.hot.accept('./components/Root', () => { const NewRoot = require('./components/Root').default; render( <AppContainer> <NewRoot /> </AppContainer>, document.getElementById('app') ); }); }
    pootle/static/js/shared/components/AutosizeTextarea.js
    evernote/zing
    /* * Copyright (C) Pootle contributors. * Copyright (C) Zing contributors. * * This file is a part of the Zing project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import autosize from 'autosize'; import React from 'react'; const AutosizeTextarea = React.createClass({ componentDidMount() { autosize(this.refs.textarea); }, componentDidUpdate() { autosize.update(this.refs.textarea); }, componentWillUnmount() { autosize.destroy(this.refs.textarea); }, render() { return <textarea ref="textarea" {...this.props} />; }, }); export default AutosizeTextarea;
    plugins/react/frontend/components/controls/base/ArrayControl/ConstraintsForm/index.js
    carteb/carte-blanche
    import React from 'react'; import controlTypes from '../../../../CustomMetadataForm/controlTypes'; import getControl from '../../../../../utils/getControl'; import renderConstraintForm from './renderConstraintForm'; import Row from '../../../../form/Grid/Row'; import LeftColumn from '../../../../form/Grid/LeftColumn'; import RightColumn from '../../../../form/Grid/RightColumn'; import ComboBox from '../../../../form/ComboBox'; /** * * Takes care of rendering of the selection & constraint form for nested arrays * * The props should have the following structure: * * constraints: { * controlType: "arrayOf", * constraints: { * controlType: "string" * } * } * * parsedMetadata: { * name: "arrayOf", * value: { * name: "string" * } * } * * * @param constraints * @param parsedMetadata * @param onUpdate * @returns {Object} * @constructor */ const ConstraintsForm = ({ constraints, parsedMetadata, onUpdate, nestedLevel }) => { const onChange = (event) => { const controlType = event.value; // check if the control type has constraints // if the type doesn't have constraints neglect the existing constraints. const control = getControl({ name: controlType }); const hasConstraints = control.type.ConstraintsForm; const newCustomMetadata = hasConstraints && constraints && constraints.constraints ? { ...constraints.constraints } : {}; newCustomMetadata.controlType = controlType; onUpdate({ ...newCustomMetadata }); }; const renderControl = ({ controlType, constraint }) => ( <Row> <LeftColumn nestedLevel={nestedLevel}>{controlType}</LeftColumn> <RightColumn> <ComboBox value={controlType} onChange={onChange} options={controlTypes.map((type) => ({ value: type }))} /> </RightColumn> {renderConstraintForm( controlType, onUpdate, constraints, parsedMetadata )} {constraint && renderControl(constraint)} </Row> ); return ( <Row> {renderControl(constraints)} </Row> ); }; export default ConstraintsForm;
    app/components/Facebook.js
    vietvd88/developer-crawler
    // @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Facebook.css'; import SortTable from './SortTable' import { Button, FormControl, FormGroup, ControlLabel } from 'react-bootstrap'; export default class Home extends Component { constructor(props) { super(props); var queryString = this.props.location.query this.props.getFacebookDeveloperAsync(queryString.user) this.props.getFacebookJobAsync(queryString.user) this.onChange = this.onChange.bind(this); this.postComment = this.postComment.bind(this); this.comment = '' } postComment(evt) { this.props.postComment(this.props.developer.user_name, this.comment) } onChange(evt) { console.log(evt.target.value) this.comment = evt.target.value } render() { const columns = [ {name: 'Company', key: 'company', width: 200}, {name: 'Position', key: 'position', width: 200}, {name: 'Duration', key: 'duration', width: 200}, ]; var comments = this.props.commentList.map(function(comment) { return comment.comment }) var commentText = comments.join('\n\n') return ( <div> <div className={styles.container}> <h2>Job Search Crawler -- <Link to={{ pathname: '/' }}> HomePage </Link> </h2> <hr/> <div className={styles.userPanel}> <img src={this.props.developer.avatar} className={styles.avatar}/> <span className={styles.userName}>{this.props.developer.name}</span> </div> <div className={styles.repoTable}> <SortTable dataList={this.props.facebookJobList} columns={columns} onSortChange={this.props.sortFacebookJob} width={800} height={200} /> </div> <div className={styles.email}> Email: {this.props.developer.email} </div> <div className={styles.phone}> Website: {this.props.developer.website} </div> <FormGroup controlId="formControlsTextarea"> <FormControl componentClass="textarea" value={commentText} readOnly className={styles.comments}/> </FormGroup> <FormGroup> <FormControl type="text" placeholder="New Comment" onChange={this.onChange}/> </FormGroup> {' '} <Button bsStyle="primary" bsSize="small" className={styles.filterButton} onClick={this.postComment} > Post </Button> </div> </div> ); } }
    packages/server/src/core/renderers.js
    warebrained/basis
    import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; // renderReactView export default (res, view, title, componentType, props) => { const element = React.createElement(componentType, props, null); const markup = renderToStaticMarkup(element); res.render(view, { title, markup }); };
    clients/packages/admin-client/src/pages/admin/mobilizations/launch/page.js
    nossas/bonde-client
    import React from 'react'; import { FormattedMessage, injectIntl } from 'react-intl'; import * as paths from '../../../../paths'; import * as MobActions from '../../../../mobrender/redux/action-creators'; import { Loading } from '../../../../components/await'; import MobSelectors from '../../../../mobrender/redux/selectors'; import { PageCentralizedLayout, PageCentralizedLayoutTitle, } from '../../../../components/layout'; import { Tabs, Tab } from '../../../../components/navigation/tabs'; import { Button, FlatForm } from '../../../../ux/components'; import { StepsContainerStack, StepContent } from '../../../../components/steps'; import { FormDomain, FormShare } from '../../../../mobilizations/components'; if (require('exenv').canUseDOM) { require('./form-domain.scss'); require('./form-share.scss'); } const FormShareImplementation = injectIntl( FormShare( (state) => ({ initialValues: MobSelectors(state).getMobilization() }), { submit: MobActions.asyncUpdateMobilization }, (values, props) => { const errors = {}; const messageRequired = props.intl.formatMessage({ id: 'page--mobilizations-launch.form-share.validation.required', defaultMessage: 'Obrigatório', }); if (!values.facebook_share_image) { errors.facebook_share_image = messageRequired; } if (!values.facebook_share_title) { errors.facebook_share_title = messageRequired; } if (!values.facebook_share_description) { errors.facebook_share_description = messageRequired; } if (!values.twitter_share_text) { errors.twitter_share_text = messageRequired; } return errors; } ) ); const MobilizationsLaunchPage = ({ history, hostedZones, mobilization, isSaving, ...formProps }) => { const stepDomainValidation = () => !!mobilization.custom_domain; const stepShareValidation = () => !!mobilization.facebook_share_image && !!mobilization.facebook_share_title && !!mobilization.facebook_share_description && !!mobilization.twitter_share_text; const stepFinishValidation = () => mobilization.custom_domain && mobilization.facebook_share_image && mobilization.facebook_share_title && mobilization.facebook_share_description && mobilization.twitter_share_text; const savingButtonMessage = ( <FormattedMessage id="page--mobilizations-launch.button.saving" defaultMessage="Salvando..." /> ); const launchButtonMessage = ( <FormattedMessage id="page--mobilizations-launch.button.launch" defaultMessage="Lançar mobilização" /> ); const continueButtonMessage = ( <FormattedMessage id="page--mobilizations-launch.button.next" defaultMessage="Continuar" /> ); return ( <PageCentralizedLayout> <PageCentralizedLayoutTitle> <FormattedMessage id="page--mobilizations-launch.title" defaultMessage="Lançando sua mobilização" /> </PageCentralizedLayoutTitle> <StepsContainerStack ComponentPointerContainer={Tabs} ComponentPointerChildren={Tab} pointerChildrenProps={({ index, step }) => ({ isActive: index === step, index, })} progressValidations={[ stepDomainValidation, stepShareValidation, stepFinishValidation, ]} > <StepContent> <FormDomain {...formProps} formComponent={FlatForm} titleText={ <FormattedMessage id="page--mobilizations-launch.steps.form-domain.title" defaultMessage="Configure o endereço da mobilização" /> } buttonText={ isSaving ? savingButtonMessage : stepShareValidation() ? launchButtonMessage : continueButtonMessage } requiredField mobilization={mobilization} hostedZones={hostedZones} redirectToCreateDNS={() => { history.push( paths.communityDomainCreate( `?next=${paths.mobilizationLaunch(mobilization.id)}` ) ); }} /> </StepContent> <StepContent> <FormShareImplementation {...formProps} FormComponent={FlatForm} formClassNames="mobilization-launch--form-share" titleText={ <FormattedMessage id="page--mobilizations-launch.steps.form-share.title" defaultMessage="Configure as informações de compartilhamento" /> } buttonText={isSaving ? savingButtonMessage : launchButtonMessage} /> </StepContent> <StepContent> <div className="ux--flat-form"> <h1> <FormattedMessage id="page--mobilizations-launch.steps.done.title" defaultMessage="Seu BONDE está pronto!" /> </h1> <p className="h5"> <FormattedMessage id="page--mobilizations-launch.steps.done.helper-text" defaultMessage={ 'Em uma nova aba, digite o endereço que cadastrou na mobilização ' + 'para se certificar de que ela já está no ar. Se ainda não estiver, ' + 'cheque se cadastrou os domínios corretamente. Está tudo certo? Então ' + 'é só esperar ele propagar pela internet!' } /> </p> <Button href={`http://${mobilization.custom_domain}`} target="_blank" > <FormattedMessage id="page--mobilizations-launch.steps.done.button.open" defaultMessage="Visualizar mobilização" /> </Button> </div> </StepContent> </StepsContainerStack> {isSaving && <Loading />} </PageCentralizedLayout> ); }; export default MobilizationsLaunchPage;
    src/parser/deathknight/blood/modules/features/BoneShield.js
    ronaldpereira/WoWAnalyzer
    import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatDuration, formatPercentage } from 'common/format'; import { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import StatisticBox from 'interface/others/StatisticBox'; import StatTracker from 'parser/shared/modules/StatTracker'; import BoneShieldTimesByStacks from './/BoneShieldTimesByStacks'; class BoneShield extends Analyzer { static dependencies = { statTracker: StatTracker, boneShieldTimesByStacks: BoneShieldTimesByStacks, }; get boneShieldTimesByStack() { return this.boneShieldTimesByStacks.boneShieldTimesByStacks; } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.BONE_SHIELD.id) / this.owner.fightDuration; } get uptimeSuggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.95, average: 0.9, major: .8, }, style: 'percentage', }; } suggestions(when) { when(this.uptimeSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest('Your Bone Shield uptime can be improved. Try to keep it up at all times.') .icon(SPELLS.BONE_SHIELD.icon) .actual(`${formatPercentage(actual)}% Bone Shield uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.BONE_SHIELD.id} />} value={`${formatPercentage(this.uptime)} %`} label="Bone Shield uptime" > <table className="table table-condensed"> <thead> <tr> <th>Stacks</th> <th>Time (s)</th> <th>Time (%)</th> </tr> </thead> <tbody> {Object.values(this.boneShieldTimesByStack).map((e, i) => ( <tr key={i}> <th>{i}</th> <td>{formatDuration(e.reduce((a, b) => a + b, 0) / 1000)}</td> <td>{formatPercentage(e.reduce((a, b) => a + b, 0) / this.owner.fightDuration)}%</td> </tr> ))} </tbody> </table> </StatisticBox> ); } statisticOrder = STATISTIC_ORDER.CORE(5); } export default BoneShield;
    app/javascript/mastodon/components/animated_number.js
    primenumber/mastodon
    import React from 'react'; import PropTypes from 'prop-types'; import { FormattedNumber } from 'react-intl'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { reduceMotion } from 'mastodon/initial_state'; const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; export default class AnimatedNumber extends React.PureComponent { static propTypes = { value: PropTypes.number.isRequired, obfuscate: PropTypes.bool, }; state = { direction: 1, }; componentWillReceiveProps (nextProps) { if (nextProps.value > this.props.value) { this.setState({ direction: 1 }); } else if (nextProps.value < this.props.value) { this.setState({ direction: -1 }); } } willEnter = () => { const { direction } = this.state; return { y: -1 * direction }; } willLeave = () => { const { direction } = this.state; return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) }; } render () { const { value, obfuscate } = this.props; const { direction } = this.state; if (reduceMotion) { return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />; } const styles = [{ key: `${value}`, data: value, style: { y: spring(0, { damping: 35, stiffness: 400 }) }, }]; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <span className='animated-number'> {items.map(({ key, data, style }) => ( <span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span> ))} </span> )} </TransitionMotion> ); } }
    src/index.js
    jcxk/ethercity
    import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import Root from './container/Root'; import configureStore from './store/configureStore'; import { syncHistoryWithStore } from 'react-router-redux'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('app') ); if (module.hot) { module.hot.accept('./container/Root', () => { const NewRoot = require('./container/Root').default; render( <AppContainer> <NewRoot store={store} history={history} /> </AppContainer>, document.getElementById('app') ); }); }
    ui/src/pages/404.js
    danielbh/danielhollcraft.com-gatsbyjs
    import React from 'react' export default ({ data }) => { return ( <section id="one"> <div className="container"> <header className="major" style={{paddingBottom: '45vh'}}> <h2>404 error!</h2> </header> </div> </section> ) }
    src/components/project/ProjectView.js
    omgunis/portfolio
    import React from 'react'; {/* View for single project, /project/:id, imported into ManageProjectPage */} const ProjectView = ({ project }) => { return ( <form> <h1>{ project.title }</h1> </form> ); }; ProjectView.propTypes = { project: React.PropTypes.object.isRequired }; export default ProjectView;
    modules/Route.js
    RickyDan/react-router
    import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './PropTypes'; import warning from 'warning'; var { string, bool, func } = React.PropTypes; /** * A <Route> is used to declare which components are rendered to the page when * the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is requested, * the tree is searched depth-first to find a route whose path matches the URL. * When one is found, all routes in the tree that lead to it are considered * "active" and their components are rendered into the DOM, nested in the same * order as they are in the tree. */ export var Route = React.createClass({ statics: { createRouteFromReactElement(element) { var route = createRouteFromReactElement(element); if (route.handler) { warning(false, '<Route handler> is deprecated, use <Route component> instead'); route.component = route.handler; delete route.handler; } return route; } }, propTypes: { path: string, ignoreScrollBehavior: bool, handler: component, component, components, getComponents: func }, render() { invariant( false, '<Route> elements are for router configuration only and should not be rendered' ); } }); export default Route;
    client/modules/App/__tests__/Components/Footer.spec.js
    trantuthien/React-Test
    import React from 'react'; import test from 'ava'; import { shallow } from 'enzyme'; import { Footer } from '../../components/Footer/Footer'; test('renders the footer properly', t => { const wrapper = shallow( <Footer /> ); t.is(wrapper.find('p').length, 2); t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.'); });
    src/common/components/Routes.js
    GarciaEdgar/firstReactApplication
    import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import LoginPage from '../../pages/login/page'; import HomePage from '../../pages/home/page'; export default ( <Route path="/" component={App}> <IndexRoute component={LoginPage} /> <Route path="home" component={HomePage} /> </Route> );
    app/javascript/src/pages/settings/VerificationView.js
    michelson/chaskiq
    import React from 'react' import Prism from 'prismjs' import { connect } from 'react-redux' import FilterMenu from '../../components/FilterMenu' import Button from '../../components/Button' import Input from '../../components/forms/Input' function VerificationView({app}){ const [currentLang, setCurrentLang] = React.useState("ruby") const [show, setShow] = React.useState(false) function setupScript () { const hostname = window.location.hostname const port = window.location.port ? ':' + window.location.port : '' const secure = window.location.protocol === 'https:' const httpProtocol = window.location.protocol const wsProtocol = secure ? 'wss' : 'ws' const hostnamePort = `${hostname}${port}` const code = ` <script> (function(d,t) { var g=d.createElement(t),s=d.getElementsByTagName(t)[0]; g.src="${httpProtocol}//${hostnamePort}/embed.js" s.parentNode.insertBefore(g,s); g.onload=function(){ new window.ChaskiqMessengerEncrypted({ domain: '${httpProtocol}//${hostnamePort}', ws: '${wsProtocol}://${hostnamePort}/cable', app_id: "${app ? app.key : ''}", data: { email: "[email protected]", identifier_key: "INSERT_HMAC_VALUE_HERE", properties: { } }, lang: "USER_LANG_OR_DEFAULTS_TO_BROWSER_LANG" }) } })(document,"script"); </script> ` return Prism.highlight(code, Prism.languages.javascript, 'javascript') } function keyGeneration () { const code = optionsForFilter().find( (o)=> o.id === currentLang ).code return Prism.highlight(code, Prism.languages.ruby, 'ruby') } function optionsForFilter(){ return [ { title: 'Ruby', description: 'ruby', id: 'ruby', state: 'archived', code: ` OpenSSL::HMAC.hexdigest( 'sha256', # hash function '${app.encryptionKey}', # secret key (keep safe!) current_user.email )` }, { title: 'NodeJs', description: 'nodejs', id: 'nodejs', code: ` const crypto = require('crypto'); const hmac = crypto.createHmac('sha256', '${app.encryptionKey}'); hmac.update('Message'); console.log(hmac.digest('hex'));` }, { title: 'PHP', description: 'PHP', id: 'php', code: ` hash_hmac( 'sha256', // hash function $user->email, // user's id '${app.encryptionKey}' // secret key (keep safe!) );` }, { title: 'Python 3', description: 'python', id: 'python', code: ` import hmac import hashlib hmac.new( b'${app.encryptionKey}', # secret key (keep safe!) bytes(request.user.id, encoding='utf-8'), # user's id digestmod=hashlib.sha256 # hash function ).hexdigest() ` }, { title: 'Golang', description: 'golang', id: 'golang', code: ` package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" ) func ComputeHmac256(message string, secret string) string { key := []byte(secret) h := hmac.New(sha256.New, key) h.Write([]byte(message)) return hex.EncodeToString(h.Sum(nil)) } func main() { fmt.Println(ComputeHmac256("Message", "secret")) // ${app.encryptionKey} } ` } ] } function toggleButton(clickHandler) { return ( <div> <Button variant={'outlined'} onClick={clickHandler}> {currentLang} </Button> </div> ) } function changeLang(item){ setCurrentLang(item.id) } return ( <div className="space-y-6 mx-10-- py-6 text-sm"> <h2 className="text-lg font-bold-">{I18n.t("identified_users.title")}</h2> <div className="flex md:w-1/4 items-center"> <Input label="Identity verification secret" disabled={true} value={app.encryptionKey} type={show ? 'text' : 'password'} helperText={ "Don't share this code" } /> <Button className="ml-2" variant="success" style={{ marginTop: '-12px' }} onClick={()=>setShow(!show)}> show </Button> </div> <p className=""> {I18n.t("identified_users.hint1")} To configure identity verification, you will need to generate an HMAC on your server for each logged in user and submit it to Chaskiq. </p> <p className="font-bold">{I18n.t("identified_users.lang")}</p> <div className="flex justify-between items-center"> <p className="font-bold text-lg">{currentLang}:</p> <div className="flex justify-end"> <FilterMenu options={optionsForFilter()} value={null} filterHandler={changeLang} triggerButton={toggleButton} position={'right'} /> </div> </div> <CodeBox content={keyGeneration()}/> <p dangerouslySetInnerHTML={{__html: I18n.t("identified_users.hint2") }}/> <CodeBox content={setupScript()}/> </div> ) } function CodeBox ({content}){ return ( <pre className="p-3 bg-black rounded-md border-black border-2 dark:border-gray-100 text-white text-sm overflow-auto shadow-sm"> <div dangerouslySetInnerHTML={{__html: content }}/> </pre> ) } function mapStateToProps (state) { const { app } = state return { app } } export default connect(mapStateToProps)(VerificationView)
    auth/src/components/LoginForm.js
    carlosnavarro25/calculadora
    import React, { Component } from 'react'; import { Text } from 'react-native'; import firebase from 'firebase'; import { Button, Card, CardSection, Input, Spinner } from './common'; class LoginForm extends Component { state = { email: '', password: '', error: '', loading: false }; onButtonPress(){ const { email, password } = this.state; this.setState({ error: '', loading: true }); firebase.auth().signInWithEmailAndPassword(email, password) .then(this.onLogInSuccess.bind(this)) .catch(() => { firebase.auth().createUserWithEmailAndPassword(email, password) .then(this.onLogInSuccess.bind(this)) .catch(this.onLogInFail.bind(this)); }); } onLogInFail(){ this.setState({ error:'Authentication Failed', loading: false }); } onLogInSuccess(){ this.setState({ email: '', password: '', loading: false, error: '' }); } renderButton(){ if (this.state.loading){ return <Spinner size="small" />; } return ( <Button onPress={this.onButtonPress.bind(this)}> log in </Button> ); } render(){ return( <Card> <CardSection > <Input placeholder="[email protected]" label="Email" value={this.state.email} onChangeText={email => this.setState({ email })} /> </CardSection> <CardSection> <Input secureTextEntry placeholder="password" label="Pasword" value={this.state.password} onChangeText={password => this.setState({password})} /> </CardSection> <Text style={styles.errorTextStyle}> {this.state.error} </Text> <CardSection> {this.renderButton()} </CardSection> </Card> ); } } const styles ={ errorTextStyle: { fontSize: 20, alignSelf: 'center', color: 'red' } } export default LoginForm;
    src/Dropdown/__tests__/Dropdown_test.js
    react-fabric/react-fabric
    import React from 'react' import { render, mount } from 'enzyme' import test from 'tape' import Dropdown from '..' import events from '../../util/events.js' const defaultOptions = [ { label: 'Foo', value: 'foo' }, { label: 'Bar', value: 'bar' } ] test('Dropdown', t => { t.ok(Dropdown, 'export') t.equal(Dropdown.displayName, 'FabricComponent(Dropdown)') t.end() }) test('Dropdown#render - simple', t => { const container = render( <Dropdown options={defaultOptions} /> ).contents() t.assert(container.is('div.ms-Dropdown', 'container')) t.assert(container.is('[data-fabric="Dropdown"]'), 'data-fabric') t.equal(container.find('.ms-Dropdown-items > .ms-Dropdown-item').length, defaultOptions.length) t.end() }) test('Dropdown lifecycle - unmount', t => { t.plan(1) const removeEventsFromDocument = events.removeEventsFromDocument events.removeEventsFromDocument = ({ click }) => { t.ok(click) } const wrapper = mount( <Dropdown active options={defaultOptions} /> ) wrapper.unmount() events.removeEventsFromDocument = removeEventsFromDocument }) test('Dropdown lifecycle - update', t => { t.plan(2) const addEventsToDocument = events.addEventsToDocument const removeEventsFromDocument = events.removeEventsFromDocument events.addEventsToDocument = ({ click }) => { t.ok(click, 'add click handler') } events.removeEventsFromDocument = ({ click }) => { t.ok(click) } const wrapper = mount( <Dropdown options={defaultOptions} /> ) wrapper.setProps({ active: true }) wrapper.setProps({ active: false }) events.addEventsToDocument = addEventsToDocument events.removeEventsFromDocument = removeEventsFromDocument }) test('Dropdown - blur', t => { t.plan(1) const handleBlur = e => t.ok(e, 'blur called') const wrapper = mount( <Dropdown onBlur={handleBlur} options={defaultOptions} /> ) wrapper.setProps({ active: true }) const event = document.createEvent('HTMLEvents') event.initEvent('click', true, false) document.body.dispatchEvent(event) }) test('Dropdown - focus', t => { t.plan(1) const handleFocus = e => t.ok(e, 'focus called') const wrapper = mount( <Dropdown onFocus={handleFocus} options={defaultOptions} /> ) wrapper.find('.ms-Dropdown-title').simulate('mouseDown') }) test('Dropdown - select', t => { t.plan(2) const handleBlur = e => t.equal(e.target.value, 'foo', 'blur called') const handleChange = e => t.ok(e.target.value, 'foo', 'change called') const wrapper = mount( <Dropdown onBlur={handleBlur} onChange={handleChange} value={null} options={defaultOptions} /> ) wrapper.setProps({ active: true }) wrapper.find('.ms-Dropdown-item > div').first().simulate('mouseDown') t.end() })
    src/components/GoogleMapContainer/RichMarker.js
    joelvoss/react-gmaps
    import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOMServer from 'react-dom/server'; import createElementFromString from 'utilities/createElementFromString'; import CustomMarker from 'components/CustomMarker'; /** * This component represents an overlay view. */ class RichMarker extends Component { // PropTypes static propTypes = { google: PropTypes.object.isRequired, map: PropTypes.object.isRequired, data: PropTypes.object.isRequired, handleClick: PropTypes.func }; /** * On mount, initialize the factory OverlayView instance provided by google * and set the three default methods "onAdd", "draw" and "onRemove". */ componentDidMount() { const { google, map } = this.props; this.richMarker = new google.maps.OverlayView(); this.richMarker.onAdd = this.onAdd; this.richMarker.draw = this.draw; this.richMarker.onRemove = this.onRemove; this.richMarker.setMap(map); } /** * When the component unmounts, set the map of the overlayview to null. * This calls the "onRemove" method of this class. */ componentWillUnmount() { this.richMarker.setMap(null); } /** * Google maps calls this method as soon as the overlayview can be drawn onto * the overlay map pane. * * This method gets called only once! */ onAdd = () => { const { data, handleClick } = this.props; const html = ReactDOMServer.renderToStaticMarkup( <CustomMarker delay={Math.floor(Math.random() * 10) + 1} /> ); this.markerItem = createElementFromString(html); // Add a standard eventlistener for a click event of the static markup // react component, since a marker is not a seperate react app. this.markerItem.addEventListener('click', (e) => { // prevent event bubbling and propagation e.stopPropagation(); e.preventDefault(); // execute the custom click event handler which was passed down to the overlay component. handleClick(data.id) }); const panes = this.richMarker.getPanes(); panes.overlayMouseTarget.appendChild(this.markerItem); }; /** * This method gets called each time the current maps viewport or zoom-level changes. * In here we convert the lat/lng values to pixel values and position the overlay. */ draw = () => { const { google, data } = this.props; const latlng = new google.maps.LatLng(data.geometry.location.lat, data.geometry.location.lng); const point = this.richMarker.getProjection().fromLatLngToDivPixel(latlng); if (point) { this.markerItem.style.left = point.x + 'px'; this.markerItem.style.top = point.y + 'px'; } }; /** * This method gets called as soon as we set the map property of * the overlayview to null. We remove all event listener and delete the * dom representation. */ onRemove = () => { if (this.markerItem) { this.markerItem.parentNode.removeChild(this.markerItem); this.markerItem = null; } }; render() { return null; } } export default RichMarker;
    src/app.js
    fjoder/indecision-app
    import React from 'react'; import ReactDOM from 'react-dom'; import IndecisionApp from './components/IndecisionApp'; import 'normalize.css/normalize.css'; import './styles/styles.scss'; ReactDOM.render(<IndecisionApp />, document.getElementById('app'));
    src/svg-icons/maps/train.js
    ruifortes/material-ui
    import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsTrain = (props) => ( <SvgIcon {...props}> <path d="M12 2c-4 0-8 .5-8 4v9.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h2.23l2-2H14l2 2h2v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V6c0-3.5-3.58-4-8-4zM7.5 17c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm3.5-7H6V6h5v4zm2 0V6h5v4h-5zm3.5 7c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/> </SvgIcon> ); MapsTrain = pure(MapsTrain); MapsTrain.displayName = 'MapsTrain'; MapsTrain.muiName = 'SvgIcon'; export default MapsTrain;
    src/assets/js/react/components/FontManager/AddFont.js
    GravityPDF/gravity-forms-pdf-extended
    /* Dependencies */ import React from 'react' import PropTypes from 'prop-types' import { sprintf } from 'sprintf-js' /* Components */ import FontVariant from './FontVariant' import AddUpdateFontFooter from './AddUpdateFontFooter' /** * @package Gravity PDF * @copyright Copyright (c) 2021, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 6.0 */ /** * Display add font panel UI * * @param label * @param onHandleInputChange * @param onHandleUpload * @param onHandleDeleteFontStyle * @param onHandleSubmit * @param fontStyles * @param validateLabel * @param validateRegular * @param msg * @param loading * @param tabIndexFontName * @param tabIndexFontFiles * @param tabIndexFooterButtons * * @since 6.0 */ export const AddFont = ( { label, onHandleInputChange, onHandleUpload, onHandleDeleteFontStyle, onHandleSubmit, fontStyles, validateLabel, validateRegular, msg, loading, tabIndexFontName, tabIndexFontFiles, tabIndexFooterButtons } ) => { const fontNameLabel = sprintf(GFPDF.fontManagerFontNameLabel, "<span class='required'>", '</span>') return ( <div data-test='component-AddFont' className='add-font'> <form onSubmit={onHandleSubmit}> <h2>{GFPDF.fontManagerAddTitle}</h2> <p>{GFPDF.fontManagerAddDesc}</p> <label htmlFor='gfpdf-font-name-input' dangerouslySetInnerHTML={{ __html: fontNameLabel }} /> <p id='gfpdf-font-name-desc-add'>{GFPDF.fontManagerFontNameDesc}</p> <input type='text' id='gfpdf-add-font-name-input' className={!validateLabel ? 'input-label-validation-error' : ''} aria-describedby='gfpdf-font-name-desc-add' name='label' value={label} maxLength='60' onChange={e => onHandleInputChange(e, 'addFont')} tabIndex={tabIndexFontName} /> <div aria-live='polite'> {!validateLabel && ( <span className='required' role='alert'> <em>{GFPDF.fontManagerFontNameValidationError}</em> </span> )} </div> <label id='gfpdf-font-files-label-add' aria-labelledby='gfpdf-font-files-description-add'>{GFPDF.fontManagerFontFilesLabel}</label> <p id='gfpdf-font-files-description-add'>{GFPDF.fontManagerFontFilesDesc}</p> <FontVariant state='addFont' fontStyles={fontStyles} validateRegular={validateRegular} onHandleUpload={onHandleUpload} onHandleDeleteFontStyle={onHandleDeleteFontStyle} msg={msg} tabIndex={tabIndexFontFiles} /> <AddUpdateFontFooter state='addFont' msg={msg} loading={loading} tabIndex={tabIndexFooterButtons} /> </form> </div> ) } /** * PropTypes * * @since 6.0 */ AddFont.propTypes = { label: PropTypes.string.isRequired, onHandleInputChange: PropTypes.func.isRequired, onHandleUpload: PropTypes.func.isRequired, onHandleDeleteFontStyle: PropTypes.func.isRequired, onHandleSubmit: PropTypes.func.isRequired, validateLabel: PropTypes.bool.isRequired, validateRegular: PropTypes.bool.isRequired, fontStyles: PropTypes.object.isRequired, msg: PropTypes.object.isRequired, loading: PropTypes.bool.isRequired, tabIndexFontName: PropTypes.string.isRequired, tabIndexFontFiles: PropTypes.string.isRequired, tabIndexFooterButtons: PropTypes.string.isRequired } export default AddFont
    src/svg-icons/action/note-add.js
    xmityaz/material-ui
    import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionNoteAdd = (props) => ( <SvgIcon {...props}> <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 14h-3v3h-2v-3H8v-2h3v-3h2v3h3v2zm-3-7V3.5L18.5 9H13z"/> </SvgIcon> ); ActionNoteAdd = pure(ActionNoteAdd); ActionNoteAdd.displayName = 'ActionNoteAdd'; ActionNoteAdd.muiName = 'SvgIcon'; export default ActionNoteAdd;
    index.ios.js
    denistakeda/LifeBalance
    import React from 'react'; import { AppRegistry } from 'react-native'; import App from './src/mobile/App'; const LifeBalance = () => { return ( <App /> ); }; AppRegistry.registerComponent('LifeBalance', () => LifeBalance); export default LifeBalance;
    lib/ui/core.js
    Markcial/electro-corder
    import React from 'react'; import range from '../misc/utils'; export class Button extends React.Component { constructor(props) { super(props); this.state = { label: props.label, click: props.click }; } click (evt) { this.state.click(evt); } render() { return ( <button onClick={(e) => this.click(e)}>{this.state.label}</button> ); } } Button.propTypes = { label: React.PropTypes.string, click: React.PropTypes.function }; Button.defaultProps = { label: 'Button', click: () => {} }; export class Slider extends React.Component { constructor(props) { super(props); this.state = { defaultValue:props.defaultValue, orientation:props.orientation, min:props.min, max:props.max, onSlide:props.onSlide } } componentDidMount () { React.findDOMNode(this).style['-webkit-appearance'] = `slider-${this.props.orientation}`; } onSlide (evt) { this.props.onSlide(evt); } render () { return ( <input type="range" onChange={(e) => this.onSlide(e)} defaultValue={this.props.defaultValue} min={this.props.min} max={this.props.max} orientation={this.props.orientation} /> ); } } Slider.PropTypes = { defaultValue: React.PropTypes.int, orientation: React.PropTypes.string, min: React.PropTypes.integer, max: React.PropTypes.integer, onSlide: React.PropTypes.func } Slider.defaultProps = { defaultValue: 0, orientation: "horizontal", min: 0, max: 100, onSlide: (e) => {} } export class Timer extends React.Component { constructor(props) { super(props); this.state = {seconds: props.seconds}; } onTimerTick (seconds) {} onTimerEnd () {} componentDidMount () {} stopTimer() { clearInterval(this.intervalID); } resetTimer() { this.stopTimer(); this.setState({seconds:this.props.seconds}); this.startTimer(); } startTimer () { this.stopTimer(); this.intervalID = setInterval(() => { if (this.state.seconds > 0) { this.onTimerTick(this.state.seconds); this.tick(); } else { this.stopTimer(); this.onTimerEnd(); } }, 1000); } tick() { this.setState({ seconds: this.state.seconds - 1 }); } render() { return ( <div> Seconds left: {this.state.seconds} </div> ); } } Timer.propTypes = { seconds: React.PropTypes.number }; Timer.defaultProps = { seconds: 10 }; export class Preview extends React.Component { startRecording () { navigator.webkitGetUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'screen', maxWidth: screen.availWidth, maxHeight: screen.availHeight, maxFrameRate: 25 }, optional: [] } }, (stream) => this.onStartRecording(stream), (error) => this.onStreamError(error)); } onStartRecording (stream) { this.video = React.findDOMNode(this.refs.video); this.video.style.display = 'none'; this.video.muted = true; this.video.autoplay = true; this.video.src = URL.createObjectURL(stream); this.canvas = React.findDOMNode(this.refs.preview); this.context = this.canvas.getContext("2d"); this.enrichenCanvasContext(this.context); requestAnimationFrame(() => {this.drawPreview()}) } drawPreview() { requestAnimationFrame(() => {this.drawPreview()}); this.context.drawImage(this.video, 0, 0); } onStreamError (error) { console.log(error); } componentDidMount () { this.startRecording(); } onVideoClick (evt) { console.log(evt); } onWheel (evt) { var lastX=this.canvas.width/2, lastY=this.canvas.height/2; var pt = this.context.transformedPoint(lastX,lastY); console.log(evt.deltaY); if (evt.deltaY > 0) { var scale = 0.9; } else { var scale = 1.1; } this.context.translate(pt.x,pt.y); this.context.scale(scale, scale); this.context.translate(-pt.x,-pt.y); } enrichenCanvasContext(ctx) { var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg'); var xform = svg.createSVGMatrix(); ctx.getTransform = function(){ return xform; }; var savedTransforms = []; var save = ctx.save; ctx.save = function(){ savedTransforms.push(xform.translate(0,0)); return save.call(ctx); }; var restore = ctx.restore; ctx.restore = function(){ xform = savedTransforms.pop(); return restore.call(ctx); }; var scale = ctx.scale; ctx.scale = function(sx,sy){ xform = xform.scaleNonUniform(sx,sy); return scale.call(ctx,sx,sy); }; var rotate = ctx.rotate; ctx.rotate = function(radians){ xform = xform.rotate(radians*180/Math.PI); return rotate.call(ctx,radians); }; var translate = ctx.translate; ctx.translate = function(dx,dy){ xform = xform.translate(dx,dy); return translate.call(ctx,dx,dy); }; var transform = ctx.transform; ctx.transform = function(a,b,c,d,e,f){ var m2 = svg.createSVGMatrix(); m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f; xform = xform.multiply(m2); return transform.call(ctx,a,b,c,d,e,f); }; var setTransform = ctx.setTransform; ctx.setTransform = function(a,b,c,d,e,f){ xform.a = a; xform.b = b; xform.c = c; xform.d = d; xform.e = e; xform.f = f; return setTransform.call(ctx,a,b,c,d,e,f); }; var pt = svg.createSVGPoint(); ctx.transformedPoint = function(x,y){ pt.x=x; pt.y=y; return pt.matrixTransform(xform.inverse()); } } render () { return ( <div> <video ref="video" /> <canvas ref="preview" width="420" height="240" onWheel={(evt) => this.onWheel(evt)} onClick={(evt) => this.onVideoClick(evt)} /> </div> ) } }
    app/javascript/mastodon/components/status_content.js
    alarky/mastodon
    import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import escapeTextContentForBrowser from 'escape-html'; import PropTypes from 'prop-types'; import emojify from '../emoji'; import { isRtl } from '../rtl'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, onExpandedToggle: PropTypes.func, onHeightUpdate: PropTypes.func, onClick: PropTypes.func, }; state = { hidden: true, }; componentDidMount () { const node = this.node; const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener'); link.setAttribute('title', link.href); } } } componentDidUpdate () { if (this.props.onHeightUpdate) { this.props.onHeightUpdate(); } } onMentionClick = (mention, e) => { if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${mention.get('id')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, '').toLowerCase(); if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/timelines/tag/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) { return; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const content = { __html: emojify(status.get('content')) }; const spoilerContent = { __html: emojify(escapeTextContentForBrowser(status.get('spoiler_text', ''))) }; const directionStyle = { direction: 'ltr' }; if (isRtl(status.get('search_index'))) { directionStyle.direction = 'rtl'; } if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className='status__content status__content--with-action' ref={this.setRef} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} /> {' '} <button tabIndex='0' className='status__content__spoiler-link' onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} /> </div> ); } else if (this.props.onClick) { return ( <div ref={this.setRef} className='status__content status__content--with-action' style={directionStyle} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} dangerouslySetInnerHTML={content} /> ); } else { return ( <div ref={this.setRef} className='status__content' style={directionStyle} dangerouslySetInnerHTML={content} /> ); } } }
    boxroom/archive/backup-js-glow-2018-01-28/boxroom/archive/js-surface-2018-01-27/boxroom/archive/2018-01-11/src/main/js-surface-react-native.js
    js-works/js-surface
    import adaptReactLikeComponentSystem from './adaption/adaptReactLikeComponentSystem'; import React from 'react'; import ReactNative from 'react-native'; const { createElement, defineComponent, isElement, mount, unmount, Adapter, Config } = adaptReactLikeComponentSystem({ name: 'react-native', api: { React, ReactNative }, createElement: React.createElement, createFactory: React.createFactory, isValidElement: React.isValidElement, mount: reactNativeMount, Component: React.Component, browserBased: false }); export { createElement, defineComponent, isElement, mount, unmount, Adapter, Config }; function reactNativeMount(Component) { ReactNative.AppRegistry.registerComponent('AppMainComponent', () => Component); }
    src/routes/gallery/Gallery.js
    malinowsky/dataroot_03
    /** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Contact from '../../components/Contact'; import Gallery from '../../components/Gallery'; import s from './Gallery.scss'; class GalleryR extends React.Component { render() { return ( <div className={s.root}> <Gallery/> <Contact/> </div> ); } } export default withStyles(s)(GalleryR);
    test/test_helper.js
    YacYac/ReduxSimpleStarter
    import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
    src/components/cart/cartCheckOut/CartCheckOutListItemComponent.js
    bluebill1049/cart
    'use strict'; import React from 'react'; require('styles/cart/cartCheckOut/CartCheckOutListItem.scss'); class CartCheckOutListItemComponent extends React.Component { constructor(props) { super(props) } render() { return ( <li className="cartlistitem-component clearfix"> <img src={this.props.assets[this.props.item.fields.itemImage.sys.id]} /> <div className="cartlistitem-component__brief"> <h3>{this.props.item.fields.itemName}</h3> <p>{this.props.item.fields.itemShortDescription}</p> <p className="cartlistitem-component__price">${this.props.item.fields.price}</p> </div> <div className="cartlistitem-component__price-section"> <button className="small round alert" onClick={this.props.removeItem.bind(this, this.props.item.id, this.props.itemIndex)}>删除</button> </div> </li> ); } } CartCheckOutListItemComponent.displayName = 'CartCartCheckOutCartCheckOutListItemComponent'; // Uncomment properties you need CartCheckOutListItemComponent.propTypes = { item : React.PropTypes.object.isRequired, removeItem : React.PropTypes.func.isRequired, itemIndex : React.PropTypes.number.isRequired // viewDetail : React.PropTypes.func.isRequired }; // CartCheckOutListItemComponent.defaultProps = {}; export default CartCheckOutListItemComponent;
    src/components/SegmentedControl.js
    pairyo/elemental
    import classnames from 'classnames'; import React from 'react'; module.exports = React.createClass({ displayName: 'SegmentedControl', propTypes: { className: React.PropTypes.string, equalWidthSegments: React.PropTypes.bool, onChange: React.PropTypes.func.isRequired, options: React.PropTypes.array.isRequired, type: React.PropTypes.oneOf(['default', 'muted', 'danger', 'info', 'primary', 'success', 'warning']), value: React.PropTypes.string }, getDefaultProps () { return { type: 'default' }; }, onChange (value) { this.props.onChange(value); }, render () { let componentClassName = classnames('SegmentedControl', ('SegmentedControl--' + this.props.type), { 'SegmentedControl--equal-widths': this.props.equalWidthSegments }, this.props.className); let options = this.props.options.map((op) => { let buttonClassName = classnames('SegmentedControl__button', { 'is-selected': op.value === this.props.value }); return ( <span key={'option-' + op.value} className="SegmentedControl__item"> <button type="button" onClick={this.onChange.bind(this, op.value)} className={buttonClassName}> {op.label} </button> </span> ); }); return <div className={componentClassName}>{options}</div>; } });
    src/app.react.js
    JasonStoltz/test-runner-demo
    import {connect} from 'react-redux'; import {List} from 'immutable'; import React from 'react'; import Promise from 'bluebird'; import PureComponent from 'react-pure-render/component'; import TestsService from './model/test'; import mapStateToProps from './lib/mapStateToProps'; import mapDispatchToProps from './lib/mapDispatchToProps'; import * as actions from './store/tests/actions'; import * as TestConstants from './model/test'; import Test from './model/test'; import * as TestsConstants from './store/tests/reducers'; import Tests from './components/runner/tests.react.js'; import Status from './components/runner/status.react'; @connect(mapStateToProps('tests'), mapDispatchToProps(actions)) export default class App extends PureComponent { static propTypes = { tests: React.PropTypes.object.isRequired, actions: React.PropTypes.object.isRequired }; constructor() { super(); this.run = this.run.bind(this); //So we don't break pure render } render() { const {tests} = this.props; return ( <div> <div> <h1>Tests</h1> {tests.get('status') === TestsConstants.FINISHED && <div>FINISHED!</div> } <Tests tests={tests.get('tests')} /> <div> <button onClick={this.run} disabled={tests.get('status') === TestsConstants.RUNNING}>Run</button> </div> <Status running={tests.get('running')} failed={tests.get('failed')} passed={tests.get('passed')} /> </div> </div> ); } componentDidMount() { const {actions} = this.props; const tests = Test.all(); actions.setTests(tests); } run(e) { e.preventDefault(); const {actions} = this.props; const tests = this.props.tests.get('tests'); tests.forEach(test => { actions.setStatus(test.get('id'), TestConstants.RUNNING); TestsService.run(test.get('id')).then(result => { actions.setStatus(test.get('id'), (result) ? TestConstants.PASSED : TestConstants.FAILED); }); }); } }
    src/components/Scheme/HypertensionC.js
    lethecoa/work-order-pc
    import React from 'react'; import {Form, InputNumber, Row, Col} from 'antd'; import styles from './Scheme.less'; const FormItem = Form.Item; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 8 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 }, }, }; class HypertensionC extends React.Component { state = { scheme: {}, }; componentWillMount() { this.setState( { scheme: this.props.scheme } ); } componentWillReceiveProps( nextProps ) { this.setState( { scheme: nextProps.scheme } ); } render() { const { getFieldDecorator } = this.props.form; const disabled = this.props.disabled; const { scheme } = this.state; return ( <div className={styles.need}> <div className={styles.title}>随访项目</div> <div className={styles.form}> <Row> <Col span={12}> <FormItem {...formItemLayout} label="舒张压(mmHg)"> {getFieldDecorator( 'sbp', { initialValue: scheme.sbp } )( <InputNumber min={1} max={300} style={{ width: 200 }} disabled={disabled} placeholder="请输入1-300之间的一个数值"/> )} </FormItem> </Col> <Col span={12}> <FormItem {...formItemLayout} label="收缩压(mmHg)"> {getFieldDecorator( 'dbp', { initialValue: scheme.dbp } )( <InputNumber min={1} max={300} style={{ width: 200 }} disabled={disabled} placeholder="请输入1-300之间的一个数值"/> )} </FormItem> </Col> </Row> </div> </div> ); } } export default Form.create()( HypertensionC );
    src/components/pages/NotFoundPage.js
    mm-taigarevolution/tas_web_app
    import React from 'react'; import { Link } from 'react-router-dom'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
    app/views/Homepage/components/RetroTitanic.js
    herereadthis/redwall
    import React from 'react'; import AppConstants from 'AppConstants'; export default class RetroTitantic extends React.Component { constructor() { super(); } componentWillMount() { } componentDidMount() { } render() { var titanticStyle; titanticStyle = { paddingTop: '2rem', paddingBottom: '1rem' }; return ( <article id="retro_art" className="starfield parallax_scroll" data-parallax-speed="250" ref="starfield" style={titanticStyle}> <h2>Here are some awesome thing!</h2> <section className="bellmaker_container geocities_me"> <h3>1997 was the best year ever!</h3> <div className="centered_image"> {AppConstants.dataSprite('titanic_468x60')} </div> </section> </article> ); } }
    src/js/component/ClearCompleted.js
    dtk0528/TODOs
    import React, { Component } from 'react'; class ClearCompleted extends Component { render() { let clearButton = null; if (this.props.itemCount > 0) { clearButton = ( <button className="clear-completed" onClick={ this.props.onButtonClick } >Clear</button> ); } return ( <div> { clearButton } </div> ); } } export default ClearCompleted;
    src/mobile/routes.js
    Perslu/rerebrace
    import chalk from 'chalk'; import { injectReducer } from './redux/reducers'; import React from 'react'; import { Route, IndexRoute } from 'react-router/es6'; import App from './App' import GalleryView from './public/containers/GalleryView'; import ProfileView from './public/containers/ProfileView'; // import Home from './Home' import UserInfo from './UserInfo' import NotFound from './NotFound' const errorLoading = (err) => { console.error(chalk.red(`==> 😭 Dynamic page loading failed ${err}`)); }; const loadModule = cb => (Component) => { cb(null, Component.default); }; export default ( <Route path="/" component={App}> <IndexRoute component={GalleryView} /> <Route path="/userinfo" component={UserInfo} /> <Route path="/profile/:profileId" component={ProfileView} /> <Route path="/*" component={NotFound} /> </Route> ) // export default function createRoutes(store) { // return { // path: '/', // component: App, // indexRoute: Home, // childRoutes: [ // { // path: 'UserInfo/:id', // // getComponent(location, cb) { // const importModules = Promise.all([ // System.import('./UserInfo'), // // System.import('./UserInfo/reducer'), // ]); // // const renderRoute = loadModule(cb); // // importModules // .then(([Component/*, reducer*/]) => { // // injectReducer(store, 'userInfo', reducer.default); // // renderRoute(Component); // }) // .catch(errorLoading); // }, // }, // { // path: '*', // getComponent(location, cb) { // System.import('./NotFound') // .then(loadModule(cb)) // .catch(errorLoading); // }, // }, // ], // }; // }
    app/javascript/mastodon/components/radio_button.js
    kirakiratter/mastodon
    import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class RadioButton extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, checked: PropTypes.bool, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, label: PropTypes.node.isRequired, }; render () { const { name, value, checked, onChange, label } = this.props; return ( <label className='radio-button'> <input name={name} type='radio' value={value} checked={checked} onChange={onChange} /> <span className={classNames('radio-button__input', { checked })} /> <span>{label}</span> </label> ); } }
    client/src/components/Polls.js
    NicholasAsimov/voting-app
    import React from 'react'; import { connect } from 'react-redux'; import Poll from './Poll'; import { Link } from 'react-router'; import { LinkContainer } from 'react-router-bootstrap'; import { ListGroup, ListGroupItem } from 'react-bootstrap'; class Polls extends React.Component { render() { return ( <div> <h2>Public polls</h2> <p>Select a poll to see the results and vote, or make a <Link to="/newpoll">new poll</Link>!</p> <ListGroup> {this.props.polls.map((poll, index) => ( <LinkContainer to={"/poll/" + poll._id} key={index}> <ListGroupItem>{poll.title}</ListGroupItem> </LinkContainer> ))} </ListGroup> </div> ) } } function mapStateToProps(state) { return { polls: state.polls }; } export default connect(mapStateToProps)(Polls);
    src/icons/AndroidAdd.js
    fbfeix/react-icons
    import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class AndroidAdd extends React.Component { render() { if(this.props.bare) { return <g> <g id="Icon_7_"> <g> <path d="M416,277.333H277.333V416h-42.666V277.333H96v-42.666h138.667V96h42.666v138.667H416V277.333z"></path> </g> </g> </g>; } return <IconBase> <g id="Icon_7_"> <g> <path d="M416,277.333H277.333V416h-42.666V277.333H96v-42.666h138.667V96h42.666v138.667H416V277.333z"></path> </g> </g> </IconBase>; } };AndroidAdd.defaultProps = {bare: false}
    src/components/GroceryList.js
    clayhan/reactserver
    import React from 'react'; export default class GroceryList extends React.Component { constructor(props) { super(props); this.state = { clickedItems: [] }; this.handleClick = this.handleClick.bind(this); } handleClick(e) { const clickedItems = this.state.clickedItems.slice(); clickedItems.push(e.target.textContent); this.setState({ clickedItems: clickedItems }); } render() { console.log('FE Render: GroceryList'); return ( <div className='component grocerylist'> <div>GroceryList Component</div> <h3>Ingredients:</h3> <div> <ol> {this.props.ingredients.map((ingredient) => { return <li onClick={this.handleClick}>{ingredient}</li> })} </ol> </div> <div> <h6>Things I need to buy:</h6> <ul> {this.state.clickedItems.map((item) => { return <li>{item}</li> })} </ul> </div> </div> ); } }
    src/Containers/Top10/Top10.js
    rahulp959/airstats.web
    import React from 'react' import {connect} from 'react-redux' import TableTop from './TableTop/TableTop' import './Top10.scss' import { fetchTop10 } from '../../ducks/top10.js' let top10Dispatcher const refreshTime = 60 * 30 * 1000 // Once per half-hour class Top10 extends React.Component { componentDidMount () { this.props.dispatch(fetchTop10()) top10Dispatcher = setInterval(() => this.props.dispatch(fetchTop10()), refreshTime) } componentWillUnmount () { clearInterval(top10Dispatcher) } render () { console.dir(this.props.top10) let html = '' if (this.props.top10.get('isFetching') === true) { html = 'Loading...' } else { html = ( <div className='top10'> <div className='topbox'> <div className='title'>Top Departures</div> <TableTop data={this.props.top10.getIn(['data', 'departures'])} /> </div> <div className='topbox'> <div className='title'>Top Arrivals</div> <TableTop data={this.props.top10.getIn(['data', 'arrivals'])} /> </div> </div> ) } return ( <div className='topcontainer'> <p>Top 10 airports by types of operations within the past 7 days.</p> {html} <p>Last updated: {this.props.top10.getIn(['data', 'updated'])}Z</p> </div> ) } } const mapStateToProps = state => { return { top10: state.get('top10') } } export default connect(mapStateToProps)(Top10)
    src/router.js
    ITenTeges/portfolioPage
    /** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-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'; function decodeParam(val) { if (!(typeof val === 'string' || val.length === 0)) { return val; } try { return decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { err.message = `Failed to decode param '${val}'`; err.status = 400; } throw err; } } // Match the provided URL path pattern to an actual URI string. For example: // matchURI({ path: '/posts/:id' }, '/dummy') => null // matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 } function matchURI(route, path) { const match = route.pattern.exec(path); if (!match) { return null; } const params = Object.create(null); for (let i = 1; i < match.length; i += 1) { params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined; } return params; } // Find the route matching the specified location (context), fetch the required data, // instantiate and return a React component function resolve(routes, context) { for (const route of routes) { // eslint-disable-line no-restricted-syntax const params = matchURI(route, context.error ? '/error' : context.pathname); if (!params) { continue; // eslint-disable-line no-continue } // Check if the route has any data requirements, for example: // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' } if (route.data) { // Load page component and all required data in parallel const keys = Object.keys(route.data); return Promise.all([ route.load(), ...keys.map((key) => { const query = route.data[key]; const method = query.substring(0, query.indexOf(' ')); // GET let url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id // TODO: Optimize Object.keys(params).forEach((k) => { url = url.replace(`${k}`, params[k]); }); return fetch(url, { method }).then(resp => resp.json()); }), ]).then(([Page, ...data]) => { const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {}); return <Page route={{ ...route, params }} error={context.error} {...props} />; }); } return route.load().then(Page => <Page route={{ ...route, params }} error={context.error} />); } const error = new Error('Page not found'); error.status = 404; return Promise.reject(error); } export default { resolve };
    examples/huge-apps/routes/Course/components/Course.js
    AnSavvides/react-router
    import React from 'react'; import Dashboard from './Dashboard'; import Nav from './Nav'; var styles = {}; styles.sidebar = { float: 'left', width: 200, padding: 20, borderRight: '1px solid #aaa', marginRight: 20 }; class Course extends React.Component { render () { let { children, params } = this.props; let course = COURSES[params.courseId]; return ( <div> <h2>{course.name}</h2> <Nav course={course} /> {children && children.sidebar && children.main ? ( <div> <div className="Sidebar" style={styles.sidebar}> {children.sidebar} </div> <div className="Main" style={{padding: 20}}> {children.main} </div> </div> ) : ( <Dashboard /> )} </div> ); } } export default Course;
    components/Login/ReviseUser.js
    slidewiki/slidewiki-platform
    import PropTypes from 'prop-types'; import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import {navigateAction} from 'fluxible-router'; import {connectToStores} from 'fluxible-addons-react'; import checkEmail from '../../actions/user/registration/checkEmail'; import checkUsername from '../../actions/user/registration/checkUsername'; import UserRegistrationStore from '../../stores/UserRegistrationStore'; import SSOStore from '../../stores/SSOStore'; import common from '../../common'; import finalizeMergedUser from '../../actions/user/finalizeMergedUser'; import instances from '../../configs/instances.js'; import {FormattedMessage, defineMessages} from 'react-intl'; const headerStyle = { 'textAlign': 'center' }; const modalStyle = { top: '15%' }; class ReviseUser extends React.Component { constructor(props) { super(props); this.errorMessages = defineMessages({ error409: { id: 'SSOSignIn.errormessage.isForbidden', defaultMessage: 'Migration is not possible with this user. Please start all over again.' }, error404: { id: 'SSOSignIn.errormessage.accountNotFound', defaultMessage: 'This account was not prepared for migration. Please start all over again.' }, error500: { id: 'SSOSignIn.errormessage.badImplementation', defaultMessage: 'An unknown error occurred.' } }); } componentDidMount() { //Form validation const validationRules = { fields: { username: { identifier: 'username', rules: [{ type: 'empty', prompt: 'Please select your username' }, { type: 'uniqueUsername', prompt: 'The username is already in use' }, { type : 'maxLength[64]', prompt : 'Your username can not be longer than 64 characters' }, { type : 'regExp[/^[a-zA-Z0-9-.~_]+$/i]', prompt : 'The username must contain only alphanumeric characters plus the following: _ . - ~' }] }, email: { identifier: 'email', rules: [{ type: 'empty', prompt: 'Please enter your email address' }, { type: 'email', prompt: 'Please enter a valid email address' }, { type: 'uniqueEmail', prompt: 'The email address is already in use' }] } }, onSuccess: this.handleSignUp.bind(this) }; $.fn.form.settings.rules.uniqueEmail = (() => { const emailNotAllowed = this.props.UserRegistrationStore.failures.emailNotAllowed; return (emailNotAllowed !== undefined) ? !emailNotAllowed : true; }); $.fn.form.settings.rules.uniqueUsername = (() => { const usernameNotAllowed = this.props.UserRegistrationStore.failures.usernameNotAllowed; return (usernameNotAllowed !== undefined) ? !usernameNotAllowed : true; }); $(ReactDOM.findDOMNode(this.refs.ReviseUser_form)).form(validationRules); } componentWillReceiveProps(nextProps) { console.log('ReviseUser componentWillReceiveProps()', this.props.UserRegistrationStore.socialuserdata, nextProps.UserRegistrationStore.socialuserdata, this.props.SSOStore.username, nextProps.SSOStore.username); if (nextProps.SSOStore.username !== this.props.SSOStore.username) { this.refs.username.value = nextProps.SSOStore.username; this.refs.email.value = nextProps.SSOStore.email; this.checkUsername(); this.checkEmail(); } } handleSignUp(e) { e.preventDefault(); let user = {}; user.email = this.refs.email.value; user.username = this.refs.username.value; user.hash = this.props.SSOStore.hash; let language = common.getIntlLanguage(); user.language = language; user.url = instances[instances._self].finalize.replace('{hash}', user.hash); user.errorMessages = { error409: this.context.intl.formatMessage(this.errorMessages.error409), error404: this.context.intl.formatMessage(this.errorMessages.error404), error500: this.context.intl.formatMessage(this.errorMessages.error500) }; this.context.executeAction(finalizeMergedUser, user); $(ReactDOM.findDOMNode(this.refs.ReviseUser_Modal)).modal('hide'); return false; } checkEmail() { const email = this.refs.email.value; if (this.props.UserRegistrationStore.failures.usernameNotAllowed !== undefined || email !== '') { this.context.executeAction(checkEmail, {email: email}); } } checkUsername() { const username = this.refs.username.value; if (this.props.UserRegistrationStore.failures.usernameNotAllowed !== undefined || username !== '') { this.context.executeAction(checkUsername, {username: username}); } } render() { const signUpLabelStyle = {width: '150px'}; const emailNotAllowed = this.props.UserRegistrationStore.failures.emailNotAllowed; let emailClasses = classNames({ 'ui': true, 'field': true, 'inline': true, 'error': (emailNotAllowed !== undefined) ? emailNotAllowed : false }); let emailIconClasses = classNames({ 'icon': true, 'inverted circular red remove': (emailNotAllowed !== undefined) ? emailNotAllowed : false, 'inverted circular green checkmark': (emailNotAllowed !== undefined) ? !emailNotAllowed : false }); let emailToolTipp = emailNotAllowed ? 'This E-Mail has already been used by someone else. Please choose another one.' : undefined; const usernameNotAllowed = this.props.UserRegistrationStore.failures.usernameNotAllowed; let usernameClasses = classNames({ 'ui': true, 'field': true, 'inline': true, 'error': (usernameNotAllowed !== undefined) ? usernameNotAllowed : false }); let usernameIconClasses = classNames({ 'icon': true, 'inverted circular red remove': (usernameNotAllowed !== undefined) ? usernameNotAllowed : false, 'inverted circular green checkmark': (usernameNotAllowed !== undefined) ? !usernameNotAllowed : false }); let usernameToolTipp = usernameNotAllowed ? 'This Username has already been used by someone else. Please choose another one.' : undefined; if (this.props.UserRegistrationStore.suggestedUsernames.length > 0) { usernameToolTipp += '\n Here are some suggestions: ' + this.props.UserRegistrationStore.suggestedUsernames; } return ( <div> <div className="ui ssoregistration modal" id='signinModal' style={modalStyle} ref="ReviseUser_Modal" > <div className="header"> <h1 style={headerStyle}>Validate user information</h1> <h2 style={headerStyle}>Your account could not migrated automatically. In order to finialize the migration, please change the data which is already in use.</h2> <h3 style={headerStyle}>Hint: if your email or username is already in use, it could be possible that you have already an stand-alone account on this SlideWiki instance. In this case close the window and do a sign in.</h3> </div> <div className="content"> <form className="ui ssoregistrationmodalform form" ref="ReviseUser_form" > <div className={usernameClasses} data-tooltip={usernameToolTipp} data-position="top center" data-inverted="" onBlur={this.checkUsername.bind(this)}> <label style={signUpLabelStyle}>Username * </label> <div className="ui icon input"><i className={usernameIconClasses}/><input type="text" name="username" ref="username" placeholder="Username" aria-required="true" /></div> </div> <div className={emailClasses} data-tooltip={emailToolTipp} data-position="top center" data-inverted="" onBlur={this.checkEmail.bind(this)}> <label style={signUpLabelStyle}>Email * </label> <div className="ui icon input"><i className={emailIconClasses}/><input type="email" name="email" ref="email" placeholder="Email" aria-required="true" /></div> </div> <div className="ui error message" role="region" aria-live="polite"/> <button type="submit" className="ui blue labeled submit icon button" > <i className="icon add user"/> Migrate User </button> </form> </div> <div className="actions"> <div className="ui cancel button">Cancel</div> </div> </div> </div> ); } } ReviseUser.contextTypes = { executeAction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired }; ReviseUser = connectToStores(ReviseUser, [UserRegistrationStore, SSOStore], (context, props) => { return { UserRegistrationStore: context.getStore(UserRegistrationStore).getState(), SSOStore: context.getStore(SSOStore).getState() }; }); export default ReviseUser;
    Realization/frontend/czechidm-core/src/components/advanced/ProfileInfo/ProfileInfo.js
    bcvsolutions/CzechIdMng
    import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; // import * as Basic from '../../basic'; import { ProfileManager } from '../../../redux'; import AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo'; import EntityInfo from '../EntityInfo/EntityInfo'; import TwoFactorAuthenticationTypeEnum from '../../../enums/TwoFactorAuthenticationTypeEnum'; // const manager = new ProfileManager(); /** * Component for rendering information about identity profile. * * @author Radek Tomiška * @since 12.0.0 */ export class ProfileInfo extends AbstractEntityInfo { getManager() { return manager; } showLink() { return false; } /** * Returns entity icon (null by default - icon will not be rendered) * * @param {object} entity */ getEntityIcon() { return 'fa:cog'; } getNiceLabel(entity) { const _entity = entity || this.getEntity(); let label = this.i18n('entity.Profile._type'); if (_entity && _entity._embedded && _entity._embedded.identity) { label = `${ label } - (${ _entity._embedded.identity.username })`; } return label; } /** * Returns popovers title * * @param {object} entity */ getPopoverTitle() { return this.i18n('entity.Profile._type'); } getTableChildren() { // component are used in #getPopoverContent => skip default column resolving return [ <Basic.Column property="label"/>, <Basic.Column property="value"/> ]; } /** * Returns popover info content * * @param {array} table data */ getPopoverContent(entity) { return [ { label: this.i18n('entity.Identity._type'), value: ( <EntityInfo entityType="identity" entity={ entity._embedded ? entity._embedded.identity : null } entityIdentifier={ entity.identity } face="popover" /> ) }, { label: this.i18n('entity.Profile.preferredLanguage.label'), value: entity.preferredLanguage }, { label: this.i18n('entity.Profile.systemInformation.label'), value: (entity.systemInformation ? this.i18n('label.yes') : this.i18n('label.no')) }, { label: this.i18n('entity.Profile.twoFactorAuthenticationType.label'), value: ( <Basic.EnumValue enum={ TwoFactorAuthenticationTypeEnum } value={ entity.twoFactorAuthenticationType }/> ) } ]; } } ProfileInfo.propTypes = { ...AbstractEntityInfo.propTypes, /** * Selected entity - has higher priority */ entity: PropTypes.object, /** * Selected entity's id - entity will be loaded automatically */ entityIdentifier: PropTypes.string, /** * Internal entity loaded by given identifier */ _entity: PropTypes.object, _showLoading: PropTypes.bool }; ProfileInfo.defaultProps = { ...AbstractEntityInfo.defaultProps, entity: null, face: 'link', _showLoading: true }; function select(state, component) { return { _entity: manager.getEntity(state, component.entityIdentifier), _showLoading: manager.isShowLoading(state, null, component.entityIdentifier) }; } export default connect(select)(ProfileInfo);
    app/components/App/App.js
    Tonnu/workflows-ecs-ecr-demo
    import React from 'react'; import createStore from 'lib/createStore'; import { Provider } from 'react-redux'; import HelloApp from 'components/HelloApp/HelloApp'; const store = createStore(); class App extends React.Component { render() { return ( <Provider {...{ store }}> <HelloApp/> </Provider> ); } } export default App;
    src/containers/DevTools/DevTools.js
    svsool/react-redux-universal-hot-example
    import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-H" changePositionKey="ctrl-Q"> <LogMonitor /> </DockMonitor> );
    app/javascript/mastodon/features/community_timeline/index.js
    ebihara99999/mastodon
    import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../ui/components/column'; import { refreshTimeline, updateTimeline, deleteFromTimelines, connectTimeline, disconnectTimeline, } from '../../actions/timelines'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import createStream from '../../stream'; const messages = defineMessages({ title: { id: 'column.community', defaultMessage: 'Local timeline' }, }); const mapStateToProps = state => ({ hasUnread: state.getIn(['timelines', 'community', 'unread']) > 0, streamingAPIBaseURL: state.getIn(['meta', 'streaming_api_base_url']), accessToken: state.getIn(['meta', 'access_token']), }); let subscription; class CommunityTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, streamingAPIBaseURL: PropTypes.string.isRequired, accessToken: PropTypes.string.isRequired, hasUnread: PropTypes.bool, }; componentDidMount () { const { dispatch, streamingAPIBaseURL, accessToken } = this.props; dispatch(refreshTimeline('community')); if (typeof subscription !== 'undefined') { return; } subscription = createStream(streamingAPIBaseURL, accessToken, 'public:local', { connected () { dispatch(connectTimeline('community')); }, reconnected () { dispatch(connectTimeline('community')); }, disconnected () { dispatch(disconnectTimeline('community')); }, received (data) { switch(data.event) { case 'update': dispatch(updateTimeline('community', JSON.parse(data.payload))); break; case 'delete': dispatch(deleteFromTimelines(data.payload)); break; } }, }); } componentWillUnmount () { // if (typeof subscription !== 'undefined') { // subscription.close(); // subscription = null; // } } render () { const { intl, hasUnread } = this.props; return ( <Column icon='users' active={hasUnread} heading={intl.formatMessage(messages.title)}> <ColumnBackButtonSlim /> <StatusListContainer {...this.props} scrollKey='community_timeline' type='community' emptyMessage={<FormattedMessage id='empty_column.community' defaultMessage='The local timeline is empty. Write something publicly to get the ball rolling!' />} /> </Column> ); } } export default connect(mapStateToProps)(injectIntl(CommunityTimeline));
    features/filmStrip/components/web/DominantSpeakerIndicator.js
    jitsi/jitsi-meet-react
    import React, { Component } from 'react'; import Icon from 'react-fontawesome'; import { styles } from './styles'; /** * Thumbnail badge showing that the participant is the dominant speaker in * the conference. */ export class DominantSpeakerIndicator extends Component { /** * Implements React's {@link Component#render()}. * * @inheritdoc */ render() { return ( <div style = { styles.dominantSpeakerIndicatorBackground }> <Icon name = 'bullhorn' style = { styles.dominantSpeakerIndicator } /> </div> ); } }
    src/svg-icons/av/video-label.js
    mtsandeep/material-ui
    import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideoLabel = (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-2zm0 13H3V5h18v11z"/> </SvgIcon> ); AvVideoLabel = pure(AvVideoLabel); AvVideoLabel.displayName = 'AvVideoLabel'; AvVideoLabel.muiName = 'SvgIcon'; export default AvVideoLabel;
    examples/todomvc/containers/Root.js
    dherault/redux
    import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createStore, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from '../reducers'; const store = createStore(rootReducer); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <TodoApp /> } </Provider> ); } }
    packages/react-scripts/fixtures/kitchensink/src/features/syntax/AsyncAwait.js
    timlogemann/create-react-app
    /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; async function load() { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; } /* eslint-disable */ // Regression test for https://github.com/facebook/create-react-app/issues/3055 const x = async ( /* prettier-ignore */ y: void ) => { const z = await y; }; /* eslint-enable */ export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = await load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-async-await"> {this.state.users.map(user => ( <div key={user.id}>{user.name}</div> ))} </div> ); } }
    src/Components/SearchHeader.stories.js
    elderfo/elderfo-react-native-components
    import React from 'react'; import { Text, View } from 'react-native'; import { storiesOf, action, linkTo, } from '@kadira/react-native-storybook'; import { Container, SearchHeader } from '../'; storiesOf('SearchHeader', module) .addDecorator(story => ( <Container> {story()} </Container> )) .add('with left button', () => ( <SearchHeader onLeftButtonClick={action('onLeftButtonClick')} leftButtonIcon='md-arrow-back' onSearch={action('onSearch')} /> )) .add('with right button', () => ( <SearchHeader onRightButtonClick={action('onRightButtonClick')} rightButtonIcon='md-qr-scanner' onSearch={action('onSearch')} /> )) .add('with both buttons', () => ( <SearchHeader onLeftButtonClick={action('onLeftButtonClick')} leftButtonIcon='md-arrow-back' onRightButtonClick={action('onRightButtonClick')} rightButtonIcon='md-qr-scanner' onSearch={action('onSearch')} /> )) .add('with custom placeholder', () => ( <SearchHeader placeholder='Custom Placeholder' onLeftButtonClick={action('onLeftButtonClick')} leftButtonIcon='md-arrow-back' onRightButtonClick={action('onRightButtonClick')} rightButtonIcon='md-qr-scanner' onSearch={action('onSearch')} /> )) .add('with a backgroundColor/foregroundColor', () => ( <SearchHeader onLeftButtonClick={action('onLeftButtonClick')} leftButtonIcon='md-menu' onRightButtonClick={action('onRightButtonClick')} rightButtonIcon='md-qr-scanner' backgroundColor='red' foregroundColor='silver' /> ))
    examples/src/app.js
    yonaichin/react-select
    /* eslint react/prop-types: 0 */ import React from 'react'; import ReactDOM from 'react-dom'; import Select from 'react-select'; import Contributors from './components/Contributors'; import GithubUsers from './components/GithubUsers'; import CustomComponents from './components/CustomComponents'; import CustomRender from './components/CustomRender'; import Multiselect from './components/Multiselect'; import NumericSelect from './components/NumericSelect'; import Virtualized from './components/Virtualized'; import States from './components/States'; ReactDOM.render( <div> <States label="States" searchable /> <Multiselect label="Multiselect" /> <Virtualized label="Virtualized" /> <Contributors label="Contributors (Async)" /> <GithubUsers label="Github users (Async with fetch.js)" /> <NumericSelect label="Numeric Values" /> <CustomRender label="Custom Render Methods"/> <CustomComponents label="Custom Placeholder, Option and Value Components" /> {/* <SelectedValuesField label="Option Creation (tags mode)" options={FLAVOURS} allowCreate hint="Enter a value that's NOT in the list, then hit return" /> */} </div>, document.getElementById('example') );
    src/app/components/team/TeamData/TeamDataComponent.js
    meedan/check-web
    import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Box from '@material-ui/core/Box'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import SettingsHeader from '../SettingsHeader'; import { ContentColumn } from '../../../styles/js/shared'; const TeamDataComponent = ({ dataReportUrl }) => ( <ContentColumn large> <SettingsHeader title={ <FormattedMessage id="teamDataComponent.title" defaultMessage="Workspace data" description="Header for the stored data page of the current team" /> } subtitle={ <FormattedMessage id="teamDataComponent.subtitle" defaultMessage="Download data and metadata from Check. Get insight and analysis about workspace and tipline usage." /> } helpUrl="https://help.checkmedia.org/en/articles/4511362" /> <Card> <CardContent> { dataReportUrl ? <React.Fragment> <Typography variant="body1" component="p" paragraph> <FormattedMessage id="teamDataComponent.notSet1" defaultMessage="Click the button below to open your data report in a new window." /> </Typography> <Box mt={2} mb={2}> <Button variant="contained" color="primary" onClick={() => { window.open(dataReportUrl); }} > <FormattedMessage id="teamDataComponent.viewDataReport" defaultMessage="View data report" /> </Button> </Box> <Typography variant="body1" component="p" paragraph> <FormattedMessage id="teamDataComponent.notSet2" defaultMessage="To request any customization of your data report, please reach out to support." /> </Typography> </React.Fragment> : <React.Fragment> <Typography variant="body1" component="p" paragraph> <FormattedMessage id="teamDataComponent.set1" defaultMessage="Fill {thisShortForm} to request access to your data report." values={{ thisShortForm: ( <a href="https://airtable.com/shrWpaztZ2SzD5TrA" target="_blank" rel="noopener noreferrer"> <FormattedMessage id="teamDataComponent.formLinkText" defaultMessage="this short form" /> </a> ), }} /> </Typography> <Typography variant="body1" component="p" paragraph> <FormattedMessage id="teamDataComponent.set2" defaultMessage="Your data report will be enabled within one business day." /> </Typography> </React.Fragment> } </CardContent> </Card> </ContentColumn> ); TeamDataComponent.defaultProps = { dataReportUrl: null, }; TeamDataComponent.propTypes = { dataReportUrl: PropTypes.string, // or null }; export default TeamDataComponent;
    docs/src/NavMain.js
    adampickeral/react-bootstrap
    import React from 'react'; import { Link } from 'react-router'; import Navbar from '../../src/Navbar'; import Nav from '../../src/Nav'; const NAV_LINKS = { 'introduction': { link: 'introduction', title: 'Introduction' }, 'getting-started': { link: 'getting-started', title: 'Getting started' }, 'components': { link: 'components', title: 'Components' }, 'support': { link: 'support', title: 'Support' } }; const NavMain = React.createClass({ propTypes: { activePage: React.PropTypes.string }, render() { let brand = <Link to='home' className="navbar-brand">React-Bootstrap</Link>; let links = Object.keys(NAV_LINKS).map(this.renderNavItem).concat([ <li key='github-link'> <a href='https://github.com/react-bootstrap/react-bootstrap' target='_blank'>GitHub</a> </li> ]); return ( <Navbar componentClass='header' brand={brand} staticTop className="bs-docs-nav" role="banner" toggleNavKey={0}> <Nav className="bs-navbar-collapse" role="navigation" eventKey={0} id="top"> {links} </Nav> </Navbar> ); }, renderNavItem(linkName) { let link = NAV_LINKS[linkName]; return ( <li className={this.props.activePage === linkName ? 'active' : null} key={linkName}> <Link to={link.link}>{link.title}</Link> </li> ); } }); export default NavMain;
    src/admin/BedChart.js
    ocelotconsulting/global-hack-6
    /* eslint no-new: "off" */ import React from 'react' import { v4 } from 'uuid' import ChartKey from './ChartKey' import Row from 'react-bootstrap/lib/Row' import Col from 'react-bootstrap/lib/Col' import ChartistGraph from 'react-chartist' export default class BedChart extends React.Component { constructor(props) { super(props) this.state = { id: `chart_${v4().replace(/-/g, '')}` } } render() { const { total, available, pending } = this.props const data = { series: [total - available - pending, pending, available] } const options = { startAngle: 270, showLabel: false } return ( <div className='summary-chart'> <Row> <Col md={3}> <ChartKey/> </Col> <Col md={3}> <ChartistGraph data={data} options={options} type='Pie'/> </Col> </Row> </div> ) } }
    src/components/auth/accountpage.js
    Hommasoft/wappuapp-adminpanel
    import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import * as Auth from '../../actions/auth'; class AccountPage extends Component { handleFormSubmit({ newpassword, oldpassword }) { this.props.changepassword({ newpassword, oldpassword }); } renderError() { if (this.props.errorMessage) { console.log(this.props.errorMessage); return <div className="alert alert-danger">{this.props.errorMessage}</div>; } } renderField({ input, label, type, meta: { error } }) { return ( <div> <label>{label}</label> <div> <input className="form-control" {...input} placeholder={label} type={type} /> {error && <span className="text-danger">{error}</span>} </div> </div> ); } render() { const { handleSubmit } = this.props; var accountType = localStorage.getItem('admin'); if (accountType === 'true') { accountType = 'admin'; } else { accountType = 'moderator'; } return ( <div> <div> <h3>User details</h3> Email: {localStorage.getItem('email')} <br /> Account type: {accountType} <br /> Activated: {localStorage.getItem('activated')} <br /> </div> <br /> <div align="center"> Change password <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> <fieldset className="form-group"> <Field name="oldpassword" label="Old password" component={this.renderField} type="password" /> </fieldset> <br /> <fieldset className="form-group"> <Field name="newpassword" label="New password" component={this.renderField} type="password" /> </fieldset> <fieldset className="form-group"> <Field name="newpasswordagain" label="New password again" component={this.renderField} type="password" /> </fieldset> {this.renderError()} <button action="submit" className="btn btn-primary"> Change password </button> </form> </div> </div> ); } } const validate = values => { const errors = {}; //if (values.newpassword && values.newpassword.length < 8) { // errors.newpassword = 'Password has to be atleast 8 characters long' //} if (values.newpassword && values.oldpassword === values.newpassword) { errors.newpassword = 'New password can not be the same as old one'; } if (values.newpasswordagain && values.newpassword !== values.newpasswordagain) { errors.newpasswordagain = 'New passwords need to match'; } return errors; }; const mapStateToProps = state => { return { errorMessage: state.auth.error }; }; export default reduxForm({ form: 'auth', validate })(connect(mapStateToProps, Auth)(AccountPage));
    src/plugins/position/components/SpacerRow.js
    joellanciaux/Griddle
    import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from '../../../utils/griddleConnect'; import compose from 'recompose/compose'; import mapProps from 'recompose/mapProps'; import getContext from 'recompose/getContext'; import withHandlers from 'recompose/withHandlers'; const spacerRow = compose( getContext({ selectors: PropTypes.object, }), connect((state, props) => { const { topSpacerSelector, bottomSpacerSelector } = props.selectors; const { placement } = props; return { spacerHeight: placement === 'top' ? topSpacerSelector(state, props) : bottomSpacerSelector(state, props), }; }), mapProps(props => ({ placement: props.placement, spacerHeight: props.spacerHeight, })) )(class extends Component { static propTypes = { placement: PropTypes.string, spacerHeight: PropTypes.number, } static defaultProps = { placement: 'top' } // shouldComponentUpdate(nextProps) { // const { currentPosition: oldPosition, placement: oldPlacement } = this.props; // const { currentPosition, placement } = nextProps; // // return oldPosition !== currentPosition || oldPlacement !== placement; // } render() { const { placement, spacerHeight } = this.props; let spacerRowStyle = { height: `${spacerHeight}px`, }; return ( <tr key={placement + '-' + spacerHeight} style={spacerRowStyle}></tr> ); } }); export default spacerRow;
    node_modules/react-bootstrap/es/ModalBody.js
    firdiansyah/crud-req
    import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var ModalBody = function (_React$Component) { _inherits(ModalBody, _React$Component); function ModalBody() { _classCallCheck(this, ModalBody); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalBody.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return ModalBody; }(React.Component); ModalBody.propTypes = propTypes; ModalBody.defaultProps = defaultProps; export default bsClass('modal-body', ModalBody);
    imports/ui/components/Routes/Authenticated.js
    haraneesh/mydev
    import React from 'react'; import PropTypes from 'prop-types'; import { Route, Redirect } from 'react-router-dom'; /* const Authenticated = ({ layout: Layout, roles, authenticated, component, ...rest }) => ( <Route {...rest} render={props => ( authenticated ? (<Layout {...props} isAdmin={roles.indexOf('admin') !== -1} authenticated {...rest} > {(React.createElement(component, { ...props, authenticated, ...rest }))} </Layout>) : (<Redirect to="/about" />) )} /> ); */ const Authenticated = ({ layout: Layout, roles, authenticated, component: Component, ...rest }) => ( <Route {...rest} render={(props) => ( authenticated ? ( <Layout {...props} isAdmin={roles.indexOf('admin') !== -1} authenticated {...rest} > <Component {...props} authenticated {...rest} roles={roles} /> </Layout> ) : (<Redirect to="/about" />) )} /> ); Authenticated.propTypes = { routeName: PropTypes.string.isRequired, roles: PropTypes.array.isRequired, authenticated: PropTypes.bool.isRequired, component: PropTypes.func.isRequired, layout: PropTypes.node.isRequired, }; export default Authenticated;
    packages/mcs-lite-ui/src/DataChannelAdapter/DataChannelAdapter.example.js
    MCS-Lite/mcs-lite
    import React from 'react'; import styled from 'styled-components'; import { storiesOf } from '@storybook/react'; import { withInfo } from '@storybook/addon-info'; import { action } from '@storybook/addon-actions'; import DataChannelCard from '../DataChannelCard'; import DATA_CHANNELS from './API'; import DataChannelAdapter from '.'; const CardWrapper = styled.div` display: flex; flex-wrap: wrap; > * { height: initial; padding: 8px 16px; margin: 4px; flex-basis: 100%; } > [data-width~=' half'] { flex-grow: 1; flex-basis: 40%; } `; storiesOf('DataChannelAdapter', module).add( 'API', withInfo({ text: ` ~~~js type Event = { type: 'SUBMIT'|'CHANGE'|'CLEAR', // event type id: string, // data channel id values: { // datapoint values value: ?string|number, period: ?number, }, } type DCEventHandler = DCEvent => void ~~~ `, inline: true, })(() => ( <CardWrapper> {DATA_CHANNELS.map(dataChannel => ( <DataChannelCard key={dataChannel.id} data-width="half" title={dataChannel.type} subtitle="Last data point time : 2015-06-12 12:00" description="You can input description of controller here. You can input description of You can input description of controller here. You can input description of" header={<a href=".">Link</a>} > <DataChannelAdapter dataChannelProps={dataChannel} eventHandler={action( 'DataChannelAdapter eventHandler(event: Event)', )} /> </DataChannelCard> ))} </CardWrapper> )), );
    src/docs/components/header/HeaderExamplesDoc.js
    grommet/grommet-docs
    // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Header from 'grommet/components/Header'; import Title from 'grommet/components/Title'; import Search from 'grommet/components/Search'; import Menu from 'grommet/components/Menu'; import Box from 'grommet/components/Box'; import Anchor from 'grommet/components/Anchor'; import ActionsIcon from 'grommet/components/icons/base/Actions'; import InteractiveExample from '../../../components/InteractiveExample'; const PROPS_SCHEMA = { fixed: { value: true }, float: { value: true }, size: { options: ['small', 'medium', 'large', 'xlarge'] }, splash: { value: true } }; const CONTENTS_SCHEMA = { title: { value: <Title>Sample Title</Title>, initial: true }, search: { value: ( <Search inline={true} fill={true} size='medium' placeHolder='Search' dropAlign={{ right: 'right' }}/> ), initial: true }, menu: { value: ( <Menu icon={<ActionsIcon />} dropAlign={{right: 'right'}}> <Anchor href='#' className='active'>First</Anchor> <Anchor href='#'>Second</Anchor> <Anchor href='#'>Third</Anchor> </Menu> ), initial: true } }; export default class HeaderExamplesDoc extends Component { constructor () { super(); this.state = { contents: {}, elementProps: {} }; } render () { let { contents, elementProps } = this.state; const element = ( <Header {...elementProps}> {contents.title} <Box flex={true} justify='end' direction='row' responsive={false}> {contents.search} {contents.menu} </Box> </Header> ); return ( <InteractiveExample contextLabel='Header' contextPath='/docs/header' justify='start' align='stretch' preamble={`import Header from 'grommet/components/Header';`} propsSchema={PROPS_SCHEMA} contentsSchema={CONTENTS_SCHEMA} element={element} onChange={(elementProps, contents) => { this.setState({ elementProps, contents }); }} /> ); } };
    packages/benchmarks/src/index.js
    css-components/styled-components
    /* eslint-disable no-param-reassign */ /* global document */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './app/App'; import impl from './impl'; import Tree from './cases/Tree'; import SierpinskiTriangle from './cases/SierpinskiTriangle'; const implementations = impl; const packageNames = Object.keys(implementations); const createTestBlock = fn => { return packageNames.reduce((testSetups, packageName) => { const { name, components, version } = implementations[packageName]; const { Component, getComponentProps, sampleCount, Provider, benchmarkType } = fn(components); testSetups[packageName] = { Component, getComponentProps, sampleCount, Provider, benchmarkType, version, name, }; return testSetups; }, {}); }; const tests = { 'Mount deep tree': createTestBlock(components => ({ benchmarkType: 'mount', Component: Tree, getComponentProps: () => ({ breadth: 2, components, depth: 7, id: 0, wrap: 1 }), Provider: components.Provider, sampleCount: 500, })), 'Mount wide tree': createTestBlock(components => ({ benchmarkType: 'mount', Component: Tree, getComponentProps: () => ({ breadth: 6, components, depth: 3, id: 0, wrap: 2 }), Provider: components.Provider, sampleCount: 500, })), 'Update dynamic styles': createTestBlock(components => ({ benchmarkType: 'update', Component: SierpinskiTriangle, getComponentProps: ({ cycle }) => { return { components, s: 200, renderCount: cycle, x: 0, y: 0 }; }, Provider: components.Provider, sampleCount: 1000, })), }; ReactDOM.render(<App tests={tests} />, document.querySelector('.root'));
    app/routes/routes/PaySuccess/components/PaySuccess.view.js
    bugknightyyp/leyizhu
    import React from 'react' import {observer} from 'mobx-react' import {Route, Link} from 'react-router-dom' import {IMAGE_DIR, TOKEN, GET_HOTEL_INFO, RESPONSE_CODE_SUCCESS} from 'macros' import {setParamsToURL, dateToZh} from 'utils' import './paySuccess.less' export default observer( (props) => ( <div className="pay-success-container"> <div className="hotel-info"> <i className="iconfont icon-success" /> <h1>支付成功</h1> <div className="hotel-name">{props.store.hotelName}</div> <div className="hotel-address">{`酒店地址:${props.store.address}`}</div> <Link to={{pathname: `${props.match.url}/map`, search: `?longitude=${props.store.longitude}&latitude=${props.store.latitude}`}} className="go-hotel">前往酒店</Link> </div> <div className="how-to-checking"> <h6>如何入住</h6> <p> 1.前往酒店,并找到自助入住登记机<br /> 2.在自助机登记证件,并进行脸部识别<br /> 3.收取入住短信通知(含房间号和密码)<br /> *房门还可通过网络开锁功能开启</p> </div> <div className="safety-tips"> <i className="iconfont icon-tixing" />根据公安部法律规定,住宿需登记身份证信息 </div> </div> ) )
    frontend/src/Factura/FacturaTable.js
    GAumala/Facturacion
    import React from 'react'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn } from 'material-ui/Table'; import TextField from 'material-ui/TextField'; import IconButton from 'material-ui/IconButton'; import Delete from 'material-ui/svg-icons/action/delete'; import Math from 'facturacion_common/src/Math.js'; const black54p = '#757575'; const noPaddingStyle = { padding: '0px' }; const RenderTableHeader = props => { let regSanCol = ( <TableHeaderColumn width={80} style={noPaddingStyle}> Reg. Santario </TableHeaderColumn> ); let loteCol = ( <TableHeaderColumn width={60} style={noPaddingStyle}> Lote </TableHeaderColumn> ); let fechaExpCol = ( <TableHeaderColumn width={70} style={noPaddingStyle}> Fecha Exp. </TableHeaderColumn> ); if (props.isExamen) { //ocultar columnas que no se usan en examenes regSanCol = null; loteCol = null; fechaExpCol = null; } return ( <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> <TableHeaderColumn width={40} style={noPaddingStyle}> # </TableHeaderColumn> {regSanCol} <TableHeaderColumn width={170} style={noPaddingStyle}> Nombre </TableHeaderColumn> {loteCol} <TableHeaderColumn width={40} style={noPaddingStyle}> Cant. </TableHeaderColumn> {fechaExpCol} <TableHeaderColumn width={60} style={noPaddingStyle}> Precio </TableHeaderColumn> <TableHeaderColumn width={50} style={noPaddingStyle}> Importe </TableHeaderColumn> <TableHeaderColumn width={30} style={noPaddingStyle} /> </TableRow> </TableHeader> ); }; export default class FacturaTable extends React.Component { renderRow = (facturable, i) => { const { isExamen, onFacturableChanged, onFacturableDeleted } = this.props; let regSanCol = ( <TableRowColumn width={80} style={noPaddingStyle}> {facturable.codigo} </TableRowColumn> ); let loteCol = ( <TableRowColumn width={60} style={noPaddingStyle}> <TextField value={facturable.lote} style={{ width: '50px' }} name={'lote'} inputStyle={{ textAlign: 'right', fontSize: '13px' }} onChange={event => { onFacturableChanged(i, 'lote', event.target.value); }} /> </TableRowColumn> ); let fechaExpCol = ( <TableRowColumn width={70} style={noPaddingStyle}> <TextField value={facturable.fechaExp} hintText={'expiración'} style={{ width: '70px', fontSize: '13px' }} onChange={(event, date) => { onFacturableChanged(i, 'fechaExp', date); }} /> </TableRowColumn> ); if (isExamen) { //ocultar columnas que no se usan en examenes regSanCol = null; loteCol = null; fechaExpCol = null; } return ( <TableRow key={i}> <TableRowColumn width={40} style={noPaddingStyle}> {i + 1} </TableRowColumn> {regSanCol} <TableRowColumn width={170} style={noPaddingStyle}> {facturable.nombre} </TableRowColumn> {loteCol} <TableRowColumn width={40} style={noPaddingStyle}> <TextField style={{ width: '28px' }} value={facturable.countText} name={'count'} inputStyle={{ textAlign: 'right', fontSize: '13px' }} onChange={event => { onFacturableChanged(i, 'count', event.target.value); }} /> </TableRowColumn> {fechaExpCol} <TableRowColumn width={60} style={noPaddingStyle}> ${' '} <TextField style={{ width: '50px' }} name={'precio'} value={facturable.precioVentaText} onChange={event => { onFacturableChanged(i, 'precioVenta', event.target.value); }} inputStyle={{ fontSize: '13px' }} /> </TableRowColumn> <TableRowColumn width={50} style={{ padding: '0px', textOverflow: 'clip' }} > <span style={{ marginRight: '34px' }}> $ {Math.calcularImporteFacturable(facturable)} </span> </TableRowColumn> <TableRowColumn width={30} style={{ padding: '0px', textAlign: 'right' }} > <IconButton onTouchTap={() => onFacturableDeleted(i)}> <Delete color={black54p} /> </IconButton> </TableRowColumn> </TableRow> ); }; render() { return ( <Table height={'200px'} selectable={false}> {RenderTableHeader(this.props)} <TableBody displayRowCheckbox={false}> {this.props.items.map(this.renderRow)} </TableBody> </Table> ); } } FacturaTable.propTypes = { isExamen: React.PropTypes.bool, items: React.PropTypes.array.isRequired, onFacturableChanged: React.PropTypes.func.isRequired, onFacturableDeleted: React.PropTypes.func.isRequired }; FacturaTable.defaultProps = { isExamen: false };
    lib/routes.js
    codevlabs/filepizza
    import React from 'react' import { Route, DefaultRoute, NotFoundRoute, RouteHandler } from 'react-router' import App from './components/App' import DownloadPage from './components/DownloadPage' import UploadPage from './components/UploadPage' import ErrorPage from './components/ErrorPage' export default ( <Route handler={App}> <DefaultRoute handler={UploadPage} /> <Route name="download" path="/:a-:b-:c-:d" handler={DownloadPage} /> <Route name="error" path="error" handler={ErrorPage} /> <NotFoundRoute handler={ErrorPage} /> </Route> )
    2016-04-declarative-charts/assets/highcharts.js
    rosko/slides
    import React from 'react'; import IframeExample from '../components/IframeExample'; function Highcharts() { return <IframeExample html={`<html><head> <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> </head><body> <div id="container" style="width: 100vw; height: 100vh; margin: 0 auto"></div> <script> ${require('raw!./highcharts.example')} </script> </body></html>`}/>; } Highcharts.displayName = 'Highcharts'; module.exports = Highcharts;
    node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
    Rmutek/rmutek.github.io
    import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
    packages/ui/src/components/Sprinkle.stories.js
    dino-dna/donut
    import React from 'react' import { storiesOf } from '@storybook/react' import Sprinkle from './Sprinkle' export default storiesOf('Sprinkle', module) .add('basic', () => { return ( <svg viewport='0 0 60 60' width='60' height='60'> <Sprinkle /> </svg> ) }) .add('rotated', () => { return ( <svg viewport='0 0 60 60'> <Sprinkle deg={90} /> </svg> ) }) .add('rotated & translated', () => { return ( <svg viewport='0 0 60 60'> <g style={{ transform: `translate(${25}px, ${25}px)` }}> <Sprinkle deg={45} /> </g> </svg> ) })
    actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js
    JeeLiu/actor-platform
    import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import LoginStore from 'stores/LoginStore'; import AvatarItem from 'components/common/AvatarItem.react'; const GroupProfileMembers = React.createClass({ propTypes: { groupId: React.PropTypes.number, members: React.PropTypes.array.isRequired }, mixins: [PureRenderMixin], onClick(id) { DialogActionCreators.selectDialogPeerUser(id); }, onKickMemberClick(groupId, userId) { DialogActionCreators.kickMember(groupId, userId); }, render() { let groupId = this.props.groupId; let members = this.props.members; let myId = LoginStore.getMyId(); let membersList = _.map(members, (member, index) => { let controls; let canKick = member.canKick; if (canKick === true && member.peerInfo.peer.id !== myId) { controls = ( <div className="controls pull-right"> <a onClick={this.onKickMemberClick.bind(this, groupId, member.peerInfo.peer.id)}>Kick</a> </div> ); } return ( <li className="profile__list__item row" key={index}> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <AvatarItem image={member.peerInfo.avatar} placeholder={member.peerInfo.placeholder} size="small" title={member.peerInfo.title}/> </a> <div className="col-xs"> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <span className="title"> {member.peerInfo.title} </span> </a> {controls} </div> </li> ); }, this); return ( <ul className="profile__list profile__list--members"> <li className="profile__list__item profile__list__item--header">{members.length} members</li> {membersList} </ul> ); } }); export default GroupProfileMembers;
    src/DataTables/DataTablesTableBody.js
    hyojin/material-ui-datatables
    import React from 'react'; import PropTypes from 'prop-types'; import {TableBody} from 'material-ui/Table'; import ClickAwayListener from 'material-ui/internal/ClickAwayListener'; class DataTablesTableBody extends TableBody { static muiName = 'TableBody'; static propTypes = { /** * @ignore * Set to true to indicate that all rows should be selected. */ allRowsSelected: PropTypes.bool, /** * Children passed to table body. */ children: PropTypes.node, /** * The css class name of the root element. */ className: PropTypes.string, /** * Controls whether or not to deselect all selected * rows after clicking outside the table. */ deselectOnClickaway: PropTypes.bool, /** * Controls the display of the row checkbox. The default value is true. */ displayRowCheckbox: PropTypes.bool, /** * @ignore * If true, multiple table rows can be selected. * CTRL/CMD+Click and SHIFT+Click are valid actions. * The default value is false. */ multiSelectable: PropTypes.bool, /** * @ignore * Callback function for when a cell is clicked. */ onCellClick: PropTypes.func, /** * @ignore * Customized handler * Callback function for when a cell is double clicked. */ onCellDoubleClick: PropTypes.func, /** * @ignore * Called when a table cell is hovered. rowNumber * is the row number of the hovered row and columnId * is the column number or the column key of the cell. */ onCellHover: PropTypes.func, /** * @ignore * Called when a table cell is no longer hovered. * rowNumber is the row number of the row and columnId * is the column number or the column key of the cell. */ onCellHoverExit: PropTypes.func, /** * @ignore * Called when a table row is hovered. * rowNumber is the row number of the hovered row. */ onRowHover: PropTypes.func, /** * @ignore * Called when a table row is no longer * hovered. rowNumber is the row number of the row * that is no longer hovered. */ onRowHoverExit: PropTypes.func, /** * @ignore * Called when a row is selected. selectedRows is an * array of all row selections. IF all rows have been selected, * the string "all" will be returned instead to indicate that * all rows have been selected. */ onRowSelection: PropTypes.func, /** * Controls whether or not the rows are pre-scanned to determine * initial state. If your table has a large number of rows and * you are experiencing a delay in rendering, turn off this property. */ preScanRows: PropTypes.bool, /** * @ignore * If true, table rows can be selected. If multiple * row selection is desired, enable multiSelectable. * The default value is true. */ selectable: PropTypes.bool, /** * If true, table rows will be highlighted when * the cursor is hovering over the row. The default * value is false. */ showRowHover: PropTypes.bool, /** * If true, every other table row starting * with the first row will be striped. The default value is false. */ stripedRows: PropTypes.bool, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; createRows() { const numChildren = React.Children.count(this.props.children); let rowNumber = 0; const handlers = { onCellClick: this.onCellClick, onCellDoubleClick: this.onCellDoubleClick, onCellHover: this.onCellHover, onCellHoverExit: this.onCellHoverExit, onRowHover: this.onRowHover, onRowHoverExit: this.onRowHoverExit, onRowClick: this.onRowClick, }; return React.Children.map(this.props.children, (child) => { if (React.isValidElement(child)) { const props = { hoverable: this.props.showRowHover, selected: this.isRowSelected(rowNumber), striped: this.props.stripedRows && (rowNumber % 2 === 0), rowNumber: rowNumber++, }; if (rowNumber === numChildren) { props.displayBorder = false; } const children = [ this.createRowCheckboxColumn(props), ]; React.Children.forEach(child.props.children, (child) => { children.push(child); }); return React.cloneElement(child, {...props, ...handlers}, children); } }); } onCellDoubleClick = (event, rowNumber, columnNumber) => { event.stopPropagation(); if (this.props.onCellDoubleClick) { this.props.onCellDoubleClick(rowNumber, this.getColumnId(columnNumber), event); } }; render() { const { style, allRowsSelected, // eslint-disable-line no-unused-vars multiSelectable, // eslint-disable-line no-unused-vars onCellClick, // eslint-disable-line no-unused-vars onCellDoubleClick, // eslint-disable-line no-unused-vars onCellHover, // eslint-disable-line no-unused-vars onCellHoverExit, // eslint-disable-line no-unused-vars onRowHover, // eslint-disable-line no-unused-vars onRowHoverExit, // eslint-disable-line no-unused-vars onRowSelection, // eslint-disable-line no-unused-vars selectable, // eslint-disable-line no-unused-vars deselectOnClickaway, // eslint-disable-line no-unused-vars showRowHover, // eslint-disable-line no-unused-vars stripedRows, // eslint-disable-line no-unused-vars displayRowCheckbox, // eslint-disable-line no-unused-vars preScanRows, // eslint-disable-line no-unused-vars ...other } = this.props; const {prepareStyles} = this.context.muiTheme; return ( <ClickAwayListener onClickAway={this.handleClickAway}> <tbody style={prepareStyles(Object.assign({}, style))} {...other}> {this.createRows()} </tbody> </ClickAwayListener> ); } } export default DataTablesTableBody;
    src/svg-icons/action/settings-backup-restore.js
    mit-cml/iot-website-source
    import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsBackupRestore = (props) => ( <SvgIcon {...props}> <path d="M14 12c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2zm-2-9c-4.97 0-9 4.03-9 9H0l4 4 4-4H5c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.51 0-2.91-.49-4.06-1.3l-1.42 1.44C8.04 20.3 9.94 21 12 21c4.97 0 9-4.03 9-9s-4.03-9-9-9z"/> </SvgIcon> ); ActionSettingsBackupRestore = pure(ActionSettingsBackupRestore); ActionSettingsBackupRestore.displayName = 'ActionSettingsBackupRestore'; ActionSettingsBackupRestore.muiName = 'SvgIcon'; export default ActionSettingsBackupRestore;
    server/middleware/reactApplication/index.js
    dariobanfi/react-avocado-starter
    import React from 'react'; import Helmet from 'react-helmet'; import { renderToString, renderToStaticMarkup } from 'react-dom/server'; import { StaticRouter } from 'react-router-dom'; import { ServerStyleSheet } from 'styled-components'; import config from '../../../config'; import ServerHTML from './ServerHTML'; import Application from '../../../app/components/Application'; export default function reactApplicationMiddleware(request, response) { // Ensure a nonce has been provided to us. // See the server/middleware/security.js for more info. if (typeof response.locals.nonce !== 'string') { throw new Error('A "nonce" value has not been attached to the response'); } const nonce = response.locals.nonce; // It's possible to disable SSR, which can be useful in development mode. // In this case traditional client side only rendering will occur. if (config('disableSSR')) { if (process.env.BUILD_FLAG_IS_DEV === 'true') { // eslint-disable-next-line no-console console.log('==> Handling react route without SSR'); } // SSR is disabled so we will return an "empty" html page and // rely on the client to initialize and render the react application. const html = renderToStaticMarkup(<ServerHTML nonce={nonce} />); response.status(200).send(`<!DOCTYPE html>${html}`); return; } // Create a context for <StaticRouter>, which will allow us to // query for the results of the render. const reactRouterContext = {}; // Declare our React application. const app = ( <StaticRouter location={request.url} context={reactRouterContext}> <Application /> </StaticRouter> ); const appString = renderToString(app); // Generate the html response. const html = renderToStaticMarkup( <ServerHTML reactAppString={appString} nonce={nonce} sheet={new ServerStyleSheet()} helmet={Helmet.rewind()} />, ); // Check if the router context contains a redirect, if so we need to set // the specific status and redirect header and end the response. if (reactRouterContext.url) { response.status(302).setHeader('Location', reactRouterContext.url); response.end(); return; } response .status( reactRouterContext.missed ? 404 : 200, ) .send(`<!DOCTYPE html>${html}`); }
    src/components/Feedback/Feedback.js
    seriflafont/react-starter-kit
    /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback extends Component { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;