path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
tests/lib/rules/vars-on-top.js | Jxck/eslint | /**
* @fileoverview Tests for vars-on-top rule.
* @author Danny Fritz
* @author Gyandeep Singh
* @copyright 2014 Danny Fritz. All rights reserved.
* @copyright 2014 Gyandeep Singh. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/vars-on-top"),
EslintTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new EslintTester();
ruleTester.run("vars-on-top", rule, {
valid: [
[
"var first = 0;",
"function foo() {",
" first = 2;",
"}"
].join("\n"),
[
"function foo() {",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" if (true) {",
" first = true;",
" } else {",
" first = 1;",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" var third;",
" var fourth = 1, fifth, sixth = third;",
" var seventh;",
" if (true) {",
" third = true;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var i;",
" for (i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var outer;",
" function inner() {",
" var inner = 1;",
" var outer = inner;",
" }",
" outer = 1;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" //Hello",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" /*",
" Hello Clarice",
" */",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var first;",
" first = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var third;",
" third = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var bar = function(){",
" var third;",
" third = 5;",
" }",
" first = 5;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" first.onclick(function(){",
" var third;",
" third = 5;",
" });",
" first = 5;",
"}"
].join("\n"),
{
code: [
"function foo() {",
" var i = 0;",
" for (let j = 0; j < 10; j++) {",
" alert(j);",
" }",
" i = i + 1;",
"}"
].join("\n"),
ecmaFeatures: {
blockBindings: true
}
},
"'use strict'; var x; f();",
"'use strict'; 'directive'; var x; var y; f();",
"function f() { 'use strict'; var x; f(); }",
"function f() { 'use strict'; 'directive'; var x; var y; f(); }",
{code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}
],
invalid: [
{
code: [
"var first = 0;",
"function foo() {",
" first = 2;",
" second = 2;",
"}",
"var second = 0;"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" first = 1;",
" first = 2;",
" first = 3;",
" first = 4;",
" var second = 1;",
" second = 2;",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" if (true) {",
" var second = true;",
" }",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" for (var i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" for (i = 0; i < first; i ++) {",
" var second = i;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" switch (first) {",
" case 10:",
" var hello = 1;",
" break;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" var hello = 1;",
" } catch (e) {",
" alert('error');",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" asdf;",
" } catch (e) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" while (first) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" do {",
" var hello = 1;",
" } while (first == 10);",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" for (var item in first) {",
" item++;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"var foo = () => {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
ecmaFeatures: { arrowFunctions: true },
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: "'use strict'; 0; var x; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "'use strict'; var x; 'directive'; var y; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; 0; var x; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
}
]
});
|
app/components/panel/PanelInfo.js | jendela/jendela | import React from 'react'
import Colors from '../../constants/JendelaColors'
const styles = {
icon: {
width: '25%',
height: 'auto',
paddingBottom: '4px',
paddingTop: '4px'
},
info: {
width: '75%',
paddingLeft: 0
},
text: {
color: Colors.blue,
fontWeight: 900,
fontSize: '1.5em',
marginBottom: '-10px'
},
label: {
color: Colors.green,
fontWeight: 900
}
}
class PanelInfo extends React.Component {
render() {
const { icon, label, text } = this.props
return (
<div className="row" style={styles.panel}>
<div className="shrink columns" style={styles.icon}>
<img src={icon}/>
</div>
<div className="columns" style={styles.info}>
<div style={styles.text}>{text}</div>
<div style={styles.label}>{label}</div>
</div>
</div>
)
}
}
PanelInfo.defaultProps = { icon: '', label: '', text: '' }
export default PanelInfo
|
ukelonn.web.frontend/src/main/frontend/components/AdminJobsEdit.js | steinarb/ukelonn | import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';
import DatePicker from 'react-datepicker';
import {
JOB_TABLE_ROW_CLICK,
MODIFY_JOB_DATE,
SAVE_CHANGES_TO_JOB_BUTTON_CLICKED,
} from '../actiontypes';
import Locale from './Locale';
import Accounts from './Accounts';
import Jobtypes from './Jobtypes';
import Logout from './Logout';
export default function AdminJobsEdit() {
const text = useSelector(state => state.displayTexts);
const firstname = useSelector(state => state.accountFirstname);
const transactionAmount = useSelector(state => state.transactionAmount);
const transactionTime = useSelector(state => state.transactionDate);
const jobs = useSelector(state => state.jobs);
const dispatch = useDispatch();
return (
<div>
<nav className="navbar navbar-light bg-light">
<Link className="btn btn-primary" to="/ukelonn/admin/jobtypes">
<span className="oi oi-chevron-left" title="chevron left" aria-hidden="true"></span>
{text.administrateJobsAndJobTypes}
</Link>
<h1>{text.modifyJobsFor} {firstname}</h1>
<Locale />
</nav>
<div className="container">
<div className="form-group row">
<label htmlFor="account-selector" className="col-form-label col-5">{text.chooseAccount}:</label>
<div className="col-7">
<Accounts id="account-selector" className="form-control" />
</div>
</div>
</div>
<div className="table-responsive table-sm table-striped">
<table className="table">
<thead>
<tr>
<th className="transaction-table-col1">{text.date}Dato</th>
<th className="transaction-table-col-hide-overflow transaction-table-col2">{text.jobs}</th>
<th className="transaction-table-col3">{text.amount}</th>
</tr>
</thead>
<tbody>
{jobs.map((job) =>
<tr onClick={ ()=>dispatch(JOB_TABLE_ROW_CLICK({ ...job })) } key={job.id}>
<td>{new Date(job.transactionTime).toISOString().split('T')[0]}</td>
<td>{job.name}</td>
<td>{job.transactionAmount}</td>
</tr>
)}
</tbody>
</table>
</div>
<h2>Endre jobb</h2>
<div className="container">
<div className="form-group row">
<label htmlFor="jobtype" className="col-form-label col-5">{text.jobType}</label>
<div className="col-7">
<Jobtypes id="jobtype" />
</div>
</div>
<div className="form-group row">
<label htmlFor="amount" className="col-form-label col-5">{text.amount}</label>
<div className="col-7">
<input id="amount" type="text" value={transactionAmount} readOnly={true} />
</div>
</div>
<div className="form-group row">
<label htmlFor="date" className="col-form-label col-5">{text.date}</label>
<div className="col-7">
<DatePicker
selected={new Date(transactionTime)}
dateFormat="yyyy-MM-dd"
onChange={d => dispatch(MODIFY_JOB_DATE(d))}
onFocus={e => e.target.blur()} />
</div>
</div>
</div>
<button className="btn btn-primary" onClick={() => dispatch(SAVE_CHANGES_TO_JOB_BUTTON_CLICKED())}>{text.saveChangesToJob}</button>
<br/>
<br/>
<Logout />
<br/>
<a href="../../../..">{text.returnToTop}</a>
</div>
);
}
|
packages/material-ui-icons/src/RemoveFromQueue.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2H8v-2h8z" /></g>
, 'RemoveFromQueue');
|
src/components/common/ComponentUtil.js | lq782655835/ReactDemo | import React from 'react';
import ReactDOM from 'react-dom';
import { DataLoad } from './carcomponent';
//import { Modal } from 'antd';
class ComponentUtil{
constructor(){
this.loaderId = 'mask-loader';
}
showLoading = (loadMsg='Loading...') => {
let loading = document.getElementById(this.loaderId);
if(loading)
return;
let div = document.createElement('div');
div.id = this.loaderId;
document.body.appendChild(div);
ReactDOM.render(<DataLoad loadMsg={loadMsg}/>, div);
}
hideLoading = () => {
let loading = document.getElementById(this.loaderId);
if(!loading)
return;
loading.parentNode.removeChild(loading);
}
}
export default new ComponentUtil(); |
examples/src/components/CustomOption.js | lemming/react-select | import React from 'react';
import Gravatar from 'react-gravatar';
var Option = React.createClass({
propTypes: {
addLabelText: React.PropTypes.string,
className: React.PropTypes.string,
mouseDown: React.PropTypes.func,
mouseEnter: React.PropTypes.func,
mouseLeave: React.PropTypes.func,
option: React.PropTypes.object.isRequired,
renderFunc: React.PropTypes.func
},
render () {
var obj = this.props.option;
var size = 15;
var gravatarStyle = {
borderRadius: 3,
display: 'inline-block',
marginRight: 10,
position: 'relative',
top: -2,
verticalAlign: 'middle',
};
return (
<div className={this.props.className}
onMouseEnter={this.props.mouseEnter}
onMouseLeave={this.props.mouseLeave}
onMouseDown={this.props.mouseDown}
onClick={this.props.mouseDown}>
<Gravatar email={obj.email} size={size} style={gravatarStyle} />
{obj.value}
</div>
);
}
});
module.exports = Option;
|
src/AppHeader.js | tvthatsme/yalla-qari | import React, { Component } from 'react';
class AppHeader extends Component {
render() {
return (
<div className="AppHeader">
Yalla Qari
</div>
);
}
}
export default AppHeader;
|
packages/vx-grid/src/grids/Columns.js | Flaque/vx | import React from 'react';
import cx from 'classnames';
import { Line } from '@vx/shape';
import { Group } from '@vx/group';
import { Point } from '@vx/point';
export default function Columns({
top = 0,
left = 0,
scale,
height,
stroke = '#eaf0f6',
strokeWidth = 1,
strokeDasharray,
className,
numTicks = 10,
lineStyle,
...restProps
}) {
return (
<Group
className={cx('vx-columns', className)}
top={top}
left={left}
>
{scale.ticks &&
scale.ticks(numTicks).map((d, i) => {
const x = scale(d);
const fromPoint = new Point({
x,
y: 0,
});
const toPoint = new Point({
x,
y: height,
});
return (
<Line
key={`column-line-${d}-${i}`}
from={fromPoint}
to={toPoint}
stroke={stroke}
strokeWidth={strokeWidth}
strokeDasharray={strokeDasharray}
style={lineStyle}
{...restProps}
/>
);
})}
</Group>
);
}
|
src/components/operatorDiagram/transformNote.js | philpl/rxjs-diagrams | import React from 'react'
import { white, black, gray } from '../../constants/colors'
import { fontFamily, fontSize } from '../../constants/font'
const textStyle = height => ({
fontFamily,
fontSize: `${height * 0.24}px`,
lineHeight: `${height * 0.24}px`,
textShadow: 'none'
})
const TransformNote = ({
stroke,
children,
width = 500,
height = 50,
x = 0,
y = 0
}) => (
<g>
<rect
x={x}
y={y}
width={width - 2}
height={height}
fill={white.opacity(.95).toString()}
stroke={stroke}
strokeWidth={2}
/>
<text
x={x + width / 2}
y={y + height / 2}
textAnchor="middle"
alignmentBaseline="central"
stroke={black}
fill={black}
style={textStyle(height)}
>
{children}
</text>
</g>
)
export default TransformNote
|
todos/src/app/App.js | vnsgbt/reduxactdemo | import React from 'react';
import AddTodo from '../addToDo/AddTodo';
const App = () => (
<div>
<AddTodo />
</div>
);
export default App;
|
skm-spa/weather-jsx/src/index.js | krulik/demos | import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
import App from './App/App.jsx';
ReactDOM.render(<App />, document.querySelector('main'));
|
src/app/views/projects/components/addProject/index.js | kristjanpikk/things-to-do | import React from 'react';
import './addProject.scss';
// Create AddProject component
export default class AddProject extends React.Component{
render() {
return(
<form className="projects__add-project" onSubmit={this.handleAddProject.bind(this)}>
<fieldset className="projects__add-project-container">
<input type="text" name="projects__new-project" ref="newProject" required />
<label className="label">Name your next project</label>
<input type="submit" value="" />
</fieldset>
</form>
);
} // Render
// Custom functions
handleAddProject(e) {
e.preventDefault();
this.props.onAddProject(this.refs.newProject.value);
this.refs.newProject.value = '';
}
}; |
src/containers/DevTools/DevTools.js | once-ler/react-fhir | 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/static/src/diagnostic/EquipmentForm_modules/AditionalEqupmentParameters_modules/PowerSourceParams.js | SnowBeaver/Vision | import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import {findDOMNode} from 'react-dom';
import {hashHistory} from 'react-router';
import {Link} from 'react-router';
import Checkbox from 'react-bootstrap/lib/Checkbox';
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
import Tooltip from 'react-bootstrap/lib/Tooltip';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
const TextField = React.createClass({
render: function () {
let tooltip = <Tooltip id={this.props.label}>{this.props.label}</Tooltip>;
var label = (this.props.label != null) ? this.props.label : "";
var name = (this.props.name != null) ? this.props.name : "";
var type = (this.props["data-type"] != null) ? this.props["data-type"]: undefined;
var len = (this.props["data-len"] != null) ? this.props["data-len"]: undefined;
var validationState = (this.props.errors[name]) ? 'error' : null;
var error = this.props.errors[name];
var value = (this.props["value"] != null) ? this.props["value"]: "";
return (
<OverlayTrigger overlay={tooltip} placement="top">
<FormGroup validationState={validationState}>
<ControlLabel>{label}</ControlLabel>
<FormControl type="text"
placeholder={label}
name={name}
data-type={type}
data-len={len}
onChange={this._onChange}
value={value}
/>
<HelpBlock className="warning">{error}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</OverlayTrigger>
);
}
});
var PowerSourceParams = React.createClass({
getInitialState: function () {
return {
'phase_number':'',
'sealed':'',
'welded_cover':'',
'kv':'',
'threephase':'',
'id':'',
'errors': {}
}
},
handleChange: function(e){
var state = this.state;
state[e.target.name] = e.target.value;
this.setState(state);
},
load:function() {
this.setState(this.props.equipment_item)
},
render: function () {
var errors = (Object.keys(this.state.errors).length) ? this.state.errors : this.props.errors;
return (
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Kv"
name="kv"
value={this.state.kv}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Three Phase"
name="threephase"
value={this.state.threephase}
errors={errors}
data-type="float"/>
</div>
</div>
)
}
});
export default PowerSourceParams; |
app/components/shared/headerNav.js | nypl-registry/browse | import React from 'react';
import { Router, Route, Link } from 'react-router';
const HeaderNav = React.createClass({
render() {
return (
<nav>
<div className="container">
<div className="row header">
<div className="eight columns">
<a href="http://www.nypl.org"><svg width="45" height="45" viewBox="0 0 150 150" version="1.1" style={{'fillRule': 'evenodd', 'clipRule' : 'evenodd', 'strokeLinejoin' : 'round', 'strokeMiterlimit' :1.41421}}><g id="Layer1"><path d="M123.096,122.247c-2.068,2.066 -3.241,0.446 -3.916,-0.881c-2.896,-6.158 -5.724,-11.311 -10.286,-16.304c-0.789,-0.8 -0.181,-1.925 0.981,-1.811c1.484,0.119 2.457,0.039 4.09,-0.664c1.382,-0.593 2.965,-2.53 3.755,-5.313c0.574,-2.03 0.602,-2.627 1.846,-2.754c0.308,-0.029 0.874,0.049 1.218,0.148c1.514,0.431 3.139,1.668 4.327,2.579c3.047,2.327 7.592,7.464 8.388,9.126c0.505,1.059 0.021,1.776 -0.263,2.381c-1.595,3.26 -6.623,10.014 -10.14,13.493ZM38.982,79.21c-4.348,-10.59 -1.509,-20.125 0.411,-23.742c0.969,-1.825 1.915,-3.018 3.15,-2.674c1.345,0.375 1.655,1.751 1.841,4.302c1.368,21.167 14.172,28.295 30.254,35.769c12.688,6.486 27.124,13.901 39.222,31.864c1.832,2.593 2.096,4.167 0.028,5.652c-7.375,5.036 -14.058,8.546 -23.835,10.825c-1.472,0.345 -2.989,0.087 -4.294,-3.276c-13.581,-34.995 -36.384,-33.417 -46.777,-58.72ZM7.838,61.948c0.152,-0.858 0.219,-1.097 0.736,-1.773c0.819,-1.225 10.76,-12.38 26.169,-15.083c2.028,-0.29 3.488,-0.15 3.821,0.663c0.582,1.425 -0.598,2.246 -2.017,3.068c-24.713,14.769 -22.961,36.726 -23.198,45.708c0.074,3.674 -2.579,4.343 -3.241,2.612c-2.901,-7.911 -5.339,-20.313 -2.27,-35.195ZM24.547,29.589c0.506,-0.537 0.836,-0.784 1.588,-0.995c9.491,-2.357 19.011,-0.857 25.868,2.201c1.539,0.681 2.233,1.647 1.222,2.295c-1.285,0.747 -5.181,3.281 -7.334,5.287c-0.626,0.54 -1.743,0.568 -2.4,0.48c-8.038,-1.059 -12.213,-1.685 -24.296,2.895c-1.854,0.78 -3.521,-0.281 -2.668,-1.738c1.609,-2.882 5.35,-7.702 8.02,-10.425ZM95.255,88.182c0.408,-1.179 0.884,-1.874 1.8,-2.448c1.726,-1.082 4.593,-1.129 7.361,-1.318c2.681,-0.181 5.547,-0.338 7.455,-1.219c1.155,-0.531 2.31,-2.044 4.094,-1.274c0.844,0.365 1.305,1.139 1.557,1.909c0.282,0.857 0.489,1.724 0.401,2.873c-0.257,3.319 -2.952,4.94 -3.437,8.041c-0.045,0.479 -0.127,1.173 -0.402,1.449c-2.057,2.094 -6.127,1.654 -9.806,1.283c-1.317,-0.13 -2.619,-0.166 -3.51,-0.59c-0.642,-0.301 -1.219,-0.914 -1.753,-1.41c-1.177,-1.091 -1.843,-1.894 -3.023,-3.217c-0.4,-0.448 -1.307,-1.259 -1.366,-1.752c-0.052,-0.472 0.454,-1.83 0.629,-2.327ZM40.165,20.107c-2.079,-0.237 -2.108,-1.757 -1.229,-2.349c2.257,-1.582 5.921,-3.492 9.606,-4.953c1.104,-0.437 1.673,-0.551 2.684,-0.449c2.716,0.271 7.213,2.1 12.373,5.781c6.188,4.416 11.693,12.804 8.011,12.125c-2.328,-0.403 -1.314,-0.292 -4.044,-0.592c-2.789,-0.247 -4.619,0.039 -5.904,-0.092c-0.56,-0.046 -1.001,-0.418 -1.396,-0.741c-5.223,-4.683 -11.256,-7.656 -20.101,-8.73ZM56.574,39.013c2.453,-1.941 9.526,-4.639 17.947,-2.567c2.383,0.587 8.615,2.624 12.755,4.652c4.058,1.86 6.949,5.315 10.721,7.406c4.763,2.646 11.309,3.881 16.349,6.348c1.015,0.496 3.695,2.29 2.945,2.673c-2.544,1.116 -6.964,0.473 -9.609,-0.134c-1.334,-0.311 -2.996,-0.647 -3.655,0.539c-0.716,1.287 -0.203,3.26 0.35,4.461c0.658,1.436 1.579,2.469 2.774,3.021c1.636,0.754 3.879,0.794 5.384,1.661c2.805,1.611 2.912,6.884 1.074,9.5c-1.537,2.193 -6.114,2.591 -10.354,2.386c-4.105,-0.2 -8.865,-0.629 -11.89,0.634c-2.979,1.239 -4.418,3.333 -6.187,5.935c-0.236,0.322 -0.624,0.39 -0.995,0.137c-10.532,-6.329 -23.826,-9.588 -30.929,-19.62c-1.75,-2.476 -2.851,-5.485 -3.443,-9.064c-1.397,-8.464 2.182,-14.348 6.763,-17.968ZM118.703,70.673c-0.036,-0.262 -0.149,-1.149 -0.148,-1.332c0.003,-0.467 0.964,-1.104 1.413,-1.46c0.679,-0.541 1.467,-1.136 1.982,-1.396c0.187,-0.117 0.31,0.154 0.335,0.207c1.897,2.879 1.186,9.993 -0.185,13.375c-0.158,0.344 -0.448,0.478 -0.566,0.226c-0.699,-1.526 -1.737,-2.9 -2.928,-3.654c-0.22,-0.171 -0.237,-0.526 -0.22,-0.592c0.384,-1.607 0.582,-3.391 0.317,-5.374ZM139.588,93.424c-0.557,1.738 -1.219,3.92 -2.637,2.908c-2.635,-1.961 -8.492,-5.73 -14.163,-7.822c-0.305,-0.068 -0.27,-0.491 -0.163,-0.73c0.402,-0.89 0.583,-1.714 0.756,-2.768c0.162,-0.987 0.873,-1.646 1.363,-2.437c1.453,-2.321 2.241,-6.369 2.558,-8.894c0.241,-2.32 0.097,-4.905 -0.405,-7.06c-0.215,-0.92 -0.879,-2.107 -0.861,-3.124c0.017,-0.996 0.486,-2.039 0.582,-3.215c0.28,-3.402 -4.012,-6.237 -6.355,-7.33c-5.315,-2.482 -10.964,-4.701 -16.704,-7.73c-3.241,-1.709 -5.841,-5.459 -8.441,-7.471c-2.627,-2.026 -11.068,-5.374 -14.441,-6.265c-0.762,-0.24 -1.032,-0.557 -1.161,-1.163c-1.391,-6.637 -5.308,-13.948 -12.624,-19.602c-2.369,-1.841 0.287,-2.888 3.55,-3.047c51.435,-1.764 81.034,45.571 69.146,85.75ZM30.825,127.29c-1.35,-1.106 -1.931,-2.039 -2.707,-3.35c-6.3,-10.068 -9.831,-45.727 -1.713,-57.822c2.583,-4.237 5.32,-2.283 4.41,0.992c-1.554,7.353 -0.601,11.474 2.974,19.453c5.619,11.857 22.964,28.319 27.556,34.291c7.871,10.24 10.491,17.699 10.455,19.71c-0.042,1.541 -0.338,2.524 -3.04,2.296c-14.252,-1.13 -28.029,-7.038 -37.935,-15.57ZM74.095,1.048c-40.659,0 -73.789,33.06 -73.789,74.173c0,41.111 33.332,74.191 73.835,74.191c41.113,0 74.385,-33.063 74.385,-74.175c0,-41.113 -33.319,-74.189 -74.431,-74.189Z" style={{fill:'#231f20',fillRule: 'nonzero'}}/><path d="M77.656,53.569c1.832,0.606 3.814,1.118 5.216,1.9c0.83,0.465 1.666,1.708 2.826,1.56c1.149,-0.149 1.868,-2.427 2.094,-3.607c0.328,-1.701 0.149,-3.874 -0.437,-4.97c-0.971,-1.819 -3.734,-2.233 -6.628,-2.094c-1.967,0.091 -3.071,0.266 -4.581,0.73c-1.602,0.492 -3.826,1.555 -2.874,3.8c0.636,1.508 2.803,2.157 4.384,2.681Z" style={{fill: '#231f20', 'fillRule' : 'nonzero'}}/></g></svg></a>
<Link className="nypl" to={ this.props.link }><span >{ this.props.title }</span></Link>
</div>
</div>
</div>
</nav>
);
}
});
export default HeaderNav;
|
src/components/Main.js | jc784999074/study-react | require('normalize.css/normalize.css');
require('styles/App.css');
import React from 'react';
//let yeomanImage = require('../images/yeoman.png');
//获取图片
var imageDatas = require('../data/image.json');
//拉出URL
imageDatas = (function getImages(imageDatas) {
for (var i = 0, j = imageDatas.length; i < j; i++) {
var image = imageDatas[i];
image.imageURL = require('../images/' + image.fileName);
imageDatas[i] = image;
}
return imageDatas;
})(imageDatas);
//获取区间内的一个随机值
function getRangeRandom(low,hign) {
return Math.ceil(Math.random()*(hign - low) + low);
}
function get30DegRandom() {
return Math.random() > 0.5 ? '' : '-' + Math.ceil(Math.random() * 30)
}
//控制组件
var ControllerUnit=React.createClass({
handleClick:function(e) {
//如果电机的是选中态的按钮,翻转,否则居中
if(this.props.arrange.isCenter){
this.props.inverse();
}else{
this.props.center();
}
e.preventDefault();
e.stopPropagation();
},
render:function() {
var controllerUnitClasssName = 'controller-unit';
//如果对应的是居中的图片,显示控制按钮居中
if(this.props.arrange.isCenter){
controllerUnitClasssName +=' is-center';
//如果同时对应的是翻转图片,翻转
if(this.props.arrange.isInvers){
controllerUnitClasssName += ' is-inverse';
}
}
return (
<span className={controllerUnitClasssName} onClick={this.handleClick}></span>
);
}
});
var ImgFigure = React.createClass( {
//图片点击事件
handleClick:function(e) {
if(this.props.arrange.isCenter){
this.props.isInvers();
}else{
this.props.center();
}
e.stopPropagation();
e.preventDefault();
},
render:function (){
var styleObj = {};
//如果props属性中指定了这张图片的位置,则使用
if(this.props.arrange.pos){
styleObj = this.props.arrange.pos;
}
//如果图片的旋转角度有值并且不为0,添加旋转角度
if(this.props.arrange.rotate){
(['MozTransform','msTransform','WebkitTransform','transform']).forEach(function (value) {
styleObj[ value ] = 'rotate(' + this.props.arrange.rotate + 'deg)';
}.bind(this));
}
var imgFigureClassName = 'img-figure';
imgFigureClassName += this.props.arrange.isInvers ? ' is-inverse':'';
return (
<figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}>
<img src ={this.props.data.imageURL} alt={this.props.data.title} />
<figcaption>
<h2>{this.props.data.description}</h2>
<div className='img-back' onClick={this.handleClick}>
<p>
{this.props.data.description}
</p>
</div>
</figcaption>
</figure>
);
}
})
var AppComponent = React.createClass( {
Constant : {
centerPos:{
left:0,
right:0
},
hPosRange:{//水平方向取值范围
leftSecX:[0,0],
rightSecX:[0,0],
y:[0,0]
},
vPosRange:{//垂直方向取值范围
x:[0,0],
topY:[0,0]
}
},
/*
*翻转图片param index输入当前被执行inverse操作的图片对应的图片信息数组的index值
*return 一个闭包函数,其内return一个真正被执行的函数
*/
isInvers: function(index) {
return function() {
var imgsArrangeArr = this.state.imgsArrangeArr;
imgsArrangeArr[index].isInvers = !imgsArrangeArr[index].isInvers;
this.setState({
imgsArrangeArr:imgsArrangeArr
})
}.bind(this);
},
//重新布局所有图片,指定哪个图片居中
rearrange:function(centerIndex) {
var imgsArrangeArr = this.state.imgsArrangeArr,
Constant = this.Constant,
centerPos= Constant.centerPos,
hPosRange= Constant.hPosRange,
vPosRange= Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX= hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
imgsArrangeTopArr=[],
topImgNum = Math.floor(Math.random()*2),//一个或者不取
topImgSpliceIndex = 0,
imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);
//首先居中centerIndex的图片,无需旋转
imgsArrangeCenterArr[0]={
pos:centerPos,
rotate:0,
isCenter:true
}
//取出要布局上侧的状态信息
topImgSpliceIndex = Math.ceil(Math.random()*(imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum);
//布局位于上侧的图片
imgsArrangeTopArr.forEach(function(value,index) {
imgsArrangeTopArr[index]={
pos : {
top : getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1]),
left: getRangeRandom(vPosRangeX[0],vPosRangeX[1])
},
rotate:get30DegRandom(),
isCenter:false
}
});
//布局左右两侧的图片
for(var i=0,j=imgsArrangeArr.length,k=j/2;i<j;i++){
var hPosRangeLORX = null;
//前半部分布局左边,后半部分布局右边
if(i<k){
hPosRangeLORX = hPosRangeLeftSecX;
}else{
hPosRangeLORX = hPosRangeRightSecX;
}
imgsArrangeArr[i] = {
pos : {
top: getRangeRandom(hPosRangeY[0],hPosRangeY[1]),
left:getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1])
},
rotate : get30DegRandom(),
isCenter:false
}
}
if(imgsArrangeTopArr && imgsArrangeTopArr[0]){
imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]);
}
imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]);
this.setState({
imgsArrangeArr:imgsArrangeArr
});
},
/*
*利用rearrange凹函数,居中对应index图片
*@param index ,需要被居中的图片信息的index值
*@return{function}
*/
center:function(index) {
return function() {
this.rearrange(index);
}.bind(this);
},
getInitialState:function () {
return{
imgsArrangeArr:[
/*{
pos:{
left:0,
top:0
},
rotate:0,
isInverse:false, //图片正反面,默认正面
isCenter:false //是否居中
}*/
]
}
},
//组件加载后,计算图片范围
componentDidMount:function (){debugger;
//舞台大小
var stageDOM=this.refs.stage,
stageW = stageDOM.scrollWidth,
stageH = stageDOM.scrollHeight,
halfStageW= Math.ceil(stageW/2),
halfStageH=Math.ceil(stageH/2);
var imgFigureDOM = document.getElementsByTagName('img')[0],//component无法用ref获取未知原因
imgW = imgFigureDOM.parentNode.scrollWidth,
imgH = imgFigureDOM.parentNode.scrollHeight,
halfImgW = Math.ceil(imgW/2),
halfImgH = Math.ceil(imgH/2);
//中心图片位置点
this.Constant.centerPos = {
left:halfStageW-halfImgW,
top :halfStageH-halfImgH
}
//计算左右区域图片排布位置范围
this.Constant.hPosRange.leftSecX[0] = -halfImgW;
this.Constant.hPosRange.leftSecX[1] = halfStageW-halfImgW*3;
this.Constant.hPosRange.rightSecX[0]= halfImgW + halfStageW;
this.Constant.hPosRange.rightSecX[1]= stageW-halfImgW;
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[1] = stageH - halfImgH;
//计算上侧区域图片排布取值范围
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH*3;
this.Constant.vPosRange.x[0] = halfStageW - imgW;
this.Constant.vPosRange.x[1] = halfStageW;
this.rearrange(0);
},
render:function (){
var controllerUnits = [],
imgFigures = [];
imageDatas.forEach(function(element,index) {
if(!this.state.imgsArrangeArr[index]){
this.state.imgsArrangeArr[index] = {
pos:{
left:0,
top:0
},
rotate:0,
isInvers:false,
isCenter:false
}
}
imgFigures.push(
<ImgFigure data={element} key = {index} ref = {'imgFigure'+index} key = {'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} isInvers={this.isInvers(index)} center={this.center(index)} />)
controllerUnits.push(<ControllerUnit key = {index} arrange={this.state.imgsArrangeArr[index]} inverse={this.isInvers(index)} center={this.center(index)}/>);
}.bind(this));
return (
<section className='stage' ref='stage' style={{height:document.documentElement.clientHeight+'px'}}>
<section className='img-sec'>
{imgFigures}
</section>
<nav className = 'controller-nav'>
{controllerUnits}
</nav>
</section>
)
}
})
export default AppComponent;
|
src/svg-icons/action/thumb-up.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionThumbUp = (props) => (
<SvgIcon {...props}>
<path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z"/>
</SvgIcon>
);
ActionThumbUp = pure(ActionThumbUp);
ActionThumbUp.displayName = 'ActionThumbUp';
ActionThumbUp.muiName = 'SvgIcon';
export default ActionThumbUp;
|
ignite/DevScreens/DevscreensButton.js | TylerKirby/Phrontis | import React from 'react'
import { View, Modal } from 'react-native'
import DebugConfig from '../../App/Config/DebugConfig'
import RoundedButton from '../../App/Components/RoundedButton'
import PresentationScreen from './PresentationScreen'
export default class DevscreensButton extends React.Component {
constructor (props) {
super(props)
this.state = {
showModal: false
}
}
toggleModal = () => {
this.setState({ showModal: !this.state.showModal })
}
render () {
if (DebugConfig.showDevScreens) {
return (
<View>
<RoundedButton onPress={this.toggleModal}>
Open DevScreens
</RoundedButton>
<Modal
visible={this.state.showModal}
onRequestClose={this.toggleModal}>
<PresentationScreen screenProps={{ toggle: this.toggleModal }} />
</Modal>
</View>
)
} else {
return <View />
}
}
}
|
packages/material-ui-icons/legacy/Battery50.js | lgollut/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z" /><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z" /></React.Fragment>
, 'Battery50');
|
packages/web/src/components/Note/NoteLog.js | hengkx/note | import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import difflib from 'jsdifflib';
import './less/noteLog.less';
class NoteLog extends React.Component {
static propTypes = {
getLogList: PropTypes.func.isRequired,
id: PropTypes.string.isRequired,
getLogListResult: PropTypes.object,
};
constructor(props) {
super(props);
this.state = {
logs: []
};
}
componentDidMount() {
this.props.getLogList({ id: this.props.id });
}
componentWillReceiveProps(nextProps) {
const { getLogListResult } = nextProps;
if (getLogListResult !== this.props.getLogListResult) {
this.setState({ logs: getLogListResult.data });
}
}
handleSelected = (log) => {
const compare = difflib(log.old.content, log.new.content);
// console.log(compare);
this.setState({ selectedLog: log, compare });
}
renderCompare = () => {
const { result, baseTextLines, newTextLines } = this.state.compare;
return result.map((item) => {
const [type, ob, oe, nb, ne] = item;
const eles = [];
if (type === 'replace') {
for (let i = ob; i < oe; i += 1) {
eles.push(
<tr className="remove" key={`o${i}`}>
<td className="line-number">{i + 1}</td>
<td className="line-number" />
<td className="con">{baseTextLines[i]}</td>
</tr>
);
}
for (let i = nb; i < ne; i += 1) {
eles.push(
<tr className="add" key={`n${i}`}>
<td className="line-number" />
<td className="line-number">{i + 1}</td>
<td className="con">{newTextLines[i]}</td>
</tr>
);
}
} else if (type === 'insert') {
for (let i = nb; i < ne; i += 1) {
eles.push(
<tr className="add" key={`n${i}`}>
<td className="line-number" />
<td className="line-number">{i + 1}</td>
<td className="con">{newTextLines[i]}</td>
</tr>
);
}
} else if (type === 'equal') {
for (let i = nb; i < ne; i += 1) {
eles.push(
<tr className="equal" key={`n${i}`}>
<td className="line-number">{ob + 1 + (i - nb)}</td>
<td className="line-number">{i + 1}</td>
<td className="con">{newTextLines[i]}</td>
</tr>
);
}
}
return eles;
});
}
render() {
const { logs, selectedLog } = this.state;
return (
<div className="log">
<ul className="nav">
{logs.map(log => (
<li key={log.id}>
<a href="javascript:;" onClick={() => { this.handleSelected(log); }}>{moment.unix(log.created_at).format('YYYY-MM-DD HH:mm:ss')}</a>
</li>
))}
</ul>
{selectedLog &&
<div className="compare">
<table>
<tbody>
{this.renderCompare()}
</tbody>
</table>
</div>
}
</div>
);
}
}
export default NoteLog;
|
src/interface/layout/NavigationBar/index.js | FaideWW/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Trans, t } from '@lingui/macro';
import PatreonIcon from 'interface/icons/PatreonTiny';
import DiscordIcon from 'interface/icons/DiscordTiny';
import GitHubIcon from 'interface/icons/GitHubMarkSmall';
import PremiumIcon from 'interface/icons/Premium';
import { i18n } from 'interface/RootLocalizationProvider';
import { getFightId, getPlayerName, getReportCode } from 'interface/selectors/url/report';
import { getReport } from 'interface/selectors/report';
import { getFightById } from 'interface/selectors/fight';
import { getReportProgress } from 'interface/selectors/reportProgress';
import { getUser } from 'interface/selectors/user';
import makeAnalyzerUrl from 'interface/common/makeAnalyzerUrl';
import FightSelectorHeader from './FightSelectorHeader';
import PlayerSelectorHeader from './PlayerSelectorHeader';
import LoadingBar from './LoadingBar';
import './NavigationBar.css';
class NavigationBar extends React.PureComponent {
static propTypes = {
playerName: PropTypes.string,
report: PropTypes.shape({
title: PropTypes.string.isRequired,
}),
fight: PropTypes.object,
progress: PropTypes.number,
user: PropTypes.shape({
name: PropTypes.string.isRequired,
premium: PropTypes.bool.isRequired,
}),
};
render() {
const { playerName, report, fight, progress, user } = this.props;
return (
<nav className="global">
<div className="container">
<div className="menu-item logo required">
<Link to={makeAnalyzerUrl()} data-tip="Home">
<img src="/favicon.png" alt="WoWAnalyzer logo" />
</Link>
</div>
{report && (
<div className="menu-item" data-tip={i18n._(t`Back to fight selection`)}>
<Link to={makeAnalyzerUrl(report)}>{report.title}</Link>
</div>
)}
{report && fight && (
<FightSelectorHeader className="menu-item" data-tip={i18n._(t`Change fight`)} />
)}
{report && playerName && (
<PlayerSelectorHeader className="menu-item" data-tip={i18n._(t`Change player`)} />
)}
<div className="spacer" />
<div className="menu-item required">
{user && user.premium ? (
<Link to="/premium" data-tip="Premium active">
<PremiumIcon /> <span className="optional">{user.name}</span>
</Link>
) : (
<Link to="/premium" className="premium" data-tip={i18n._(t`Premium`)}>
<PremiumIcon /> <span className="optional"><Trans>Premium</Trans></span>
</Link>
)}
</div>
<div className="menu-item optional" data-tip="Discord">
<a href="https://wowanalyzer.com/discord">
<DiscordIcon />
</a>
</div>
<div className="menu-item optional" data-tip="GitHub">
<a href="https://github.com/WoWAnalyzer/WoWAnalyzer">
<GitHubIcon />
</a>
</div>
<div className="menu-item optional" data-tip="Patreon">
<a href="https://www.patreon.com/wowanalyzer">
<PatreonIcon />
</a>
</div>
</div>
<LoadingBar progress={progress} />
</nav>
);
}
}
const mapStateToProps = state => ({
playerName: getPlayerName(state),
report: getReportCode(state) && getReport(state),
fight: getFightById(state, getFightId(state)),
progress: getReportProgress(state),
user: getUser(state),
});
export default connect(
mapStateToProps
)(NavigationBar);
|
fields/types/number/NumberFilter.js | snowkeeper/keystone | import React from 'react';
import { findDOMNode } from 'react-dom';
import { FormField, FormInput, FormRow, FormSelect } from 'elemental';
const MODE_OPTIONS = [
{ label: 'Exactly', value: 'equals' },
{ label: 'Greater Than', value: 'gt' },
{ label: 'Less Than', value: 'lt' },
{ label: 'Between', value: 'between' },
];
function getDefaultValue () {
return {
mode: MODE_OPTIONS[0].value,
value: '',
};
}
var NumberFilter = React.createClass({
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
componentDidMount () {
// focus the text input
findDOMNode(this.refs.focusTarget).focus();
},
handleChangeBuilder (type) {
const self = this;
return function handleChange (e) {
const { filter, onChange } = self.props;
switch (type) {
case 'minValue':
onChange({
mode: filter.mode,
value: {
min: e.target.value,
max: filter.value.max,
},
});
break;
case 'maxValue':
onChange({
mode: filter.mode,
value: {
min: filter.value.min,
max: e.target.value,
},
});
break;
case 'value':
onChange({
mode: filter.mode,
value: e.target.value,
});
}
};
},
// Update the props with this.props.onChange
updateFilter (changedProp) {
this.props.onChange({ ...this.props.filter, ...changedProp });
},
// Update the filter mode
selectMode (mode) {
this.updateFilter({ mode });
// focus on next tick
setTimeout(() => {
findDOMNode(this.refs.focusTarget).focus();
}, 0);
},
renderControls (mode) {
let controls;
const { field } = this.props;
const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...';
if (mode.value === 'between') {
controls = (
<FormRow>
<FormField width="one-half" style={{ marginBottom: 0 }}>
<FormInput
onChange={this.handleChangeBuilder('minValue')}
placeholder="Min."
ref="focusTarget"
type="number"
/>
</FormField>
<FormField width="one-half" style={{ marginBottom: 0 }}>
<FormInput
onChange={this.handleChangeBuilder('maxValue')}
placeholder="Max."
type="number"
/>
</FormField>
</FormRow>
);
} else {
controls = (
<FormField>
<FormInput
onChange={this.handleChangeBuilder('value')}
placeholder={placeholder}
ref="focusTarget"
type="number"
/>
</FormField>
);
}
return controls;
},
render () {
const { filter } = this.props;
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
return (
<div>
<FormSelect
onChange={this.selectMode}
options={MODE_OPTIONS}
value={mode.value}
/>
{this.renderControls(mode)}
</div>
);
},
});
module.exports = NumberFilter;
|
source/client/components/App.js | worminer/React.js-Financial-News | import React from 'react'
import UserActions from '../actions/UserActions'
import UserStore from '../stores/UserStore'
import Footer from './Footer'
import Navbar from './Navbar'
export default class App extends React.Component {
constructor (props) {
super(props)
this.state = UserStore.getState()
this.onChange = this.onChange.bind(this)
}
onChange (state) {
this.setState(state)
}
componentDidMount () {
UserStore.listen(this.onChange)
}
componentWillUnmount () {
UserStore.unlisten(this.onChange)
}
render () {
return (
<div>
<Navbar />
{this.props.children}
<Footer />
</div>
)
}
}
|
src/containers/Root.js | bplabombarda/3on3bot.com | import React from 'react'
import DatePicker from 'react-datepicker'
import { hot } from 'react-hot-loader'
import 'react-datepicker/dist/react-datepicker.css'
import getSchedule from '../utils/getSchedule'
class Root extends React.Component {
state = {
date: new Date(2016, 9, 16),
gamesByDate: {},
loading: true,
}
componentDidMount = async () => {
const games = await this.fetchGames(this.state.date)
this.setState({
gamesByDate: {
[this.state.date]: games,
},
loading: false,
})
}
fetchGames = async (date) => {
const schedule = await getSchedule(date)
return await this.getOtGames(schedule)
}
handleChange = (date) => {
this.setState({
loading: true,
}, async () => {
const games = await this.fetchGames(date)
this.setState({
date,
gamesByDate: {
...this.state.gamesByDate,
[date]: games,
},
loading: false,
})
})
}
isOvertime = (game) => {
const { currentPeriod }= game.linescore
const { statusCode }= game.status
return currentPeriod === 4 && parseInt(statusCode) === 7
}
getOtGames = (schedule) => {
return schedule.dates.reduce((acc, date) => {
const otGames = date.games.filter((game) => {
return this.isOvertime(game)
})
return [ ...acc, ...otGames ]
}, [])
}
render () {
return (
<>
<h1>{ this.state.loading ? 'Loading': 'Done' }</h1>
<DatePicker
selected={ this.state.date }
onChange={ this.handleChange }
/>
</>
)
}
}
export default hot(module)(Root) |
src/svg-icons/image/crop-7-5.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCrop75 = (props) => (
<SvgIcon {...props}>
<path d="M19 7H5c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm0 8H5V9h14v6z"/>
</SvgIcon>
);
ImageCrop75 = pure(ImageCrop75);
ImageCrop75.displayName = 'ImageCrop75';
ImageCrop75.muiName = 'SvgIcon';
export default ImageCrop75;
|
packages/simple-cache-provider/src/SimpleCacheProvider.js | prometheansacrifice/react | /**
* Copyright (c) 2014-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.
*
* @flow
*/
import React from 'react';
import warning from 'fbjs/lib/warning';
function noop() {}
const Empty = 0;
const Pending = 1;
const Resolved = 2;
const Rejected = 3;
type EmptyRecord<K> = {|
status: 0,
suspender: null,
key: K,
value: null,
error: null,
next: any, // TODO: (issue #12941)
previous: any, // TODO: (issue #12941)
/**
* Proper types would be something like this:
* next: Record<K, V> | null,
* previous: Record<K, V> | null,
*/
|};
type PendingRecord<K, V> = {|
status: 1,
suspender: Promise<V>,
key: K,
value: null,
error: null,
next: any, // TODO: (issue #12941)
previous: any, // TODO: (issue #12941)
/**
* Proper types would be something like this:
* next: Record<K, V> | null,
* previous: Record<K, V> | null,
*/
|};
type ResolvedRecord<K, V> = {|
status: 2,
suspender: null,
key: K,
value: V,
error: null,
next: any, // TODO: (issue #12941)
previous: any, // TODO: (issue #12941)
/**
* Proper types would be something like this:
* next: Record<K, V> | null,
* previous: Record<K, V> | null,
*/
|};
type RejectedRecord<K> = {|
status: 3,
suspender: null,
key: K,
value: null,
error: Error,
next: any, // TODO: (issue #12941)
previous: any, // TODO: (issue #12941)
/**
* Proper types would be something like this:
* next: Record<K, V> | null,
* previous: Record<K, V> | null,
*/
|};
type Record<K, V> =
| EmptyRecord<K>
| PendingRecord<K, V>
| ResolvedRecord<K, V>
| RejectedRecord<K>;
type RecordCache<K, V> = {|
map: Map<K, Record<K, V>>,
head: Record<K, V> | null,
tail: Record<K, V> | null,
size: number,
|};
// TODO: How do you express this type with Flow?
type ResourceMap = Map<any, RecordCache<any, any>>;
type Cache = {
invalidate(): void,
read<K, V, A>(
resourceType: mixed,
key: K,
miss: (A) => Promise<V>,
missArg: A,
): V,
preload<K, V, A>(
resourceType: mixed,
key: K,
miss: (A) => Promise<V>,
missArg: A,
): void,
// DEV-only
$$typeof?: Symbol | number,
};
let CACHE_TYPE;
if (__DEV__) {
CACHE_TYPE = 0xcac4e;
}
let isCache;
if (__DEV__) {
isCache = value =>
value !== null &&
typeof value === 'object' &&
value.$$typeof === CACHE_TYPE;
}
// TODO: Make this configurable per resource
const MAX_SIZE = 500;
const PAGE_SIZE = 50;
function createRecord<K>(key: K): EmptyRecord<K> {
return {
status: Empty,
suspender: null,
key,
value: null,
error: null,
next: null,
previous: null,
};
}
function createRecordCache<K, V>(): RecordCache<K, V> {
return {
map: new Map(),
head: null,
tail: null,
size: 0,
};
}
export function createCache(invalidator: () => mixed): Cache {
const resourceMap: ResourceMap = new Map();
function accessRecord<K, V>(resourceType: any, key: K): Record<K, V> {
if (__DEV__) {
warning(
typeof resourceType !== 'string' && typeof resourceType !== 'number',
'Invalid resourceType: Expected a symbol, object, or function, but ' +
'instead received: %s. Strings and numbers are not permitted as ' +
'resource types.',
resourceType,
);
}
let recordCache = resourceMap.get(resourceType);
if (recordCache === undefined) {
recordCache = createRecordCache();
resourceMap.set(resourceType, recordCache);
}
const map = recordCache.map;
let record = map.get(key);
if (record === undefined) {
// This record does not already exist. Create a new one.
record = createRecord(key);
map.set(key, record);
if (recordCache.size >= MAX_SIZE) {
// The cache is already at maximum capacity. Remove PAGE_SIZE least
// recently used records.
// TODO: We assume the max capcity is greater than zero. Otherwise warn.
const tail = recordCache.tail;
if (tail !== null) {
let newTail = tail;
for (let i = 0; i < PAGE_SIZE && newTail !== null; i++) {
recordCache.size -= 1;
map.delete(newTail.key);
newTail = newTail.previous;
}
recordCache.tail = newTail;
if (newTail !== null) {
newTail.next = null;
}
}
}
} else {
// This record is already cached. Remove it from its current position in
// the list. We'll add it to the front below.
const previous = record.previous;
const next = record.next;
if (previous !== null) {
previous.next = next;
} else {
recordCache.head = next;
}
if (next !== null) {
next.previous = previous;
} else {
recordCache.tail = previous;
}
recordCache.size -= 1;
}
// Add the record to the front of the list.
const head = recordCache.head;
const newHead = record;
recordCache.head = newHead;
newHead.previous = null;
newHead.next = head;
if (head !== null) {
head.previous = newHead;
} else {
recordCache.tail = newHead;
}
recordCache.size += 1;
return newHead;
}
function load<K, V>(emptyRecord: EmptyRecord<K>, suspender: Promise<V>) {
const pendingRecord: PendingRecord<K, V> = (emptyRecord: any);
pendingRecord.status = Pending;
pendingRecord.suspender = suspender;
suspender.then(
value => {
// Resource loaded successfully.
const resolvedRecord: ResolvedRecord<K, V> = (pendingRecord: any);
resolvedRecord.status = Resolved;
resolvedRecord.suspender = null;
resolvedRecord.value = value;
},
error => {
// Resource failed to load. Stash the error for later so we can throw it
// the next time it's requested.
const rejectedRecord: RejectedRecord<K> = (pendingRecord: any);
rejectedRecord.status = Rejected;
rejectedRecord.suspender = null;
rejectedRecord.error = error;
},
);
}
const cache: Cache = {
invalidate() {
invalidator();
},
preload<K, V, A>(
resourceType: any,
key: K,
miss: A => Promise<V>,
missArg: A,
): void {
const record: Record<K, V> = accessRecord(resourceType, key);
switch (record.status) {
case Empty:
// Warm the cache.
const suspender = miss(missArg);
load(record, suspender);
return;
case Pending:
// There's already a pending request.
return;
case Resolved:
// The resource is already in the cache.
return;
case Rejected:
// The request failed.
return;
}
},
read<K, V, A>(
resourceType: any,
key: K,
miss: A => Promise<V>,
missArg: A,
): V {
const record: Record<K, V> = accessRecord(resourceType, key);
switch (record.status) {
case Empty:
// Load the requested resource.
const suspender = miss(missArg);
load(record, suspender);
throw suspender;
case Pending:
// There's already a pending request.
throw record.suspender;
case Resolved:
return record.value;
case Rejected:
default:
// The requested resource previously failed loading.
const error = record.error;
throw error;
}
},
};
if (__DEV__) {
cache.$$typeof = CACHE_TYPE;
}
return cache;
}
let warnIfNonPrimitiveKey;
if (__DEV__) {
warnIfNonPrimitiveKey = (key, methodName) => {
warning(
typeof key === 'string' ||
typeof key === 'number' ||
typeof key === 'boolean' ||
key === undefined ||
key === null,
'%s: Invalid key type. Expected a string, number, symbol, or boolean, ' +
'but instead received: %s' +
'\n\nTo use non-primitive values as keys, you must pass a hash ' +
'function as the second argument to createResource().',
methodName,
key,
);
};
}
type primitive = string | number | boolean | void | null;
type Resource<K, V> = {|
read(Cache, K): V,
preload(cache: Cache, key: K): void,
|};
// These declarations are used to express function overloading. I wish there
// were a more elegant way to do this in the function definition itself.
// Primitive keys do not request a hash function.
declare function createResource<V, K: primitive, H: primitive>(
loadResource: (K) => Promise<V>,
hash?: (K) => H,
): Resource<K, V>;
// Non-primitive keys *do* require a hash function.
// eslint-disable-next-line no-redeclare
declare function createResource<V, K: mixed, H: primitive>(
loadResource: (K) => Promise<V>,
hash: (K) => H,
): Resource<K, V>;
// eslint-disable-next-line no-redeclare
export function createResource<V, K, H: primitive>(
loadResource: K => Promise<V>,
hash: K => H,
): Resource<K, V> {
const resource = {
read(cache, key) {
if (__DEV__) {
warning(
isCache(cache),
'read(): The first argument must be a cache. Instead received: %s',
cache,
);
}
if (hash === undefined) {
if (__DEV__) {
warnIfNonPrimitiveKey(key, 'read');
}
return cache.read(resource, key, loadResource, key);
}
const hashedKey = hash(key);
return cache.read(resource, hashedKey, loadResource, key);
},
preload(cache, key) {
if (__DEV__) {
warning(
isCache(cache),
'preload(): The first argument must be a cache. Instead received: %s',
cache,
);
}
if (hash === undefined) {
if (__DEV__) {
warnIfNonPrimitiveKey(key, 'preload');
}
cache.preload(resource, key, loadResource, key);
return;
}
const hashedKey = hash(key);
cache.preload(resource, hashedKey, loadResource, key);
},
};
return resource;
}
// Global cache has no eviction policy (except for, ya know, a browser refresh).
const globalCache = createCache(noop);
export const SimpleCache = React.createContext(globalCache);
|
app/javascript/mastodon/features/ui/components/confirmation_modal.js | corzntin/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, FormattedMessage } from 'react-intl';
import Button from '../../../components/button';
@injectIntl
export default class ConfirmationModal extends React.PureComponent {
static propTypes = {
message: PropTypes.node.isRequired,
confirm: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
componentDidMount() {
this.button.focus();
}
handleClick = () => {
this.props.onClose();
this.props.onConfirm();
}
handleCancel = () => {
this.props.onClose();
}
setRef = (c) => {
this.button = c;
}
render () {
const { message, confirm } = this.props;
return (
<div className='modal-root__modal confirmation-modal'>
<div className='confirmation-modal__container'>
{message}
</div>
<div className='confirmation-modal__action-bar'>
<Button onClick={this.handleCancel} className='confirmation-modal__cancel-button'>
<FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' />
</Button>
<Button text={confirm} onClick={this.handleClick} ref={this.setRef} />
</div>
</div>
);
}
}
|
docs/app/Examples/elements/List/Variations/ListExampleVeryRelaxed.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Image, List } from 'semantic-ui-react'
const ListExampleVeryRelaxed = () => (
<List relaxed='very'>
<List.Item>
<Image avatar src='http://semantic-ui.com/images/avatar/small/daniel.jpg' />
<List.Content>
<List.Header as='a'>Daniel Louise</List.Header>
<List.Description>Last seen watching <a><b>Arrested Development</b></a> just now.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='http://semantic-ui.com/images/avatar/small/stevie.jpg' />
<List.Content>
<List.Header as='a'>Stevie Feliciano</List.Header>
<List.Description>Last seen watching <a><b>Bob's Burgers</b></a> 10 hours ago.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='http://semantic-ui.com/images/avatar/small/elliot.jpg' />
<List.Content>
<List.Header as='a'>Elliot Fu</List.Header>
<List.Description>Last seen watching <a><b>The Godfather Part 2</b></a> yesterday.</List.Description>
</List.Content>
</List.Item>
</List>
)
export default ListExampleVeryRelaxed
|
src/ui/components/html.js | redcom/aperitive | // @flow
import React from 'react';
type Props = {
content: string,
state: Object,
assetMap: Object,
aphroditeCss: Object,
};
const Html = ({ content, state, assetMap, aphroditeCss }: Props) => {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>
Aperitive isomorphic fullstack based on: graphql, apollo-client, apollo-server, react, webpack
</title>
{!__DEV__ &&
<link
rel="stylesheet"
type="text/css"
href={`/assets/${assetMap['bundle.css']}`}
/>
}
{__DEV__ &&
<style dangerouslySetInnerHTML={{ __html:
require('../styles.scss')._getCss(),
}}/>
}
<link rel="shortcut icon" href="/favicon.ico"/>
<style data-aphrodite>{aphroditeCss.content}</style>
</head>
<body>
<div id="content" dangerouslySetInnerHTML={{ __html: content }} />
<script
dangerouslySetInnerHTML={{ __html: `window.__APOLLO_STATE__=${JSON.stringify(state)};` }}
charSet="UTF-8"
/>
<script src={`/assets/${assetMap['vendor.js']}`} charSet="utf-8" />
<script src={`/assets/${assetMap['bundle.js']}`} charSet="utf-8" />
</body>
</html>
);
};
export default Html;
|
src/native.js | davidkpiano/redux-simple-form | /* eslint-disable react/prop-types */
import React from 'react';
import {
MapView,
Picker,
DatePickerIOS,
DatePickerAndroid as RNDatePickerAndroid,
Switch,
TextInput,
SegmentedControlIOS,
Slider,
Text,
View,
} from 'react-native';
import SegmentedControlAndroid from 'react-native-segmented-control-tab';
import modelReducer from './reducers/model-reducer';
import formReducer from './reducers/form-reducer';
import modeled from './enhancers/modeled-enhancer';
import actions from './actions';
import combineForms, { createForms } from './reducers/forms-reducer';
import initialFieldState from './constants/initial-field-state';
import actionTypes from './action-types';
import Form from './components/form-component';
import Fieldset from './components/fieldset-component';
import Errors from './components/errors-component';
import batched from './enhancers/batched-enhancer';
import form from './form';
import track from './utils/track';
import omit from './utils/omit';
import _get from './utils/get';
import getFieldFromState from './utils/get-field-from-state';
import createControlClass from './components/control-component-factory';
function getTextValue(value) {
if (typeof value === 'string' || typeof value === 'number') {
return `${value}`;
}
return '';
}
const DatePickerAndroid = (...args) => ({
open: async () => {
const { action, year, month, day } = await RNDatePickerAndroid.open(...args);
const dismissed = action === RNDatePickerAndroid.dismissedAction;
return { dismissed, action, year, month, day };
},
});
const noop = () => undefined;
const Control = createControlClass({
get: _get,
getFieldFromState,
actions,
});
Control.MapView = (props) => (
<Control
component={MapView}
updateOn="blur"
mapProps={{
onResponderGrant: ({ onFocus }) => onFocus,
onRegionChange: ({ onChange }) => onChange,
onRegionChangeComplete: ({ onBlur }) => onBlur,
region: ({ modelValue }) => modelValue,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
Control.Picker = (props) => (
<Control
component={Picker}
mapProps={{
onResponderGrant: ({ onFocus }) => onFocus,
onResponderRelease: ({ onBlur }) => onBlur,
selectedValue: ({ modelValue }) => modelValue,
onValueChange: ({ onChange }) => onChange,
onChange: noop,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
Control.Switch = (props) => (
<Control
component={Switch}
mapProps={{
onResponderGrant: ({ onFocus }) => onFocus,
onResponderRelease: ({ onBlur }) => onBlur,
value: ({ modelValue }) => ! ! modelValue,
onValueChange: ({ onChange }) => onChange,
onChange: noop,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
Control.TextInput = (props) => (
<Control
component={TextInput}
mapProps={{
onResponderGrant: ({ onFocus }) => onFocus,
value: (_props) => ((! _props.defaultValue && ! _props.hasOwnProperty('value'))
? getTextValue(_props.viewValue)
: _props.value),
onChangeText: ({ onChange }) => onChange,
onChange: noop,
onBlur: ({ onBlur, viewValue }) => () => onBlur(viewValue),
onFocus: ({ onFocus }) => onFocus,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
Control.DatePickerIOS = (props) => (
<Control
component={DatePickerIOS}
mapProps={{
onResponderGrant: ({ onFocus }) => onFocus,
onResponderRelease: ({ onBlur }) => onBlur,
date: ({ modelValue }) => modelValue,
onDateChange: ({ onChange }) => onChange,
onChange: noop,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
Control.DatePickerAndroid = DatePickerAndroid;
Control.SegmentedControlIOS = (props) => (
<Control
component={SegmentedControlIOS}
mapProps={{
onResponderGrant: ({ onFocus }) => onFocus,
selectedIndex: ({ values, modelValue }) => values.indexOf(modelValue),
onValueChange: ({ onChange }) => onChange,
onChange: noop,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
Control.SegmentedControlAndroid = (props) => (
<Control
component={SegmentedControlAndroid}
mapProps={{
onResponderGrant: ({ onFocus }) => onFocus,
selectedIndex: ({ values, modelValue }) => values.indexOf(modelValue),
onValueChange: ({ onChange }) => onChange,
onChange: noop,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
Control.Slider = (props) => (
<Control
component={Slider}
mapProps={{
value: ({ modelValue }) => modelValue,
onResponderGrant: ({ onFocus }) => onFocus,
onSlidingComplete: ({ onBlur }) => onBlur,
onValueChange: ({ onChange }) => onChange,
onChange: noop,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
const NativeForm = (props) => <Form component={View} {...omit(props, 'mapProps')} />;
const NativeFieldset = (props) => <Fieldset component={View} {...omit(props, 'mapProps')} />;
const NativeErrors = (props) => (
<Errors
wrapper={View}
component={Text}
{...props}
/>
);
export {
// Reducers
formReducer,
modelReducer,
createForms,
combineForms,
// Constants
initialFieldState,
actions,
actionTypes,
// Components
Control,
NativeForm as Form,
NativeErrors as Errors,
NativeFieldset as Fieldset,
// Enhancers
modeled,
batched,
// Selectors
form,
// Utilities
getFieldFromState as getField,
track,
};
|
client/src/components/dashboard/Profile/Preferences/common/SaveModal.js | FCC-Alumni/alumni-network | import React from 'react';
import { Button, Modal } from 'semantic-ui-react';
const SaveModal = ({ size, close, open, warning, isValid }) => {
const context = {
buttonColor: isValid ? 'green' : 'red',
header: isValid ? 'Success' : 'Error(s)',
headerColor: isValid ? '#007E00' : '#FF4025',
text: isValid
? 'Your profile has been successfully updated!'
: 'Please review the page, correct any errors, and then try again.',
}
return (
<div>
<Modal onClose={close}open={open} size={size}>
<Modal.Header style={{ background: context.headerColor, color: 'white'}}>
{ context.header }
</Modal.Header>
<Modal.Content>
<h3 className="ui header">{context.text}</h3>
{ warning &&
<div>
{ !warning.slice(0, 4) === 'Nice' &&
<h4 className="ui header">
<i className="small red warning sign icon" />
{'But, your profile looks a bit bare...'}
</h4> }
<p>{warning}</p>
</div> }
</Modal.Content>
<Modal.Actions>
<Button
color={context.buttonColor}
content='Ok'
icon='checkmark'
labelPosition='right'
onClick={close} />
</Modal.Actions>
</Modal>
</div>
);
}
export default SaveModal;
|
src/svg-icons/places/child-care.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesChildCare = (props) => (
<SvgIcon {...props}>
<circle cx="14.5" cy="10.5" r="1.25"/><circle cx="9.5" cy="10.5" r="1.25"/><path d="M22.94 12.66c.04-.21.06-.43.06-.66s-.02-.45-.06-.66c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66s.02.45.06.66c.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2zM7.5 14c.76 1.77 2.49 3 4.5 3s3.74-1.23 4.5-3h-9z"/>
</SvgIcon>
);
PlacesChildCare = pure(PlacesChildCare);
PlacesChildCare.displayName = 'PlacesChildCare';
PlacesChildCare.muiName = 'SvgIcon';
export default PlacesChildCare;
|
packages/benchmarks/src/implementations/react-jss/View.js | css-components/styled-components | /* eslint-disable react/prop-types */
import classnames from 'classnames';
import injectSheet from 'react-jss';
import React from 'react';
class View extends React.Component {
render() {
const { classes, className, ...other } = this.props;
return <div {...other} className={classnames(classes.root, className)} />;
}
}
const styles = {
root: {
alignItems: 'stretch',
borderWidth: 0,
borderStyle: 'solid',
boxSizing: 'border-box',
display: 'flex',
flexBasis: 'auto',
flexDirection: 'column',
flexShrink: 0,
margin: 0,
padding: 0,
position: 'relative',
// fix flexbox bugs
minHeight: 0,
minWidth: 0
}
};
export default injectSheet(styles)(View);
|
judge/client/src/Components/ProblemForm.js | istamenov/NodeJS_Judge | import React, { Component } from 'react';
import TestForm from './TestForm';
class ProblemForm extends Component {
constructor(){
super();
this.state = {
problemAuthor : "",
problemDescription : "",
problemTitle : "",
problemTests : []
};
}
handleSubmit(e)
{
e.preventDefault();
this.props.submitCallback(this.state.problemAuthor
, this.state.problemDescription
, this.state.problemTests
, this.state.problemTitle)
}
onTestChange(input, output)
{
let newTests = this.state.problemTests;
newTests.push({'input' : input, 'output' : output});
this.setState({'problemTests' : newTests});
}
onAuthorChange(e){
e.preventDefault();
this.setState({
'problemAuthor' : e.target.value
});
}
onContentsChange(e){
e.preventDefault();
this.setState({
'problemDescription' : e.target.value
});
}
onTitleChange(e){
e.preventDefault();
this.setState({
'problemTitle' : e.target.value
});
}
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<label>Your New Problem</label>
<br/>
<label>Author</label>
<input type="text" onChange={this.onAuthorChange.bind(this)}/>
<br/>
<label>Title</label>
<input type="text" onChange={this.onTitleChange.bind(this)}/>
<br/>
<label>Description</label>
<input type="text" onChange={this.onContentsChange.bind(this)}/>
<br/>
<TestForm tests={this.state.problemTests} addTest={this.onTestChange.bind(this)} />
<input type="submit" value="Submit Problem" />
</form>
);
}
}
export default ProblemForm;
|
step6-serviceapi/node_modules/react-router/es6/RouteContext.js | jintoppy/react-training | 'use strict';
import warning from './routerWarning';
import React from 'react';
var object = React.PropTypes.object;
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
var RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext: function getChildContext() {
return {
route: this.props.route
};
},
componentWillMount: function componentWillMount() {
process.env.NODE_ENV !== 'production' ? warning(false, 'The `RouteContext` mixin is deprecated. You can provide `this.props.route` on context with your own `contextTypes`. http://tiny.cc/router-routecontextmixin') : undefined;
}
};
export default RouteContext; |
app/javascript/mastodon/components/display_name.js | kazh98/social.arnip.org | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { autoPlayGif } from 'mastodon/initial_state';
export default class DisplayName extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
others: ImmutablePropTypes.list,
localDomain: PropTypes.string,
};
_updateEmojis () {
const node = this.node;
if (!node || autoPlayGif) {
return;
}
const emojis = node.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
if (emoji.classList.contains('status-emoji')) {
continue;
}
emoji.classList.add('status-emoji');
emoji.addEventListener('mouseenter', this.handleEmojiMouseEnter, false);
emoji.addEventListener('mouseleave', this.handleEmojiMouseLeave, false);
}
}
componentDidMount () {
this._updateEmojis();
}
componentDidUpdate () {
this._updateEmojis();
}
handleEmojiMouseEnter = ({ target }) => {
target.src = target.getAttribute('data-original');
}
handleEmojiMouseLeave = ({ target }) => {
target.src = target.getAttribute('data-static');
}
setRef = (c) => {
this.node = c;
}
render () {
const { others, localDomain } = this.props;
let displayName, suffix, account;
if (others && others.size > 1) {
displayName = others.take(2).map(a => <bdi key={a.get('id')}><strong className='display-name__html' dangerouslySetInnerHTML={{ __html: a.get('display_name_html') }} /></bdi>).reduce((prev, cur) => [prev, ', ', cur]);
if (others.size - 2 > 0) {
suffix = `+${others.size - 2}`;
}
} else {
if (others && others.size > 0) {
account = others.first();
} else {
account = this.props.account;
}
let acct = account.get('acct');
if (acct.indexOf('@') === -1 && localDomain) {
acct = `${acct}@${localDomain}`;
}
displayName = <bdi><strong className='display-name__html' dangerouslySetInnerHTML={{ __html: account.get('display_name_html') }} /></bdi>;
suffix = <span className='display-name__account'>@{acct}</span>;
}
return (
<span className='display-name' ref={this.setRef}>
{displayName} {suffix}
</span>
);
}
}
|
react/examples/Code/Redux_Server_Communication/src/components/App.js | jsperts/workshop_unterlagen | import React from 'react';
function App({
onAddData,
onDeleteData,
data,
}) {
return <div>
<h1>Data</h1>
<div>
<button onClick={onAddData} className="btn btn-primary">Add data</button>
</div>
<ul className="list-group">
{
data.map((d) => (<li key={d.id} className="list-group-item clearfix">
{d.name}
<button className="btn pull-right" onClick={() => onDeleteData(d.id)}>Delete</button>
</li>))
}
</ul>
</div>;
}
export default App;
|
src/components/DynamicForm.js | longyarnz/WelFurnish-E-Commerce | import React, { Component } from 'react';
import UUID from 'uuid';
export default class DynamicForm extends Component {
constructor(props){
super(props);
this.elements = {};
this._getRef = this._getRef.bind(this);
this._onClick = this._onClick.bind(this);
this.state = { restore: "" }
}
_getRef(ref){
if(ref !== null){
if(ref.nodeName === "FORM") { ref.enctype = "multipart/form-data"; ref.method = "post"; }
this.elements[ref.name] = ref;
}
}
componentDidMount() {
if(this.props.onUpdate) this.props.onUpdate.call(this);
}
componentDidUpdate(prevProps, prevState) {
if(this.props.onUpdate) this.props.onUpdate.call(this);
}
_handleInputs(input){
if(!input.type) {
console.error("DynamicForm inputs are not wrapped in an object");
return;
}
const {
name, type='text', placeholder, autoComplete="off", button="", onChange=()=>{}, maxLength="",
spellCheck=false, required=true, row=7, refName, options=[], buttonClick=(e)=>e.preventDefault(), min=0, title="",
className, disabled=false, divClassName, autoFocus=false, multiple=false, pattern="[^~]*"
} = input;
if (name === 'input'){
return(
<div className={divClassName} key={UUID.v4()}>
<input
type={type}
className={divClassName}
ref={this._getRef}
name={refName}
placeholder={placeholder}
required={required}
autoComplete={autoComplete}
autoFocus={autoFocus}
spellCheck={spellCheck}
disabled={disabled}
onClick={this._onClick}
onChange={e=>onChange.call(this, e, type, refName)}
multiple={multiple}
min={min}
pattern={pattern}
maxLength={maxLength}
title={title}
/>
</div>
)
}
else if(name === 'select'){
return(
<div className={divClassName} key={UUID.v4()}>
<select className={className} ref={this._getRef} name={refName} defaultValue={options[0]}>
{
options.map((option, i)=>{
return (
<option key={i} value={option}>
{option}
</option>
)
})
}
</select>
</div>
)
}
else if(name === 'textArea'){
return(
<div className={divClassName} key={UUID.v4()}>
<textarea
ref={this._getRef}
name={refName}
placeholder={placeholder}
required={required}
autoComplete={autoComplete}
spellCheck={spellCheck}
onClick={this._onClick}
rows={row}
className={divClassName}
disabled={disabled}
/>
</div>
)
}
else if(name === 'button'){
return(
<div className={divClassName} key={UUID.v4()}>
<button className={divClassName} onClick={e=>buttonClick.call(this, e)} name={refName} ref={this._getRef}>
{button}
</button>
</div>
)
}
else if(name === 'file'){
return(
<div className={divClassName} key={UUID.v4()}>
<input
ref={this._getRef}
name={refName}
placeholder={placeholder}
required={required}
className={divClassName}
disabled={disabled}
multiple={multiple}
/>
</div>
)
}
}
_onClick(e){
if(e.which === 13) this.props.onSubmit.call(this, e);
}
render() {
return (
<form className={this.props.divClassName} onKeyPress={this._onClick} ref={this._getRef} name={this.props.formName} onSubmit={e=>this.props.onSubmit.call(this, e)}>
{
this.props.formData.map(data => {
return this._handleInputs(data);
})
}
<button className={this.props.divClassName} name={this.props.formName}>{this.props.button}</button>
</form>
);
}
}
|
src/js/components/icons/base/TableAdd.js | kylebyerly-hp/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-table-add`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'table-add');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M8,5 L8,23 M16,5 L16,11 M1,11 L17,11 M1,5 L23,5 M1,17 L11,17 M17,23 L1,23 L1,1 L23,1 L23,17 M17,23 C20.3137085,23 23,20.3137085 23,17 C23,13.6862915 20.3137085,11 17,11 C13.6862915,11 11,13.6862915 11,17 C11,20.3137085 13.6862915,23 17,23 Z M17,14 L17,20 M17,14 L17,20 M14,17 L20,17"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'TableAdd';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/common/ui/Button/Button.stories.js | MadeInHaus/react-redux-webpack-starter | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { text, boolean, number } from '@storybook/addon-knobs';
import { Button } from '@ui';
storiesOf('Global/Button', module)
.add('default', () => (
<Button
onClick={action('Button Clicked')}
disabled={boolean('Disabled', false)}
>
{text('Label', 'Example')} {number('Number', 89)}
</Button>
))
.add('primary', () => (
<Button onClick={action('Button Clicked')} primary>
Example
</Button>
))
.add('Link (href)', () => (
<Button href="http://www.google.com">Google</Button>
))
.add('Link (router)', () => <Button to="/some-route">Router Link</Button>);
|
src/pages/index.js | harrygreen/parlay | import React from 'react';
import { connect } from 'react-redux'
import Nav from '../components/Nav'
import EditionSwitcher from '../components/EditionSwitcher';
import User from '../utils/User'
import LoggedOutModal from '../components/LoggedOutModal';
const App = React.createClass({
getInitialState: function() {
return {
isLoggedIn: User.isLoggedIn(),
};
},
render: function() {
const { dispatch, edition } = this.props
if (!this.state.isLoggedIn) {
document.body.classList.add('js-show-modal')
} else {
// User.getACLs().then(function(data) {
// debugger;
// console.log(data);
// })
}
return (
<div>
{ this.state.isLoggedIn ? null : (<LoggedOutModal /> )}
<h1>Bento ({this.props.edition} edition)</h1>
<EditionSwitcher edition={this.props.edition} dispatch={dispatch} />
<Nav />
{this.props.children}
</div>
);
}
});
export default connect(state => ({
edition: state.edition,
}))(App) |
app/javascript/mastodon/containers/card_container.js | honpya/taketodon | import React from 'react';
import PropTypes from 'prop-types';
import Card from '../features/status/components/card';
import { fromJS } from 'immutable';
export default class CardContainer extends React.PureComponent {
static propTypes = {
locale: PropTypes.string,
card: PropTypes.array.isRequired,
};
render () {
const { card, ...props } = this.props;
return <Card card={fromJS(card)} {...props} />;
}
}
|
frontend/src/WorkflowDetailGraph.js | aclowes/yawn | import React from 'react';
// importing from /dist/ because something in dagre-d3 isn't webpack compatible
import * as dagreD3 from 'dagre-d3/dist/dagre-d3'
import Graph from 'graphlib/lib/graph'
import d3 from 'd3'
export default class WorkflowDetailGraph extends React.Component {
shouldComponentUpdate() {
/* Never re-render */
return false
}
render() {
return <svg/>
}
componentDidMount() {
/* After rendering, draw the graph */
const workflow = this.props.workflow;
const renderer = new dagreD3.render();
const graph = new Graph().setGraph({});
workflow.tasks.forEach(function (task) {
// Add nodes: rx ry is border radius
graph.setNode(task.name, {label: task.name, rx: 5, ry: 5});
// Add lines between nodes
task.upstream.forEach(function (upstreamTask) {
graph.setEdge(upstreamTask, task.name, {})
})
});
const svg = d3.select("svg");
const g = svg.append("g");
renderer(g, graph);
svg.attr('height', graph.graph().height);
svg.attr('width', graph.graph().width);
}
}
|
samples/react/app/utils/injectReducer.js | IntelliSearch/search-client | import React from 'react';
import PropTypes from 'prop-types';
import hoistNonReactStatics from 'hoist-non-react-statics';
import getInjectors from './reducerInjectors';
/**
* Dynamically injects a reducer
*
* @param {string} key A key of the reducer
* @param {function} reducer A reducer that will be injected
*
*/
export default ({ key, reducer }) => WrappedComponent => {
class ReducerInjector extends React.Component {
static WrappedComponent = WrappedComponent;
static contextTypes = {
store: PropTypes.object.isRequired,
};
static displayName = `withReducer(${WrappedComponent.displayName ||
WrappedComponent.name ||
'Component'})`;
componentWillMount() {
const { injectReducer } = this.injectors;
injectReducer(key, reducer);
}
injectors = getInjectors(this.context.store);
render() {
return <WrappedComponent {...this.props} />;
}
}
return hoistNonReactStatics(ReducerInjector, WrappedComponent);
};
|
src/FormControls/Static.js | aparticka/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import InputBase from '../InputBase';
import childrenValueValidation from '../utils/childrenValueInputValidation';
class Static extends InputBase {
getValue() {
const {children, value} = this.props;
return children ? children : value;
}
renderInput() {
return (
<p {...this.props} className={classNames(this.props.className, 'form-control-static')} ref="input" key="input">
{this.getValue()}
</p>
);
}
}
Static.propTypes = {
value: childrenValueValidation,
children: childrenValueValidation
};
export default Static;
|
webapp/app/components/Navbar/index.js | EIP-SAM/SAM-Solution-Server | //
// Navbar
//
import React from 'react';
import { Navbar, Nav, NavItem, Image, Glyphicon, NavDropdown, MenuItem } from 'react-bootstrap';
import { LinkContainer } from 'react-router-bootstrap';
import Logo from 'components/Navbar/logo_sam_solution.png';
import styles from 'components/Navbar/styles.css';
/* eslint-disable react/prefer-stateless-function */
export default class NavbarContainer extends React.Component {
static getNavbarLinkContainer(item, i) {
return (
<LinkContainer key={`navItem-${i}`} to={{ pathname: item.pathname }}>
<NavItem eventKey={i} className={styles.navBarMenuItem}><Glyphicon glyph={item.glyphicon} className={styles.icon} />{item.value}</NavItem>
</LinkContainer>
);
}
getNavbarDropDownMenu(item, i) {
if (item.value !== 'Logout') {
return (
<LinkContainer key={`dropdownItem-${i}`} to={{ pathname: item.pathname }}>
<MenuItem eventKey={`1.${i}`} className={styles.itemDropDown}><Glyphicon glyph={item.glyphicon} className={styles.icon} />{item.value}</MenuItem>
</LinkContainer>
);
}
return (
<LinkContainer onClick={() => this.props.logoutRequest()} key={`dropdownItem-${i}`} to={{ pathname: item.pathname }}>
<MenuItem eventKey={`1.${i}`} className={styles.itemDropDown}><Glyphicon glyph={item.glyphicon} className={styles.icon} />{item.value}</MenuItem>
</LinkContainer>
);
}
render() {
let navItems = [];
const userInfo = this.props.userInfo;
if (userInfo.isAdmin) {
navItems = [
{ pathname: '/homepage', value: 'Homepage', glyphicon: 'dashboard' },
{ pathname: '/users', value: 'Users', glyphicon: 'user' },
{ pathname: '/groups', value: 'Groups', glyphicon: 'tags' },
{ pathname: '/save', value: 'Save', glyphicon: 'floppy-disk' },
{ pathname: '/restore', value: 'Restore', glyphicon: 'repeat' },
{ pathname: '/migration/history', value: 'Migration', glyphicon: 'send' },
{ pathname: '/images', value: 'Images', glyphicon: 'modal-window' },
{ pathname: '/software', value: 'Software', glyphicon: 'cd' },
{ pathname: '/logs', value: 'Logs', glyphicon: 'list' },
{ pathname: '/statistics', value: 'Statistics', glyphicon: 'stats' },
{ pathname: '/notifications', value: 'Notifications', glyphicon: 'envelope' },
];
} else {
navItems = [
{ pathname: '/homepage', value: 'Homepage', glyphicon: 'dashboard' },
{ pathname: `/save/${userInfo.username}/${userInfo.userId}`, value: 'Save', glyphicon: 'floppy-disk' },
{ pathname: `/restore/${userInfo.username}`, value: 'Restore', glyphicon: 'repeat' },
];
}
const dropdownItems = [
{ pathname: `/edit-user/${userInfo.userId}`, value: 'Profile', glyphicon: 'user' },
{ pathname: '/login', value: 'Logout', glyphicon: 'off' },
];
return (
<Navbar inverse fixedTop className={styles.navbarStyle} role="navigation">
<Navbar.Header>
<LinkContainer key={'item-logo'} to={{ pathname: '/homepage' }}>
<NavItem><Image src={Logo} responsive className={styles.navbarLogo} /></NavItem>
</LinkContainer>
<Navbar.Brand>
<LinkContainer key={'item-name'} to={{ pathname: '/homepage' }}>
<NavItem>SAM-Solution</NavItem>
</LinkContainer>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Nav pullRight className={styles.navBarRightButtonBlock}>
<NavDropdown title={userInfo.username} eventKey={1} id="navbar-user-dropdown">
{dropdownItems.map((item, i) =>
this.getNavbarDropDownMenu(item, i)
)}
</NavDropdown>
</Nav>
<Navbar.Collapse>
<Nav className={styles.navBarSideBar}>
{navItems.map((item, i) =>
NavbarContainer.getNavbarLinkContainer(item, i)
)}
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
NavbarContainer.propTypes = {
userInfo: React.PropTypes.shape({
logged: React.PropTypes.bool,
userId: React.PropTypes.number,
username: React.PropTypes.string,
email: React.PropTypes.string,
isAdmin: React.PropTypes.bool,
}),
logoutRequest: React.PropTypes.func,
};
|
src/svg-icons/image/filter-b-and-w.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilterBAndW = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16l-7-8v8H5l7-8V5h7v14z"/>
</SvgIcon>
);
ImageFilterBAndW = pure(ImageFilterBAndW);
ImageFilterBAndW.displayName = 'ImageFilterBAndW';
ImageFilterBAndW.muiName = 'SvgIcon';
export default ImageFilterBAndW;
|
src/modules/Tab/TabPane.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
useKeyOnly,
} from '../../lib'
import Segment from '../../elements/Segment/Segment'
/**
* A tab pane holds the content of a tab.
*/
function TabPane(props) {
const { active, children, className, content, loading } = props
const classes = cx(
useKeyOnly(active, 'active'),
useKeyOnly(loading, 'loading'),
'tab',
className,
)
const rest = getUnhandledProps(TabPane, props)
const ElementType = getElementType(TabPane, props)
const calculatedDefaultProps = {}
if (ElementType === Segment) {
calculatedDefaultProps.attached = 'bottom'
}
return (
<ElementType {...calculatedDefaultProps} {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
TabPane._meta = {
name: 'TabPane',
parent: 'Tab',
type: META.TYPES.MODULE,
}
TabPane.defaultProps = {
as: Segment,
active: true,
}
TabPane.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A tab pane can be active. */
active: PropTypes.bool,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
/** A Tab.Pane can display a loading indicator. */
loading: PropTypes.bool,
}
TabPane.create = createShorthandFactory(TabPane, content => ({ content }))
export default TabPane
|
src/svg-icons/action/language.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLanguage = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2 0 .68.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.16-1.32-.16-2 0-.68.07-1.35.16-2h4.68c.09.65.16 1.32.16 2 0 .68-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2 0-.68-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z"/>
</SvgIcon>
);
ActionLanguage = pure(ActionLanguage);
ActionLanguage.displayName = 'ActionLanguage';
export default ActionLanguage;
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/ImageInclusion.js | HelpfulHuman/helpful-react-scripts | /**
* 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 from 'react';
import tiniestCat from './assets/tiniest-cat.jpg';
export default () =>
<img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" />;
|
src/index.js | City-Bus-Stops/get-route-components | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRedirect } from 'react-router';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux';
import 'leaflet/dist/leaflet.css';
import '../public/css/index.css';
import '../node_modules/semantic-ui-css/semantic.min.css';
import '../public/mapkey-icons/MapkeyIcons.css';
import '../public/mapkey-icons/L.Icon.Mapkey.css';
import RootContainer from './containers/RootContainer/RootContainer';
import UserManagementContainer from './containers/UserManagementContainer/UserManagementContainer';
import Dashboard from './components/Dashboard/Dashboard';
import SearchRouteContainer from './containers/SearchRouteContainer/SearchRouteContainer';
import LoginContainer from './containers/LoginContainer/LoginContainer';
import SignupContainer from './containers/SignupContainer/SignupContainer';
import MapContainer from './containers/MapContainer/MapContainer';
import FavoritesContainer from './containers/FavoritesContainer/FavoritesContainer';
import NotFound from './components/NotFound/NotFound';
import configureStore from './configureStore';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={RootContainer}>
<IndexRedirect to="/dashboard" />
<Route path="dashboard" component={Dashboard} />
<Route path="search-route" component={SearchRouteContainer} />
<Route path="map" component={MapContainer} />
<Route path="favorites" component={FavoritesContainer} />
</Route>
<Route path="/" component={UserManagementContainer}>
<Route path="/login" component={LoginContainer} />
<Route path="/signup" component={SignupContainer} />
</Route>
<Route path="*" component={NotFound} />
</Router>
</Provider>,
document.getElementById('root'),
);
|
src/components/login/LoginForm.js | RanjithNair/FeatureTracker | import React from 'react';
import TextInput from '../common/TextInput';
import {Link, IndexLink} from 'react-router';
const LoginForm = ({user, onSave, onChange, saving}) => {
return (
<div className="test">
<div className="login">
<form>
<h1>Login</h1>
<TextInput
name="email"
placeholder="Username"
required="required"
onChange={onChange}
value={user.email}
/>
<TextInput
name="password"
type="password"
placeholder="password"
onChange={onChange}
value={user.password}
/>
<button
type="submit"
disabled={saving}
onClick={onSave}
className="btn btn-primary btn-block btn-large">{saving ? 'Logining in...' : 'Login'}
</button>
<Link to="/register" activeClassName="active"><span>Not a member? Sign up</span></Link>
</form>
</div>
</div>
);
};
LoginForm.propTypes = {
onSave: React.PropTypes.func.isRequired,
saving: React.PropTypes.bool,
user: React.PropTypes.object.isRequired,
onChange: React.PropTypes.func.isRequired
};
export default LoginForm;
|
information/blendle-frontend-react-source/app/components/login/ResetPassword/index.js | BramscoChill/BlendleParser | import React from 'react';
import PropTypes from 'prop-types';
import BackboneView from 'components/shared/BackboneView';
import Link from 'components/Link';
import { translate } from 'instances/i18n';
import ResetTokenForm from 'views/forms/resettoken';
class ResetPassword extends React.Component {
static propTypes = {
active: PropTypes.bool,
showBack: PropTypes.bool,
onLoginLink: PropTypes.func,
};
static defaultProps() {
return {
active: true,
};
}
componentWillMount() {
this._resetTokenForm = new ResetTokenForm();
this._resetTokenForm.render();
this._resetTokenForm.setDisabled(!this.props.active);
}
componentWillReceiveProps(nextProps) {
if (nextProps.active && !this.props.active) {
this._autofocusTimeout = setTimeout(() => this._resetTokenForm.focus(), 200);
}
}
componentWillUpdate(nextProps) {
this._resetTokenForm.setDisabled(!nextProps.active);
}
componentWillUnmount() {
clearTimeout(this._autofocusTimeout);
}
_renderBack() {
if (this.props.showBack) {
return (
<Link className="lnk-toggle-pane lnk-login" onClick={this.props.onLoginLink}>
{translate('login.dropdown.to_login')}
</Link>
);
}
return null;
}
render() {
return (
<div className="v-reset-password">
<BackboneView view={this._resetTokenForm} />
{this._renderBack()}
</div>
);
}
}
export default ResetPassword;
// WEBPACK FOOTER //
// ./src/js/app/components/login/ResetPassword/index.js |
src/svg-icons/action/open-in-new.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionOpenInNew = (props) => (
<SvgIcon {...props}>
<path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/>
</SvgIcon>
);
ActionOpenInNew = pure(ActionOpenInNew);
ActionOpenInNew.displayName = 'ActionOpenInNew';
ActionOpenInNew.muiName = 'SvgIcon';
export default ActionOpenInNew;
|
js/jqwidgets/demos/react/app/window/keyboardnavigation/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxWindow from '../../../jqwidgets-react/react_jqxwindow.js';
import JqxPanel from '../../../jqwidgets-react/react_jqxpanel.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
class App extends React.Component {
componentDidMount() {
this.refs.window.focus();
this.refs.showWindowButton.on('click', (event) => {
this.refs.window.open();
});
}
render () {
let offset = { left: 40, top: 95 };
return (
<div>
<div style={{fontFamily: 'Verdana', fontSize: '12px', width: '400px', marginLeft: '20px', float: 'left' }}>
<JqxButton ref='showWindowButton' width={100} value='Show' />
<ul>
<li><b>Esc</b> key - closes the window.</li>
<li><b>Up</b> key - moves window up.</li>
<li><b>Ctrl + Up</b> - narrows window in vertical direction.</li>
<li><b>Down</b> key - moves window down.</li>
<li><b>Ctrl + Down</b> - expands window in vertical direction.</li>
<li><b>Left</b> key - moves window left.</li>
<li><b>Ctrl + Left</b> - narrows window in horizontal direction.</li>
<li><b>Right</b> key - moves window down.</li>
<li><b>Ctrl + Right</b> - expands window in horizontal direction.</li>
</ul>
</div>
<JqxWindow ref='window'
position={{ x: offset.left + 50, y: offset.top + 50 }}
width={500} height={400}
minHeight={300} minWidth={300}
resizable={true}
>
<div>
About 30 St Mary Axe
</div>
<div>
<img src="../../images/building_big.jpg" alt="" className="big-image" />
<div>
<h3>30 St Mary Axe</h3>
<p className="important-text">
the Swiss Re Building (colloquially referred to as the Gherkin), is a skyscraper
in London's main financial district, the City of London, completed in December 2003
and opened at the end of May 2004. With 40 floors, the tower is 180 metres (591
ft) tall, and stands on the former site of the Baltic Exchange building, which was
severely damaged on 10 April 1992 by the explosion of a bomb placed by the Provisional
IRA.
</p>
<div className="more-text">
The building is on the former site of the Baltic Exchange building, the headquarters
of a global marketplace for ship sales and shipping information. On 10 April 1992
the Provisional IRA detonated a bomb close to the Exchange, severely damaging the
historic Exchange building and neighbouring structures. The UK government's statutory
adviser on the historic environment, English Heritage, and the City of London governing
body, the City of London Corporation, were keen that any redevelopment must restore
the building's old façade onto St Mary Axe. The Exchange Hall was a celebrated fixture
of the ship trading company.
</div>
</div>
</div>
</JqxWindow>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/pages/demoPage/Register.js | guangqiang-liu/OneM | import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Button from 'react-native-button';
import { Actions } from 'react-native-router-flux';
export default class Register extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Register page</Text>
<Button onPress={()=>Actions.register2()}>Register</Button>
<Button onPress={Actions.home}>Replace screen</Button>
<Button onPress={Actions.pop}>Back</Button>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
})
|
src/routes/login/index.js | jhlav/mpn-web-app | /**
* 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 Layout from '../../components/Layout';
import Login from './Login';
const title = 'Log In';
function action() {
return {
chunks: ['login'],
title,
component: (
<Layout>
<Login title={title} />
</Layout>
),
};
}
export default action;
|
docs/src/components/Demo/EditorWithMentionHashtag/index.js | michalko/draft-wyswig | /* @flow */
import React from 'react';
import { Editor } from 'react-draft-wysiwyg';
import Codemirror from 'react-codemirror';
import sampleEditorContent from '../../../util/sampleEditorContent';
const EditorWithMentionHashtag = () => (
<div className="demo-section">
<h3>8. Editor with mentions and hashtag. Type @ for mentions and # for hashtag.</h3>
<div className="demo-section-wrapper">
<div className="demo-editor-wrapper">
<Editor
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
mention={{
separator: ' ',
trigger: '@',
suggestions: [
{ text: 'APPLE', value: 'apple', url: 'apple' },
{ text: 'BANANA', value: 'banana', url: 'banana' },
{ text: 'CHERRY', value: 'cherry', url: 'cherry' },
{ text: 'DURIAN', value: 'durian', url: 'durian' },
{ text: 'EGGFRUIT', value: 'eggfruit', url: 'eggfruit' },
{ text: 'FIG', value: 'fig', url: 'fig' },
{ text: 'GRAPEFRUIT', value: 'grapefruit', url: 'grapefruit' },
{ text: 'HONEYDEW', value: 'honeydew', url: 'honeydew' },
],
}}
hashtag={{}}
/>
</div>
<Codemirror
value={
'import React from \'react\';\n' +
'import { Editor } from \'react-draft-wysiwyg\';\n' +
'\n\n' +
'const EditorWithMentionHashtag = () => (\n' +
' <Editor\n' +
' wrapperClassName="demo-wrapper"\n' +
' editorClassName="demo-editor"\n' +
' mention={{\n' +
' separator: \' \',\n' +
' trigger: \'@\',\n' +
' suggestions: [\n' +
' { text: \'APPLE\', value: \'apple\', url: \'apple\' },\n' +
' { text: \'BANANA\', value: \'banana\', url: \'banana\' },\n' +
' { text: \'CHERRY\', value: \'cherry\', url: \'cherry\' },\n' +
' { text: \'DURIAN\', value: \'durian\', url: \'durian\' },\n' +
' { text: \'EGGFRUIT\', value: \'eggfruit\', url: \'eggfruit\' },\n' +
' { text: \'FIG\', value: \'fig\', url: \'fig\' },\n' +
' { text: \'GRAPEFRUIT\', value: \'grapefruit\', url: \'grapefruit\' },\n' +
' { text: \'HONEYDEW\', value: \'honeydew\', url: \'honeydew\' },\n' +
' ],\n' +
' }}\n' +
' hashtag={{}}\n' +
' />\n' +
')'
}
options={{
lineNumbers: true,
mode: 'jsx',
readOnly: true,
}}
/>
</div>
</div>
);
export default EditorWithMentionHashtag;
|
packages/@lyra/components/src/progress/story.js | VegaPublish/vega-studio | /* eslint-disable react/no-multi-comp */
import React from 'react'
import ProgressBar from 'part:@lyra/components/progress/bar'
import ProgressCircle from 'part:@lyra/components/progress/circle'
import {
withKnobs,
number,
boolean,
text
} from 'part:@lyra/storybook/addons/knobs'
import {storiesOf} from 'part:@lyra/storybook'
import Lyra from 'part:@lyra/storybook/addons/lyra'
storiesOf('Progress')
.addDecorator(withKnobs)
.add('Progress bar', () => (
<Lyra part="part:@lyra/components/progress/bar" propTables={[ProgressBar]}>
<ProgressBar
percent={number('percentage (prop)', 10, {
range: true,
min: 0,
max: 100,
step: 1
})}
showPercent={boolean('showPercent (prop)', false)}
text={text('text (prop)', 'Downloaded 5.1 of 8.2Mb')}
/>
</Lyra>
))
.add('Progress circle', () => (
<Lyra
part="part:@lyra/components/progress/circle"
propTables={[ProgressCircle]}
>
<ProgressCircle
percent={number('percent (prop)', 10, {
range: true,
min: 0,
max: 100,
step: 1
})}
showPercent={boolean('showPercent (prop)', true)}
text={text('text (prop)', 'Uploaded')}
/>
</Lyra>
))
|
app/jsx/grading/GradingPeriodSet.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import $ from 'jquery'
import _ from 'lodash'
import {Button} from '@instructure/ui-buttons'
import axios from 'axios'
import I18n from 'i18n!GradingPeriodSet'
import GradingPeriod from './AccountGradingPeriod'
import GradingPeriodForm from './GradingPeriodForm'
import gradingPeriodsApi from 'compiled/api/gradingPeriodsApi'
import 'jquery.instructure_misc_helpers'
const sortPeriods = function(periods) {
return _.sortBy(periods, 'startDate')
}
const anyPeriodsOverlap = function(periods) {
if (_.isEmpty(periods)) {
return false
}
const firstPeriod = _.head(periods)
const otherPeriods = _.tail(periods)
const overlapping = _.some(
otherPeriods,
otherPeriod =>
otherPeriod.startDate < firstPeriod.endDate && firstPeriod.startDate < otherPeriod.endDate
)
return overlapping || anyPeriodsOverlap(otherPeriods)
}
const isValidDate = function(date) {
return Object.prototype.toString.call(date) === '[object Date]' && !_.isNaN(date.getTime())
}
const validatePeriods = function(periods, weighted) {
if (_.some(periods, period => !(period.title || '').trim())) {
return [I18n.t('All grading periods must have a title')]
}
if (weighted && _.some(periods, period => _.isNaN(period.weight) || period.weight < 0)) {
return [I18n.t('All weights must be greater than or equal to 0')]
}
const validDates = _.every(
periods,
period =>
isValidDate(period.startDate) && isValidDate(period.endDate) && isValidDate(period.closeDate)
)
if (!validDates) {
return [I18n.t('All dates fields must be present and formatted correctly')]
}
const orderedStartAndEndDates = _.every(periods, period => period.startDate < period.endDate)
if (!orderedStartAndEndDates) {
return [I18n.t('All start dates must be before the end date')]
}
const orderedEndAndCloseDates = _.every(periods, period => period.endDate <= period.closeDate)
if (!orderedEndAndCloseDates) {
return [I18n.t('All close dates must be on or after the end date')]
}
if (anyPeriodsOverlap(periods)) {
return [I18n.t('Grading periods must not overlap')]
}
}
const isEditingPeriod = function(state) {
return !!state.editPeriod.id
}
const isActionsDisabled = function(state, props) {
return !!(props.actionsDisabled || isEditingPeriod(state) || state.newPeriod.period)
}
const getShowGradingPeriodRef = function(period) {
return `show-grading-period-${period.id}`
}
const {shape, string, array, bool, func} = PropTypes
export default class GradingPeriodSet extends React.Component {
static propTypes = {
gradingPeriods: array.isRequired,
terms: array.isRequired,
readOnly: bool.isRequired,
expanded: bool,
actionsDisabled: bool,
onEdit: func.isRequired,
onDelete: func.isRequired,
onPeriodsChange: func.isRequired,
onToggleBody: func.isRequired,
set: shape({
id: string.isRequired,
title: string.isRequired,
weighted: bool,
displayTotalsForAllGradingPeriods: bool.isRequired
}).isRequired,
urls: shape({
batchUpdateURL: string.isRequired,
deleteGradingPeriodURL: string.isRequired,
gradingPeriodSetsURL: string.isRequired
}).isRequired,
permissions: shape({
read: bool.isRequired,
create: bool.isRequired,
update: bool.isRequired,
delete: bool.isRequired
}).isRequired
}
constructor(props) {
super(props)
this.state = {
title: this.props.set.title,
weighted: !!this.props.set.weighted,
displayTotalsForAllGradingPeriods: this.props.set.displayTotalsForAllGradingPeriods,
gradingPeriods: sortPeriods(this.props.gradingPeriods),
newPeriod: {
period: null,
saving: false
},
editPeriod: {
id: null,
saving: false
}
}
this._refs = {}
}
componentDidUpdate(prevProps, prevState) {
if (prevState.newPeriod.period && !this.state.newPeriod.period) {
this._refs.addPeriodButton.focus()
} else if (isEditingPeriod(prevState) && !isEditingPeriod(this.state)) {
const period = {id: prevState.editPeriod.id}
this._refs[getShowGradingPeriodRef(period)]._refs.editButton.focus()
}
}
toggleSetBody = () => {
if (!isEditingPeriod(this.state)) {
this.props.onToggleBody()
}
}
promptDeleteSet = event => {
event.stopPropagation()
const confirmMessage = I18n.t('Are you sure you want to delete this grading period set?')
if (!window.confirm(confirmMessage)) return null
const url = `${this.props.urls.gradingPeriodSetsURL}/${this.props.set.id}`
axios
.delete(url)
.then(() => {
$.flashMessage(I18n.t('The grading period set was deleted'))
this.props.onDelete(this.props.set.id)
})
.catch(() => {
$.flashError(I18n.t('An error occured while deleting the grading period set'))
})
}
setTerms = () => _.filter(this.props.terms, {gradingPeriodGroupId: this.props.set.id})
termNames = () => {
const names = _.map(this.setTerms(), 'displayName')
if (names.length > 0) {
return I18n.t('Terms: ') + names.join(', ')
} else {
return I18n.t('No Associated Terms')
}
}
editSet = e => {
e.stopPropagation()
this.props.onEdit(this.props.set)
}
changePeriods = periods => {
const sortedPeriods = sortPeriods(periods)
this.setState({gradingPeriods: sortedPeriods})
this.props.onPeriodsChange(this.props.set.id, sortedPeriods)
}
removeGradingPeriod = idToRemove => {
this.setState(oldState => {
const gradingPeriods = _.reject(oldState.gradingPeriods, period => period.id === idToRemove)
return {gradingPeriods}
})
}
showNewPeriodForm = () => {
this.setNewPeriod({period: {}})
}
saveNewPeriod = period => {
const periods = this.state.gradingPeriods.concat([period])
const validations = validatePeriods(periods, this.state.weighted)
if (_.isEmpty(validations)) {
this.setNewPeriod({saving: true})
gradingPeriodsApi
.batchUpdate(this.props.set.id, periods)
.then(pds => {
$.flashMessage(I18n.t('All changes were saved'))
this.removeNewPeriodForm()
this.changePeriods(pds)
})
.catch(_err => {
$.flashError(I18n.t('There was a problem saving the grading period'))
this.setNewPeriod({saving: false})
})
} else {
_.each(validations, message => {
$.flashError(message)
})
}
}
removeNewPeriodForm = () => {
this.setNewPeriod({saving: false, period: null})
}
setNewPeriod = attr => {
this.setState(oldState => {
const newPeriod = $.extend(true, {}, oldState.newPeriod, attr)
return {newPeriod}
})
}
editPeriod = period => {
this.setEditPeriod({id: period.id, saving: false})
}
updatePeriod = period => {
const periods = _.reject(
this.state.gradingPeriods,
_period => period.id === _period.id
).concat([period])
const validations = validatePeriods(periods, this.state.weighted)
if (_.isEmpty(validations)) {
this.setEditPeriod({saving: true})
gradingPeriodsApi
.batchUpdate(this.props.set.id, periods)
.then(pds => {
$.flashMessage(I18n.t('All changes were saved'))
this.setEditPeriod({id: null, saving: false})
this.changePeriods(pds)
})
.catch(_err => {
$.flashError(I18n.t('There was a problem saving the grading period'))
this.setNewPeriod({saving: false})
})
} else {
_.each(validations, message => {
$.flashError(message)
})
}
}
cancelEditPeriod = () => {
this.setEditPeriod({id: null, saving: false})
}
setEditPeriod = attr => {
this.setState(oldState => {
const editPeriod = $.extend(true, {}, oldState.editPeriod, attr)
return {editPeriod}
})
}
renderEditButton = () => {
if (!this.props.readOnly && this.props.permissions.update) {
const disabled = isActionsDisabled(this.state, this.props)
return (
<Button
elementRef={ref => {
this._refs.editButton = ref
}}
variant="icon"
disabled={disabled}
onClick={this.editSet}
title={I18n.t('Edit %{title}', {title: this.props.set.title})}
>
<span className="screenreader-only">
{I18n.t('Edit %{title}', {title: this.props.set.title})}
</span>
<i className="icon-edit" />
</Button>
)
}
}
renderDeleteButton = () => {
if (!this.props.readOnly && this.props.permissions.delete) {
const disabled = isActionsDisabled(this.state, this.props)
return (
<Button
elementRef={ref => {
this._refs.deleteButton = ref
}}
variant="icon"
disabled={disabled}
onClick={this.promptDeleteSet}
title={I18n.t('Delete %{title}', {title: this.props.set.title})}
>
<span className="screenreader-only">
{I18n.t('Delete %{title}', {title: this.props.set.title})}
</span>
<i className="icon-trash" />
</Button>
)
}
}
renderEditAndDeleteButtons = () => (
<div className="ItemGroup__header__admin">
{this.renderEditButton()}
{this.renderDeleteButton()}
</div>
)
renderSetBody = () => {
if (!this.props.expanded) return null
return (
<div
ref={ref => {
this._refs.setBody = ref
}}
className="ig-body"
>
<div
className="GradingPeriodList"
ref={ref => {
this._refs.gradingPeriodList = ref
}}
>
{this.renderGradingPeriods()}
</div>
{this.renderNewPeriod()}
</div>
)
}
renderGradingPeriods = () => {
const actionsDisabled = isActionsDisabled(this.state, this.props)
return _.map(this.state.gradingPeriods, period => {
if (period.id === this.state.editPeriod.id) {
return (
<div
key={`edit-grading-period-${period.id}`}
className="GradingPeriodList__period--editing pad-box"
>
<GradingPeriodForm
ref={ref => {
this._refs.editPeriodForm = ref
}}
period={period}
weighted={this.state.weighted}
disabled={this.state.editPeriod.saving}
onSave={this.updatePeriod}
onCancel={this.cancelEditPeriod}
/>
</div>
)
} else {
return (
<GradingPeriod
key={`show-grading-period-${period.id}`}
ref={ref => {
this._refs[getShowGradingPeriodRef(period)] = ref
}}
period={period}
weighted={this.state.weighted}
actionsDisabled={actionsDisabled}
onEdit={this.editPeriod}
readOnly={this.props.readOnly}
onDelete={this.removeGradingPeriod}
deleteGradingPeriodURL={this.props.urls.deleteGradingPeriodURL}
permissions={this.props.permissions}
/>
)
}
})
}
renderNewPeriod = () => {
if (this.props.permissions.create && !this.props.readOnly) {
if (this.state.newPeriod.period) {
return this.renderNewPeriodForm()
} else {
return this.renderNewPeriodButton()
}
}
}
renderNewPeriodButton = () => {
const disabled = isActionsDisabled(this.state, this.props)
return (
<div className="GradingPeriodList__new-period center-xs border-rbl border-round-b">
<Button
variant="link"
elementRef={ref => {
this._refs.addPeriodButton = ref
}}
disabled={disabled}
aria-label={I18n.t('Add Grading Period')}
onClick={this.showNewPeriodForm}
>
<i className="icon-plus GradingPeriodList__new-period__add-icon" />
{I18n.t('Grading Period')}
</Button>
</div>
)
}
renderNewPeriodForm = () => (
<div className="GradingPeriodList__new-period--editing border border-rbl border-round-b pad-box">
<GradingPeriodForm
key="new-grading-period"
ref={ref => {
this._refs.newPeriodForm = ref
}}
weighted={this.state.weighted}
disabled={this.state.newPeriod.saving}
onSave={this.saveNewPeriod}
onCancel={this.removeNewPeriodForm}
/>
</div>
)
render() {
const setStateSuffix = this.props.expanded ? 'expanded' : 'collapsed'
const arrow = this.props.expanded ? 'down' : 'right'
return (
<div className={`GradingPeriodSet--${setStateSuffix}`}>
<div
className="ItemGroup__header"
ref={ref => {
this._refs.toggleSetBody = ref
}}
onClick={this.toggleSetBody}
>
<div>
<div className="ItemGroup__header__title">
<button
className="Button Button--icon-action GradingPeriodSet__toggle"
aria-expanded={this.props.expanded}
aria-label={I18n.t('Toggle %{title} grading period visibility', {
title: this.props.set.title
})}
>
<i className={`icon-mini-arrow-${arrow}`} />
</button>
<h2
ref={ref => {
this._refs.title = ref
}}
className="GradingPeriodSet__title"
>
{this.props.set.title}
</h2>
</div>
{this.renderEditAndDeleteButtons()}
</div>
<div className="EnrollmentTerms__list">{this.termNames()}</div>
</div>
{this.renderSetBody()}
</div>
)
}
}
|
bro/index.js | sullenor/reversi | 'use strict';
import App from 'app/app.jsx';
import React from 'react';
React.render(<App />, document.body);
|
src/routes/Counter/components/Counter.js | markkong318/Girlip | import React from 'react'
import PropTypes from 'prop-types'
export const Counter = ({ counter, increment, doubleAsync }) => (
<div style={{ margin: '0 auto' }} >
<h2>Counter: {counter}</h2>
<button className='btn btn-primary' onClick={increment}>
Increment
</button>
{' '}
<button className='btn btn-secondary' onClick={doubleAsync}>
Double (Async)
</button>
</div>
)
Counter.propTypes = {
counter: PropTypes.number.isRequired,
increment: PropTypes.func.isRequired,
doubleAsync: PropTypes.func.isRequired,
}
export default Counter
|
asteroids-scoreboard/src/ScoreBoard.js | lachok/asteroids | import React from 'react'
import { connect } from 'react-redux'
import _ from 'lodash'
export class ScoreBoard extends React.Component {
render() {
const renderStat = (name, value, description) => {
return <div>
<h3>{name}</h3>
<h2>{value}</h2>
<h4>{description}</h4>
</div>
}
return (
<div className="container">
<div className="row">
<div className="col-sm-6">
<div className="row">
<div className="col-sm-6">
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">Most Accurate</h3>
</div>
<div className="panel-body">
{this.props.mostAccurate && renderStat(
this.props.mostAccurate.name,
this.props.mostAccurate.accuracy.toFixed(1) + '%'
)
}
</div>
</div>
</div>
<div className="col-sm-6">
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">Least Accurate</h3>
</div>
<div className="panel-body">
{this.props.leastAccurate && renderStat(
this.props.leastAccurate.name,
this.props.leastAccurate.accuracy.toFixed(1) + '%'
)
}
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-6">
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">Most treacherous</h3>
</div>
<div className="panel-body">
{this.props.mostTreacherous && renderStat(
this.props.mostTreacherous.name,
this.props.mostTreacherous.killedFriend,
'friendly kills'
)
}
</div>
</div>
</div>
<div className="col-sm-6">
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">Rock hunter</h3>
</div>
<div className="panel-body">
{this.props.rockHunter && renderStat(
this.props.rockHunter.name,
this.props.rockHunter.shotAsteroid,
'rocks blown up'
)
}
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-6">
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">Highest kills</h3>
</div>
<div className="panel-body">
{this.props.highestKills && renderStat(
this.props.highestKills.name,
this.props.highestKills.shotAsteroid,
'enemies and rocks blown up'
)
}
</div>
</div>
</div>
<div className="col-sm-6">
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">Survivor</h3>
</div>
<div className="panel-body">
{this.props.survivor && renderStat(
this.props.survivor.name,
this.props.survivor.died,
'deaths'
)
}
</div>
</div>
</div>
</div>
</div>
<div className="col-sm-6">
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">High score</h3>
</div>
<div className="panel-body">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Accuracy</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{this.props.highScore.map((player) => (
<tr key={player.name}>
<td>{player.name}</td>
<td>{player.accuracy.toFixed(1)}%</td>
<td>{player.score}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</div>
{JSON.stringify(this.props.highScore)}
</div>
)
}
}
// {"ECU":{"score":25,"fired":86,"Friend":26,"shotAsteroid":5,"hitByAsteroid":1},"OPW":{"score":20,"died":6,"Friend":3,"fired":69,"shotAsteroid":4},"NCH":{"score":10,"died":13,"fired":18,"hitByAsteroid":2,"Friend":3,"shotAsteroid":2},"GTV":{"score":15,"fired":88,"Friend":2,"shotAsteroid":3,"died":2},"UXL":{"score":5,"fired":48,"died":14,"Friend":1,"shotAsteroid":1,"hitByAsteroid":1}}
const getAccuracy = (player) => {
return ((player.killedEnemy || 0) + (player.shotAsteroid || 0)) / (player.fired || 1)
}
const mapStateToProps = (state) => {
const highScore = _.map(state.score, (value, prop) => {
return { ...value, name: prop, accuracy: getAccuracy(value)*100 }
}).sort((a, b) => b.score - a.score)
return {
highScore: highScore,
mostAccurate: _.maxBy(highScore, function(o){return o.accuracy}),
leastAccurate: _.minBy(highScore, function(o){return o.accuracy}),
mostTreacherous: _.maxBy(highScore, function(o){return o.killedFriend}),
rockHunter: _.maxBy(highScore, function(o){return o.shotAsteroid}),
highestKills: _.maxBy(highScore, function(o){return o.shotAsteroid + o.killedEnemy}),
survivor: _.minBy(highScore, function(o){return o.died}),
score: state.score
}
}
export default connect(
mapStateToProps
)(ScoreBoard) |
src/svg-icons/communication/portable-wifi-off.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationPortableWifiOff = (props) => (
<SvgIcon {...props}>
<path d="M17.56 14.24c.28-.69.44-1.45.44-2.24 0-3.31-2.69-6-6-6-.79 0-1.55.16-2.24.44l1.62 1.62c.2-.03.41-.06.62-.06 2.21 0 4 1.79 4 4 0 .21-.02.42-.05.63l1.61 1.61zM12 4c4.42 0 8 3.58 8 8 0 1.35-.35 2.62-.95 3.74l1.47 1.47C21.46 15.69 22 13.91 22 12c0-5.52-4.48-10-10-10-1.91 0-3.69.55-5.21 1.47l1.46 1.46C9.37 4.34 10.65 4 12 4zM3.27 2.5L2 3.77l2.1 2.1C2.79 7.57 2 9.69 2 12c0 3.7 2.01 6.92 4.99 8.65l1-1.73C5.61 17.53 4 14.96 4 12c0-1.76.57-3.38 1.53-4.69l1.43 1.44C6.36 9.68 6 10.8 6 12c0 2.22 1.21 4.15 3 5.19l1-1.74c-1.19-.7-2-1.97-2-3.45 0-.65.17-1.25.44-1.79l1.58 1.58L10 12c0 1.1.9 2 2 2l.21-.02.01.01 7.51 7.51L21 20.23 4.27 3.5l-1-1z"/>
</SvgIcon>
);
CommunicationPortableWifiOff = pure(CommunicationPortableWifiOff);
CommunicationPortableWifiOff.displayName = 'CommunicationPortableWifiOff';
CommunicationPortableWifiOff.muiName = 'SvgIcon';
export default CommunicationPortableWifiOff;
|
components/Layout/Navigation.js | knaufk/ultidate-frontend | /**
* 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';
import Link from '../Link';
class Navigation extends React.Component {
componentDidMount() {
window.componentHandler.upgradeElement(this.root);
}
componentWillUnmount() {
window.componentHandler.downgradeElements(this.root);
}
render() {
return (
<nav className="mdl-navigation" ref={node => (this.root = node)}>
<Link className="mdl-navigation__link" to="/">Home</Link>
<Link className="mdl-navigation__link" to="/about">About</Link>
</nav>
);
}
}
export default Navigation;
|
test/helpers/shallowRenderHelper.js | felinewong/PhotoGallery | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
src/svg-icons/editor/border-vertical.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderVertical = (props) => (
<SvgIcon {...props}>
<path d="M3 9h2V7H3v2zm0-4h2V3H3v2zm4 16h2v-2H7v2zm0-8h2v-2H7v2zm-4 0h2v-2H3v2zm0 8h2v-2H3v2zm0-4h2v-2H3v2zM7 5h2V3H7v2zm12 12h2v-2h-2v2zm-8 4h2V3h-2v18zm8 0h2v-2h-2v2zm0-8h2v-2h-2v2zm0-10v2h2V3h-2zm0 6h2V7h-2v2zm-4-4h2V3h-2v2zm0 16h2v-2h-2v2zm0-8h2v-2h-2v2z"/>
</SvgIcon>
);
EditorBorderVertical = pure(EditorBorderVertical);
EditorBorderVertical.displayName = 'EditorBorderVertical';
EditorBorderVertical.muiName = 'SvgIcon';
export default EditorBorderVertical;
|
geonode/contrib/monitoring/frontend/src/components/cels/alert/index.js | ingenieroariel/geonode | import React from 'react';
import PropTypes from 'prop-types';
import HoverPaper from '../../atoms/hover-paper';
import styles from './styles';
class Alert extends React.Component {
static propTypes = {
alert: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
this.state = {
detail: false,
};
this.handleClick = () => {
this.setState({ detail: !this.state.detail });
};
}
render() {
const { alert } = this.props;
const visibilityStyle = this.state.detail
? styles.shownDetail
: styles.hiddenDetail;
const style = alert.severity === 'error'
? { ...styles.short, color: '#d12b2b' }
: styles.short;
return (
<HoverPaper style={styles.content} onClick={this.handleClick}>
<div style={style}>
{alert.message}
</div>
{alert.spotted_at.replace(/T/, ' ')}
<div style={visibilityStyle}>
{alert.description}
</div>
</HoverPaper>
);
}
}
export default Alert;
|
assets/jqwidgets/demos/react/app/editor/toolsvisibility/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxEditor from '../../../jqwidgets-react/react_jqxeditor.js';
class App extends React.Component {
render() {
return (
<JqxEditor width={800} height={400} tools={'bold italic underline | left center right'}>
<b>jqxEditor</b> is a HTML text editor designed to simplify web content creation. You can use it as a replacement of your Textarea or you can create it from a DIV element.
<br />
<br />
Features include:
<br />
<ul>
<li>Text formatting</li>
<li>Text alignment</li>
<li>Hyperlink dialog</li>
<li>Image dialog</li>
<li>Bulleted list</li>
<li>Numbered list</li>
</ul>
</JqxEditor>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/index.js | yihan940211/WTFSIGTP | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
|
code-samples/small-is-beautiful.js | vimto/wdcnz-2015-react-tips-and-tricks | import React from 'react';
export default React.createClass({
displayName: 'ProjectSettings',
getInitialState() {
return { open: false };
},
renameProject(event) {
// Code to rename Project...
},
archiveProject(event) {
// Code to archive Project...
},
openDropdown(event) {
event.preventDefault();
this.setState({ open: true });
},
renderItems() {
return (
<ul className="dropdown-items">
<li><a onClick={ this.renameProject }>Rename</a></li>
<li><a onClick={ this.archiveProject }>Archive</a></li>
</ul>
);
},
renderOpen() {
return (
<div className="hub-project-settings open">
<div className="dropdown">
{ this.renderItems() }
</div>
</div>
);
},
renderClosed() {
return (
<div className="hub-project-settings" onClick={ this.openDropdown } title="Project settings" />
);
},
render() {
if (this.state.open) {
{ this.renderOpen() }
} else {
{ this.renderClosed() }
}
}
});
|
node_modules/react-bootstrap/es/ModalHeader.js | okristian1/react-info | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
// TODO: `aria-label` should be `closeLabel`.
var propTypes = {
/**
* The 'aria-label' attribute provides an accessible label for the close
* button. It is used for Assistive Technology when the label text is not
* readable.
*/
'aria-label': React.PropTypes.string,
/**
* Specify whether the Component should contain a close button
*/
closeButton: React.PropTypes.bool,
/**
* A Callback fired when the close button is clicked. If used directly inside
* a Modal component, the onHide will automatically be propagated up to the
* parent Modal `onHide`.
*/
onHide: React.PropTypes.func
};
var defaultProps = {
'aria-label': 'Close',
closeButton: false
};
var contextTypes = {
$bs_modal: React.PropTypes.shape({
onHide: React.PropTypes.func
})
};
var ModalHeader = function (_React$Component) {
_inherits(ModalHeader, _React$Component);
function ModalHeader() {
_classCallCheck(this, ModalHeader);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalHeader.prototype.render = function render() {
var _props = this.props,
label = _props['aria-label'],
closeButton = _props.closeButton,
onHide = _props.onHide,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['aria-label', 'closeButton', 'onHide', 'className', 'children']);
var modal = this.context.$bs_modal;
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(
'div',
_extends({}, elementProps, {
className: classNames(className, classes)
}),
closeButton && React.createElement(
'button',
{
type: 'button',
className: 'close',
'aria-label': label,
onClick: createChainedFunction(modal.onHide, onHide)
},
React.createElement(
'span',
{ 'aria-hidden': 'true' },
'\xD7'
)
),
children
);
};
return ModalHeader;
}(React.Component);
ModalHeader.propTypes = propTypes;
ModalHeader.defaultProps = defaultProps;
ModalHeader.contextTypes = contextTypes;
export default bsClass('modal-header', ModalHeader); |
source/patterns/00-atoms/forms/text-field/docs/text-field.example.js | apparena/patterns | import React from 'react';
// import {TextField} from "apparena-patterns-react";
export default function TextFieldExample() {
return (
<div/>
);
} |
modules/dreamview/frontend/src/components/Dreamview.js | ycool/apollo | import React from 'react';
import { inject, observer } from 'mobx-react';
import SplitPane from 'react-split-pane';
import Header from 'components/Header';
import MainView from 'components/Layouts/MainView';
import ToolView from 'components/Layouts/ToolView';
import MonitorPanel from 'components/Layouts/MonitorPanel';
import SideBar from 'components/SideBar';
import HOTKEYS_CONFIG from 'store/config/hotkeys.yml';
import WS, { MAP_WS, POINT_CLOUD_WS, CAMERA_WS } from 'store/websocket';
@inject('store') @observer
export default class Dreamview extends React.Component {
constructor(props) {
super(props);
this.handleDrag = this.handleDrag.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.updateDimension = this.props.store.dimension.update.bind(this.props.store.dimension);
}
handleDrag(masterViewWidth) {
const { options, dimension } = this.props.store;
if (options.showMonitor) {
dimension.updateMonitorWidth(
Math.min(
Math.max(window.innerWidth - masterViewWidth, 0),
window.innerWidth,
),
);
}
}
handleKeyPress(event) {
const { options, enableHMIButtonsOnly, hmi } = this.props.store;
const optionName = HOTKEYS_CONFIG[event.key];
if (!optionName || options.showDataRecorder
|| options.showDefaultRoutingInput || options.showCycleNumberInput
|| options.showFuelClient) {
return;
}
event.preventDefault();
if (optionName === 'cameraAngle') {
options.rotateCameraAngle();
} else if (
!options.isSideBarButtonDisabled(optionName, enableHMIButtonsOnly, hmi.inNavigationMode)
) {
this.props.store.handleOptionToggle(optionName);
}
}
componentWillMount() {
this.props.store.dimension.initialize();
}
componentDidMount() {
WS.initialize();
MAP_WS.initialize();
POINT_CLOUD_WS.initialize();
CAMERA_WS.initialize();
window.addEventListener('resize', this.updateDimension, false);
window.addEventListener('keypress', this.handleKeyPress, false);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimension, false);
window.removeEventListener('keypress', this.handleKeyPress, false);
}
render() {
const { dimension, options, hmi } = this.props.store;
return (
<div>
<Header />
<div className="pane-container">
<SplitPane
split="vertical"
size={dimension.pane.width}
onChange={this.handleDrag}
allowResize={options.showMonitor}
>
<div className="left-pane">
<SideBar />
<div className="dreamview-body">
<MainView />
<ToolView />
</div>
</div>
<MonitorPanel
hmi={hmi}
viewName={options.monitorName}
showVideo={options.showVideo}
/>
</SplitPane>
</div>
</div>
);
}
}
|
components/PokeListView.js | geremih/PogoMap | import React from 'react';
import {
Text,
View,
Image,
StyleSheet,
} from 'react-native';
import {
MKCheckbox,
} from 'react-native-material-kit';
const styles = StyleSheet.create({
container: {
height: 64,
flexDirection: 'row',
alignItems: 'center',
},
icon: {
width: 50,
height: 50,
paddingHorizontal: 15,
},
text: {
flex: 1,
fontSize: 16,
},
});
export default function PokeListView({ pokemon, blacklist, onChoose}) {
return (
<View
style={styles.container}
>
<MKCheckbox
/>
<Text
style={styles.text}
>
{pokemon.Name}
</Text>
<Image
style={styles.icon}
source={{ uri: `poke_${parseInt(pokemon.Number)}` }}
/>
</View>
);
}
|
demo13/src/app.js | toyluck/ReactDemo | import React from 'react';
export default class App extends React.Component{
constructor(props) {
super(props);
this.render = this.render.bind(this);
this.state = {
items: this.props.items,
disabled: true
};
}
componentDidMount() {
this.setState({
disabled: false
})
}
handleClick() {
this.setState({
items: this.state.items.concat('Item ' + this.state.items.length)
})
}
render() {
return (
<div>
<button onClick={this.handleClick.bind(this)} disabled={this.state.disabled}>Add Item</button>
<ul>
{
this.state.items.map(function(item) {
return <li>{item}</li>
})
}
</ul>
</div>
)
}
};
|
src/dndBattle/Dnd.js | link1900/linkin-games | import React from 'react';
export default class Dnd extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="top-margin aligner">
<div className="aligner-item">DND 5e</div>
</div>
);
}
}
|
code/workspaces/web-app/src/components/common/buttons/DangerButton.js | NERC-CEH/datalab | import React from 'react';
import Button from '@material-ui/core/Button';
import { withStyles } from '@material-ui/core';
const style = theme => ({
button: {
borderColor: theme.palette.dangerColor,
color: theme.palette.dangerColor,
'&:hover': {
backgroundColor: theme.palette.dangerBackgroundColorLight,
color: theme.typography.dangerBackgroundColor,
},
},
});
const DangerButton = ({ classes, children, variant, color, ...rest }) => (
<Button
className={classes.button}
variant="outlined"
{...rest}
>
{children}
</Button>
);
export default withStyles(style)(DangerButton);
|
src/routes/Welcome/Welcome.js | rlesniak/tind3r.com | // @flow
import React, { Component } from 'react';
import { Button, Classes } from '@blueprintjs/core';
import DocumentTitle from 'react-document-title';
import Login from 'components/Login';
import './Welcome.scss';
type PropsType = {
isInstalled: boolean,
isOutdated: boolean,
handleConnect: () => void,
}
export default class Welcome extends Component {
state = {
isButtonVisible: true,
}
props: PropsType;
handleInstall = () => {
this.setState({ isButtonVisible: false });
window.open('/assets/tind3r.zip');
}
renderButton() {
const isChrome = window.chrome;
if (isChrome) {
if (this.props.isInstalled) {
if (this.props.isOutdated) {
return (
<div>
<h3 className={Classes.HEADING}>...but you need update firstly, click below to get latest version od Chrome Extension</h3>
<Button onClick={this.handleInstall}>Get .crx file</Button>
<div className="welcome__update-explanation">
Note: after download complete, extract zip file, go to url: <i>chrome://extensions/</i>, then toggle on developer mode
and just Drag&Drop .crx file. <br/><br/> After that reload the page!
</div>
</div>
);
}
return (
<Login onClick={this.props.handleConnect} />
);
}
if (this.state.isButtonVisible) {
return (
<Button
onClick={this.handleInstall}
text="Get the extension file"
/>
);
}
return (
<div className="welcome__update-explanation">
Note: after download complete, extract zip file, go to url: <i>chrome://extensions/</i>, then toggle on developer mode
and click "Load unpacked" at the top left and seleft unziped folder. <br/><br/> After that reload the page!
</div>
);
}
return (
<span className="welcome__chrome">
Only on Google Chrome <img alt="Chrome" src="/assets/img/chrome.png" />
</span>
);
}
render() {
return (
<DocumentTitle title="Tind3r.com - Unofficial Tinder client">
<div className="welcome">
<div className="welcome__left">
<div className="welcome__name">
tind<b>3</b>r.com
<div className="welcome__slogan">unofficial Tinder web client</div>
</div>
<div className="welcome__image" />
</div>
<div className="welcome__right">
<div className="welcome__info">
<div className="welcome__cell">
<h1>Great things <br /> are coming</h1>
{this.renderButton()}
</div>
</div>
</div>
</div>
</DocumentTitle>
);
}
}
|
src/Axis.js | 4Catalyzer/react-d3-svg | import React from 'react';
import { directionType } from './PropTypes';
import purePlotClass from './utils/purePlotClass';
@purePlotClass({ scale: ({ props }) => props.scale })
export default class Axis extends React.Component {
static propTypes = {
scale: React.PropTypes.func.isRequired,
orient: directionType.isRequired,
innerTickSize: React.PropTypes.number.isRequired,
outerTickSize: React.PropTypes.number.isRequired,
tickPadding: React.PropTypes.number.isRequired,
ticks: React.PropTypes.any.isRequired,
tickValues: React.PropTypes.array,
tickFormat: React.PropTypes.func,
shouldUpdate: React.PropTypes.bool, // For purePlotClass.
children: React.PropTypes.node,
};
static defaultProps = {
innerTickSize: 6,
outerTickSize: 6,
tickPadding: 3,
ticks: [10],
};
render() {
const {
scale,
orient,
innerTickSize,
outerTickSize,
tickPadding,
ticks: tickArgumentsRaw,
tickValues,
tickFormat: tickFormatIn,
children,
...props,
} = this.props;
let tickArguments;
if (Array.isArray(tickArgumentsRaw)) {
tickArguments = tickArgumentsRaw;
} else {
tickArguments = [tickArgumentsRaw];
}
let ticks;
if (tickValues) {
ticks = tickValues;
} else if (scale.ticks) {
ticks = scale.ticks(...tickArguments);
} else {
ticks = scale.domain();
}
let tickFormat;
if (tickFormatIn) {
tickFormat = tickFormatIn;
} else if (scale.tickFormat) {
tickFormat = scale.tickFormat(...tickArguments);
}
const [rangeStart, rangeEnd] = scale.range();
const tickSpacing = Math.max(innerTickSize, 0) + tickPadding;
const sign = orient === 'top' || orient === 'left' ? -1 : 1;
const innerTickMove = sign * innerTickSize;
const outerTickMove = sign * outerTickSize;
const tickSpacingMove = sign * tickSpacing;
let tickTransform;
let lineProps;
let textProps;
let pathD;
if (orient === 'top' || orient === 'bottom') {
tickTransform = d => `translate(${scale(d)},0)`;
lineProps = { x2: 0, y2: innerTickMove };
textProps = {
x: 0,
y: tickSpacingMove,
dy: sign < 0 ? '0em' : '.71em',
style: { textAnchor: 'middle' },
};
pathD = `M${rangeStart},${outerTickMove}V0H${rangeEnd}V${outerTickMove}`;
} else {
tickTransform = d => `translate(0,${scale(d)})`;
lineProps = { x2: innerTickMove, y2: 0 };
textProps = {
x: tickSpacingMove,
y: 0,
dy: '.32em',
style: { textAnchor: sign < 0 ? 'end' : 'start' },
};
pathD = `M${outerTickMove},${rangeStart}H0V${rangeEnd}H${outerTickMove}`;
}
const renderedTicks = ticks.map(d =>
<g key={d} className="tick" transform={tickTransform(d)}>
<line {...lineProps} />
<text {...textProps}>
{tickFormat ? tickFormat(d) : d}
</text>
</g>
);
return (
<g {...props}>
{renderedTicks}
<path className="domain" d={pathD} />
{children}
</g>
);
}
}
|
src/svg-icons/action/card-membership.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionCardMembership = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h4v5l4-2 4 2v-5h4c1.11 0 2-.89 2-2V4c0-1.11-.89-2-2-2zm0 13H4v-2h16v2zm0-5H4V4h16v6z"/>
</SvgIcon>
);
ActionCardMembership = pure(ActionCardMembership);
ActionCardMembership.displayName = 'ActionCardMembership';
ActionCardMembership.muiName = 'SvgIcon';
export default ActionCardMembership;
|
src/svg-icons/hardware/keyboard-return.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboardReturn = (props) => (
<SvgIcon {...props}>
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
</SvgIcon>
);
HardwareKeyboardReturn = pure(HardwareKeyboardReturn);
HardwareKeyboardReturn.displayName = 'HardwareKeyboardReturn';
HardwareKeyboardReturn.muiName = 'SvgIcon';
export default HardwareKeyboardReturn;
|
stories/components/form/formCheckBox/index.js | tal87/operationcode_frontend | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import FormCheckBox from 'shared/components/form/formCheckBox/formCheckBox';
storiesOf('shared/components/form/formCheckBox', module)
.add('Default', () => (
<FormCheckBox
name="check"
value="checked"
onChange={action('clicked')}
/>
))
.add('With custom checkob div style', () => (
<FormCheckBox
name="check"
value="checked"
onChange={action('clicked')}
checkBox={{
display: 'inline',
margin: '14px'
}}
/>
))
.add('With custom label styles', () => (
<FormCheckBox
name="check"
value="checked"
onChange={action('clicked')}
label={{
fontWeight: '16px',
margin: '16px'
}}
/>
)); |
client/src/pages/Login.react.js | wenhao/fixed-asset | import React from 'react'
import {
RaisedButton,
FontIcon,
Paper,
TextField
} from 'material-ui'
import {
State,
Link
} from 'react-router'
import userApi from '../services/user'
var Login = React.createClass({
mixins: [State],
getInitialState() {
return {
title: '',
isDisable: true
}
},
render() {
return (
<Paper zDepth={1} className="page-auth">
<div className="login-group">
<h3>Log in</h3>
<div>
<TextField ref="username" hintText="User name" floatingLabelText="User name" onChange={this._handleLoginButton}/>
</div>
<div>
<TextField ref="password" type="password" hintText="Password" floatingLabelText="Password" onChange={this._handleLoginButton}/>
</div>
<h5 className="error-label">{this.state.errorMsg}</h5>
<div>
<Link to="home">Forgot your password?</Link>
</div>
<RaisedButton ref="loginButton" className="login-button" secondary={true} onClick={this._login} disabled={this.state.isDisable}>
<FontIcon className="muidocs-icon-custom-github example-button-icon"/>
<span className="mui-raised-button-label example-icon-button-label">Log in</span>
</RaisedButton>
</div>
</Paper>
)
},
_handleLoginButton() {
var username = this.refs.username.getValue();
var password = this.refs.password.getValue();
if(username && password){
this.setState({isDisable:false})
} else {
this.setState({isDisable: true})
}
},
_login() {
var username = this.refs.username.getValue();
var password = this.refs.password.getValue();
if (!username || !password) {
this.setState({errorMsg: 'User name or password cannot be empty.'});
} else {
userApi.login({"account": username, "password": password}).then(this.onLogin, this.onLoginFail);
}
},
onLogin(msg) {
this.context.router.transitionTo('user');
},
onLoginFail(err) {
this.setState({errorMsg: err.response.body.errorMessage})
}
});
export default Login
|
packages/wix-style-react/src/StatisticsWidget/docs/examples/Descriptions.js | wix/wix-style-react | /* eslint-disable no-undef */
import React from 'react';
import { StatisticsWidget } from 'wix-style-react';
render(
<div style={{ background: '#fff' }}>
<StatisticsWidget
items={[
{
value: '$500',
description: 'Sales',
},
{
value: '$1,500',
},
{
value: '$2,500',
description: 'Revenue',
},
]}
/>
</div>,
);
|
src/UserInfo.js | porterjamesj/goodreads-vis | import React, { Component } from 'react';
import { extractField } from './utils';
export default class UserInfo extends Component {
render() {
let userName, imageUrl;
if (this.props.info) {
userName = extractField(this.props.info, "user name");
imageUrl = extractField(this.props.info, "user small_image_url");
} else {
userName = "N/A";
imageUrl = "";
}
return (
<div className="user-info">
<img className="user-image" src={imageUrl} alt="user profile"></img>
<span className="user-text">{userName}</span>
</div>
);
}
}
|
src/components/referrals/send-referral-email.js | dylanlott/bridge-gui | import React, { Component } from 'react';
export default class SendReferralEmail extends Component {
render() {
return (
<div className="col-xs-12 col-md-6">
<h2>Refer by email</h2>
<div className="content">
<form acceptCharset="UTF-8" onSubmit={this.props.handleSubmit}>
<p>Enter your friends' emails (separated by commas) and we'll invite them for you.
</p>
<div className="row">
<div className="col-xs-12">
<input
type="text"
className="form-control"
value={this.props.value}
onChange={this.props.handleChange}
/>
{this.props.valid
? null
: <span style={{ color: 'red', margin: '10px', display: 'inline-block' }}>Invalid email list!</span>
}
</div>
</div>
<div className="row">
<div className="col-xs-12">
<input
type="submit"
name="submit"
value="Invite friends"
className="btn btn-block btn-green"
/>
{
this.props.emailFailures.length
? <div style={{ color: 'red', margin: '10px', display:
'inline-block' }}>
Error sending: {this.props.emailFailures}
</div>
: null
}
{
this.props.emailSuccesses.length
? <div style={{ color: 'green', margin: '10px', display:
'inline-block' }}>
Success sending: {this.props.emailSuccesses}
</div>
: null
}
</div>
</div>
</form>
</div>
</div>
);
}
}
SendReferralEmail.propTypes = {
handleSubmit: React.PropTypes.func,
handleChange: React.PropTypes.func,
value: React.PropTypes.string,
valid: React.PropTypes.bool,
emailFailures: React.PropTypes.array,
emailSuccess: React.PropTypes.array
};
|
docs/src/examples/modules/Progress/Content/ProgressExampleLabel.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Progress } from 'semantic-ui-react'
const ProgressExampleLabel = () => <Progress percent={55}>Label</Progress>
export default ProgressExampleLabel
|
app/assets/scripts/main.js | requesto/requesto | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, Route, IndexRoute, useRouterHistory} from 'react-router'
import { createHashHistory } from 'history'
import ReduxPromise from 'redux-promise';
import Reducers from './reducers';
// Components
import App from './components/app';
import Index from './components/index';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
const routerHistory = useRouterHistory(createHashHistory)({queryKey:false})
const devTools = window.devToolsExtension ? window.devToolsExtension() : f => f;
ReactDOM.render(
<Provider store={createStoreWithMiddleware(Reducers,devTools)}>
<Router history={routerHistory} onUpdate={() => window.scrollTo(0, 0)}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
</Route>
</Router>
</Provider>
,document.querySelector('.component-root'));
|
client/src/javascript/components/general/form-elements/TextboxRepeater.js | stephdewit/flood | import {FormElementAddon, FormRow, FormRowGroup, Textbox} from 'flood-ui-kit';
import React from 'react';
import AddMini from '../../icons/AddMini';
import RemoveMini from '../../icons/RemoveMini';
export default class TextboxRepeater extends React.PureComponent {
state = {
textboxes: this.props.defaultValues || [{id: 0, value: ''}],
};
idCounter = 0;
getID() {
return ++this.idCounter;
}
getTextboxes = () =>
this.state.textboxes.map((textbox, index) => {
let removeButton = null;
if (index > 0) {
removeButton = (
<FormElementAddon
onClick={() => {
this.handleTextboxRemove(index);
}}>
<RemoveMini size="mini" />
</FormElementAddon>
);
}
return (
<FormRow key={textbox.id}>
<Textbox
addonPlacement="after"
id={`${this.props.id}-${textbox.id}`}
defaultValue={textbox.value}
label={index === 0 && this.props.label}
placeholder={this.props.placeholder}
wrapperClassName="textbox-repeater">
<FormElementAddon
onClick={() => {
this.handleTextboxAdd(index);
}}>
<AddMini size="mini" />
</FormElementAddon>
{removeButton}
</Textbox>
</FormRow>
);
});
handleTextboxAdd = index => {
this.setState(state => {
const textboxes = Object.assign([], state.textboxes);
textboxes.splice(index + 1, 0, {id: this.getID(), value: ''});
return {textboxes};
});
};
handleTextboxRemove = index => {
this.setState(state => {
const textboxes = Object.assign([], state.textboxes);
textboxes.splice(index, 1);
return {textboxes};
});
};
render() {
return <FormRowGroup>{this.getTextboxes()}</FormRowGroup>;
}
}
|
examples/CollectionBasic.js | 15lyfromsaturn/react-materialize | import React from 'react';
import Collection from '../src/Collection';
import CollectionItem from '../src/CollectionItem';
export default
<Collection>
<CollectionItem>Alvin</CollectionItem>
<CollectionItem>Alvin</CollectionItem>
<CollectionItem>Alvin</CollectionItem>
<CollectionItem>Alvin</CollectionItem>
</Collection>;
|
node_modules/react-native-svg/elements/Line.js | 15chrjef/mobileHackerNews | import React from 'react';
import createReactNativeComponentClass from 'react/lib/createReactNativeComponentClass';
import {LineAttributes} from '../lib/attributes';
import Shape from './Shape';
import {pathProps, numberProp} from '../lib/props';
class Line extends Shape {
static displayName = 'Line';
static propTypes = {
...pathProps,
x1: numberProp.isRequired,
x2: numberProp.isRequired,
y1: numberProp.isRequired,
y2: numberProp.isRequired
};
static defaultProps = {
x1: 0,
y1: 0,
x2: 0,
y2: 0
};
setNativeProps = (...args) => {
this.root.setNativeProps(...args);
};
render() {
let props = this.props;
return <RNSVGLine
ref={ele => {this.root = ele;}}
{...this.extractProps(props)}
x1={props.x1.toString()}
y1={props.y1.toString()}
x2={props.x2.toString()}
y2={props.y2.toString()}
/>;
}
}
const RNSVGLine = createReactNativeComponentClass({
validAttributes: LineAttributes,
uiViewClassName: 'RNSVGLine'
});
export default Line;
|
dispatch/static/manager/src/js/pages/ProfilePage.js | ubyssey/dispatch | import React from 'react'
import R from 'ramda'
import { connect } from 'react-redux'
import { Button, Intent } from '@blueprintjs/core'
import userActions from '../actions/UserActions'
import PersonEditor from '../components/PersonEditor'
import { TextInput } from '../components/inputs'
import * as Form from '../components/Form'
require('../../styles/components/user_form.scss')
class ProfilePageComponent extends React.Component {
loadUser() {
this.props.getUser(this.props.token, 'me')
}
componentDidMount() {
this.loadUser()
}
getUserId() {
return this.props.user.id
}
getPersonId() {
const userId = this.getUserId()
return userId ? this.props.entities.remote[userId].person : null
}
getUser() {
const userId = this.getUserId()
return userId ? (this.props.entities.local ? this.props.entities.local[userId]
: this.props.entities.remote[userId]) : null
}
handleUpdate(field, value) {
this.props.setUser(R.assoc(field, value, this.getUser()))
}
save() {
this.props.saveUser(this.props.token, this.getUserId(), this.getUser())
}
render() {
const userId = this.getUserId()
const personId = this.getPersonId()
const user = this.getUser()
const errors = this.props.user.errors
const personEditor = personId ? (
<PersonEditor
itemId={personId}
goBack={this.props.router.goBack}
route={this.props.route} />
) : null
const userForm = userId ? (
<div className='u-container u-container--padded c-user-form'>
<div className='c-user-form__heading'>Account Details</div>
<Form.Container onSubmit={e => e.preventDefault()}>
<Form.Input
label='Email'
padded={false}
error={errors.email}>
<TextInput
placeholder='name@domain.tld'
value={user.email || ''}
fill={true}
onChange={e => this.handleUpdate('email', e.target.value)} />
</Form.Input>
<Form.Input
label='Password'
padded={false}
error={errors.password_a}>
<TextInput
placeholder=''
value={user.password_a || ''}
fill={true}
type='password'
onChange={e => this.handleUpdate('password_a', e.target.value)} />
</Form.Input>
<Form.Input
label='Password Again'
padded={false}
error={errors.password_b}>
<TextInput
placeholder=''
value={user.password_b || ''}
fill={true}
type='password'
onChange={e => this.handleUpdate('password_b', e.target.value)} />
</Form.Input>
</Form.Container>
<Button
intent={Intent.SUCCESS}
onClick={() => this.save()}>
Save
</Button>
</div>
) : null
return (
<div>
{personEditor}
{userForm}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
user: state.app.users.single,
entities: {
remote: state.app.entities.users,
local: state.app.entities.local.users
},
token: state.app.auth.token
}
}
const mapDispatchToProps = (dispatch) => {
return {
getUser: (token, eventId) => {
dispatch(userActions.get(token, eventId))
},
saveUser: (token, eventId, data) => {
dispatch(userActions.save(token, eventId, data))
},
setUser: (data) => {
dispatch(userActions.set(data))
}
}
}
const ProfilePage = connect(
mapStateToProps,
mapDispatchToProps
)(ProfilePageComponent)
export default ProfilePage
|
src/router/Routes.js | tedyuen/react-redux-form-v6-example | import React from 'react';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import configureStore from '../store/configureStore';
import { history } from '../router/history';
import { MainRouter } from './MainRouter';
const store = configureStore();
const Routes = () => (
<Provider store={store}>
<div>
<ConnectedRouter history={history}>
<MainRouter></MainRouter>
</ConnectedRouter>
</div>
</Provider>
);
export default Routes;
|
react/create-react-app-sample/sample/src/index.js | TakesxiSximada/TIL | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
client/lib/convert-to-print/index.js | OpenWebslides/OpenWebslides | /* eslint-disable no-case-declarations */
import React from 'react';
import { contentItemTypes } from 'constants/contentItemTypes';
import { inlinePropertyTypes } from 'constants/inlinePropertyTypes';
// converters:
import ConversationElement from 'presentationals/components/print-view/ConversationElement';
import illustrativeImageToReact from './convert-items/illustrativeImageToReact';
import decorativeImageToReact from './convert-items/decorativeImageToReact';
import iframeToReact from './convert-items/iframeToReact';
import titleToReact from './convert-items/titleToReact';
import paragraphToReact from './convert-items/paragraphToReact';
const { TITLE, PARAGRAPH, SECTION, LIST, LIST_ITEM, IMAGE_CONTAINER, ILLUSTRATIVE_IMAGE, DECORATIVE_IMAGE, IFRAME } = contentItemTypes;
const { EM, STRONG } = inlinePropertyTypes;
function contentItemObjectToReact(
entities,
contentItemObject,
currentLevel,
preferences,
amountOfImages = 0,
) {
switch (contentItemObject.contentItemType) {
case TITLE:
return titleToReact(contentItemObject, currentLevel);
case PARAGRAPH:
return paragraphToReact(contentItemObject, currentLevel);
case SECTION:
return contentItemObject.childItemIds.map((itemId) => {
const itemObject = entities.contentItems.byId[itemId];
return contentItemObjectToReact(
entities, itemObject, currentLevel, preferences,
);
});
case LIST:
let childrenObjects = contentItemObject.childItemIds.map(
itemId => entities.contentItems.byId[itemId],
);
return React.createElement(
contentItemObject.ordered ? 'ol' : 'ul',
{ 'data-level': currentLevel, className: 'c_print-view__list' },
childrenObjects.map(child =>
contentItemObjectToReact(entities, child, currentLevel, preferences),
),
);
case LIST_ITEM:
return React.createElement(
'li',
{ 'data-level': currentLevel, className: 'c_print-view__list-item' },
contentItemObject.text,
);
case IMAGE_CONTAINER:
if (contentItemObject.imageType === 'ILLUSTRATIVE_IMAGE') {
childrenObjects = contentItemObject.childItemIds.map(
itemId => entities.contentItems.byId[itemId],
);
return React.createElement(
'div',
{ className: 'c_print-view__image-container' },
childrenObjects.map(child =>
contentItemObjectToReact(entities, child, currentLevel, preferences, childrenObjects.length),
),
);
}
break;
case ILLUSTRATIVE_IMAGE:
return illustrativeImageToReact(
contentItemObject, preferences.imagePref, amountOfImages, currentLevel,
);
case DECORATIVE_IMAGE:
return decorativeImageToReact(
contentItemObject, preferences.decorativeImagePref, currentLevel,
);
case IFRAME:
return iframeToReact(contentItemObject, preferences.iframesPref, currentLevel);
default:
return React.createElement(
'p',
null,
`Unsupported element: ${contentItemObject.contentItemType}`,
);
}
}
function getRelevantConversations(conversationsById, slideId) {
let relevantConversations = [];
Object.keys(conversationsById).forEach((id) => {
if (conversationsById[id].contentItemId === slideId) {
relevantConversations = relevantConversations.concat(conversationsById[id]);
}
});
return relevantConversations;
}
function getRelevantComments(commentsById, conversationId) {
let relevantComments = [];
Object.keys(commentsById).forEach((id) => {
if (commentsById[id].conversationId === conversationId) {
relevantComments = relevantComments.concat(commentsById[id]);
}
});
return relevantComments;
}
function convertSlideToContentItems(slide, entities, preferences) {
const slideElements = slide.contentItemIds.map(itemId => entities.contentItems.byId[itemId]);
const level = parseInt(slide.level, 10);
const slideId = slide.id;
const conversations = getRelevantConversations(entities.conversations.byId, slideId);
let reactElements = slideElements.reduce(
(arr, currentObject) =>
arr.concat(
contentItemObjectToReact(entities, currentObject, level, preferences),
),
[],
);
if (conversations) {
if (preferences.annotationsPref === 'INLINE') {
reactElements = reactElements.concat(conversations.map((conversation) => {
const comments = getRelevantComments(entities.conversationComments.byId, conversation.id);
const conversationWithComments = { ...conversation, comments };
return ConversationElement(conversationWithComments);
}));
}
}
return reactElements;
}
function divideTopLevelIntoSections(slides, level) {
const sections = [];
let currentSection = [];
let i = 0;
while (i < slides.length) {
// Add the first slide which we assume to be at level 1
currentSection.push(slides[i]);
i += 1;
while (i < slides.length && slides[i].level > level) {
currentSection.push(slides[i]);
i += 1;
}
sections.push(currentSection);
currentSection = [];
}
return sections;
}
// Returns a <section> element containing all nested sections
function convertSection(slides, currentLevel, entities, preferences) {
let thisSectionElements;
thisSectionElements = convertSlideToContentItems(slides[0], entities, preferences);
if (slides.length > 1) {
const subSections = divideTopLevelIntoSections(slides.slice(1), currentLevel + 1);
const subSectionsElements = subSections.map(
section => convertSection(
section, currentLevel + 1, entities, preferences,
),
);
thisSectionElements = thisSectionElements.concat(subSectionsElements);
}
return React.createElement(
'section',
null,
thisSectionElements,
);
}
function convertToPrint(entities, deckId, preferences) {
const slideIds = entities.decks.byId[deckId].slideIds;
const slideObjects = slideIds.map(id => entities.slides.byId[id]).asMutable();
const sections = divideTopLevelIntoSections(slideObjects, 0);
const elements = sections.map(
section => convertSection(section, 0, entities, preferences),
);
return elements;
}
export default convertToPrint;
|
src/docs/examples/ProgressBar/Example70Percent.js | vonZ/rc-vvz | import React from 'react';
import ProgressBar from 'ps-react/ProgressBar';
/** 70% progress */
export default function Example70Percent() {
return <ProgressBar percent={70} width={150} />
}
|
actor-apps/app-web/src/app/components/modals/InviteUser.react.js | zwensoft/actor-platform | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import _ from 'lodash';
import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import ActorClient from 'utils/ActorClient';
import { KeyCodes } from 'constants/ActorAppConstants';
import InviteUserActions from 'actions/InviteUserActions';
import InviteUserByLinkActions from 'actions/InviteUserByLinkActions';
import ContactStore from 'stores/ContactStore';
import InviteUserStore from 'stores/InviteUserStore';
import ContactItem from './invite-user/ContactItem.react';
const getStateFromStores = () => {
return ({
isOpen: InviteUserStore.isModalOpen(),
contacts: ContactStore.getContacts(),
group: InviteUserStore.getGroup()
});
};
const hasMember = (group, userId) =>
undefined !== _.find(group.members, (c) => c.peerInfo.peer.id === userId);
@ReactMixin.decorate(IntlMixin)
class InviteUser extends React.Component {
constructor(props) {
super(props);
this.state = _.assign({
search: ''
}, getStateFromStores());
InviteUserStore.addChangeListener(this.onChange);
ContactStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
InviteUserStore.removeChangeListener(this.onChange);
ContactStore.removeChangeListener(this.onChange);
}
componentWillUpdate(nextProps, nextState) {
if (nextState.isOpen && !this.state.isOpen) {
document.addEventListener('keydown', this.onKeyDown, false);
} else if (!nextState.isOpen && this.state.isOpen) {
document.removeEventListener('keydown', this.onKeyDown, false);
}
}
onChange = () => this.setState(getStateFromStores());
onClose = () => InviteUserActions.hide();
onContactSelect = (contact) => InviteUserActions.inviteUser(this.state.group.id, contact.uid);
onSearchChange = (event) => this.setState({search: event.target.value});
onInviteUrlByClick = () => {
const { group } = this.state;
InviteUserByLinkActions.show(group);
InviteUserActions.hide();
};
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
render() {
const { contacts, group, search, isOpen } = this.state;
let contactList = [];
if (isOpen) {
_.forEach(contacts, (contact, i) => {
const name = contact.name.toLowerCase();
if (name.includes(search.toLowerCase())) {
if (!hasMember(group, contact.uid)) {
contactList.push(
<ContactItem contact={contact} key={i} onSelect={this.onContactSelect}/>
);
} else {
contactList.push(
<ContactItem contact={contact} key={i} isMember/>
);
}
}
}, this);
if (contactList.length === 0) {
contactList.push(
<li className="contacts__list__item contacts__list__item--empty text-center">
<FormattedMessage message={this.getIntlMessage('inviteModalNotFound')}/>
</li>
);
}
return (
<Modal className="modal-new modal-new--invite contacts"
closeTimeoutMS={150}
isOpen={isOpen}
style={{width: 400}}>
<header className="modal-new__header">
<a className="modal-new__header__icon material-icons">person_add</a>
<h4 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('inviteModalTitle')}/>
</h4>
<div className="pull-right">
<button className="button button--lightblue" onClick={this.onClose}>Done</button>
</div>
</header>
<div className="modal-new__body">
<div className="modal-new__search">
<i className="material-icons">search</i>
<input className="input input--search"
onChange={this.onSearchChange}
placeholder={this.getIntlMessage('inviteModalSearch')}
type="search"
value={search}/>
</div>
<a className="link link--blue" onClick={this.onInviteUrlByClick}>
<i className="material-icons">link</i>
{this.getIntlMessage('inviteByLink')}
</a>
</div>
<div className="contacts__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default InviteUser;
|
openex-front/src/private/components/exercises/Exercises.js | Luatix/OpenEx | import React from 'react';
import { makeStyles } from '@mui/styles';
import { useDispatch } from 'react-redux';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import { Link } from 'react-router-dom';
import {
ChevronRightOutlined,
FileDownloadOutlined,
Kayaking,
} from '@mui/icons-material';
import ListItemSecondaryAction from '@mui/material/ListItemSecondaryAction';
import { CSVLink } from 'react-csv';
import Tooltip from '@mui/material/Tooltip';
import IconButton from '@mui/material/IconButton';
import { useFormatter } from '../../../components/i18n';
import { fetchExercises } from '../../../actions/Exercise';
import ItemTags from '../../../components/ItemTags';
import SearchFilter from '../../../components/SearchFilter';
import TagsFilter from '../../../components/TagsFilter';
import CreateExercise from './CreateExercise';
import ExerciseStatus from './ExerciseStatus';
import { useHelper } from '../../../store';
import useDataLoader from '../../../utils/ServerSideEvent';
import useSearchAnFilter from '../../../utils/SortingFiltering';
import { exportData } from '../../../utils/Environment';
const useStyles = makeStyles((theme) => ({
parameters: {
marginTop: -10,
},
container: {
marginTop: 10,
},
itemHead: {
paddingLeft: 10,
textTransform: 'uppercase',
cursor: 'pointer',
},
item: {
paddingLeft: 10,
height: 50,
},
bodyItem: {
height: '100%',
fontSize: 13,
},
itemIcon: {
color: theme.palette.primary.main,
},
goIcon: {
position: 'absolute',
right: -10,
},
inputLabel: {
float: 'left',
},
sortIcon: {
float: 'left',
margin: '-5px 0 0 15px',
},
icon: {
color: theme.palette.primary.main,
},
}));
const headerStyles = {
iconSort: {
position: 'absolute',
margin: '0 0 0 5px',
padding: 0,
top: '0px',
},
exercise_name: {
float: 'left',
width: '20%',
fontSize: 12,
fontWeight: '700',
},
exercise_subtitle: {
float: 'left',
width: '20%',
fontSize: 12,
fontWeight: '700',
},
exercise_start_date: {
float: 'left',
width: '15%',
fontSize: 12,
fontWeight: '700',
},
exercise_status: {
float: 'left',
width: '15%',
fontSize: 12,
fontWeight: '700',
},
exercise_tags: {
float: 'left',
width: '30%',
fontSize: 12,
fontWeight: '700',
},
};
const inlineStyles = {
exercise_name: {
float: 'left',
width: '20%',
height: 20,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
},
exercise_subtitle: {
float: 'left',
width: '20%',
height: 20,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
},
exercise_start_date: {
float: 'left',
width: '15%',
height: 20,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
},
exercise_status: {
float: 'left',
width: '15%',
height: 20,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
},
exercise_tags: {
float: 'left',
width: '30%',
height: 20,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
},
};
const Exercises = () => {
const classes = useStyles();
const dispatch = useDispatch();
const { t, nsdt } = useFormatter();
const { exercises, tagsMap, userAdmin } = useHelper((helper) => ({
exercises: helper.getExercises(),
tagsMap: helper.getTagsMap(),
userAdmin: helper.getMe()?.user_admin ?? false,
}));
const searchColumns = ['name', 'subtitle'];
const filtering = useSearchAnFilter('exercise', 'name', searchColumns);
useDataLoader(() => {
dispatch(fetchExercises());
});
const sortedExercises = filtering.filterAndSort(exercises);
return (
<div>
<div className={classes.parameters}>
<div style={{ float: 'left', marginRight: 20 }}>
<SearchFilter
small={true}
onChange={filtering.handleSearch}
keyword={filtering.keyword}
/>
</div>
<div style={{ float: 'left', marginRight: 20 }}>
<TagsFilter
onAddTag={filtering.handleAddTag}
onRemoveTag={filtering.handleRemoveTag}
currentTags={filtering.tags}
/>
</div>
<div style={{ float: 'right', margin: '-5px 15px 0 0' }}>
{sortedExercises.length > 0 ? (
<CSVLink
data={exportData(
'exercise',
[
'exercise_name',
'exercise_subtitle',
'exercise_description',
'exercise_status',
'exercise_tags',
],
sortedExercises,
tagsMap,
)}
filename={`${t('Exercises')}.csv`}
>
<Tooltip title={t('Export this list')}>
<IconButton size="large">
<FileDownloadOutlined color="primary" />
</IconButton>
</Tooltip>
</CSVLink>
) : (
<IconButton size="large" disabled={true}>
<FileDownloadOutlined />
</IconButton>
)}
</div>
</div>
<div className="clearfix" />
<List classes={{ root: classes.container }}>
<ListItem
classes={{ root: classes.itemHead }}
divider={false}
style={{ paddingTop: 0 }}
>
<ListItemIcon>
<span
style={{
padding: '0 8px 0 8px',
fontWeight: 700,
fontSize: 12,
}}
>
</span>
</ListItemIcon>
<ListItemText
primary={
<div>
{filtering.buildHeader(
'exercise_name',
'Name',
true,
headerStyles,
)}
{filtering.buildHeader(
'exercise_subtitle',
'Subtitle',
true,
headerStyles,
)}
{filtering.buildHeader(
'exercise_start_date',
'Start date',
true,
headerStyles,
)}
{filtering.buildHeader(
'exercise_status',
'Status',
true,
headerStyles,
)}
{filtering.buildHeader(
'exercise_tags',
'Tags',
true,
headerStyles,
)}
</div>
}
/>
<ListItemSecondaryAction> </ListItemSecondaryAction>
</ListItem>
{sortedExercises.map((exercise) => (
<ListItem
key={exercise.exercise_id}
classes={{ root: classes.item }}
divider={true}
button={true}
component={Link}
to={`/exercises/${exercise.exercise_id}`}
>
<ListItemIcon>
<Kayaking color="primary" />
</ListItemIcon>
<ListItemText
primary={
<div>
<div
className={classes.bodyItem}
style={inlineStyles.exercise_name}
>
{exercise.exercise_name}
</div>
<div
className={classes.bodyItem}
style={inlineStyles.exercise_subtitle}
>
{exercise.exercise_subtitle}
</div>
<div
className={classes.bodyItem}
style={inlineStyles.exercise_start_date}
>
{exercise.exercise_start_date ? (
nsdt(exercise.exercise_start_date)
) : (
<i>{t('Manual')}</i>
)}
</div>
<div
className={classes.bodyItem}
style={inlineStyles.exercise_start_date}
>
<ExerciseStatus
variant="list"
status={exercise.exercise_status}
/>
</div>
<div
className={classes.bodyItem}
style={inlineStyles.exercise_tags}
>
<ItemTags variant="list" tags={exercise.exercise_tags} />
</div>
</div>
}
/>
<ListItemSecondaryAction>
<ChevronRightOutlined />
</ListItemSecondaryAction>
</ListItem>
))}
</List>
{userAdmin && <CreateExercise />}
</div>
);
};
export default Exercises;
|
src/js/contexts/ResponsiveContext/stories/CustomBreakpoints.js | HewlettPackard/grommet | import React from 'react';
import { Box, Grommet, Heading, ResponsiveContext } from 'grommet';
const customBreakpoints = {
global: {
breakpoints: {
xsmall: {
value: 375,
},
small: {
value: 568,
edgeSize: {
none: '0px',
small: '6px',
medium: '12px',
large: '24px',
},
},
medium: {
value: 768,
edgeSize: {
none: '0px',
small: '12px',
medium: '24px',
large: '48px',
},
},
large: {
value: 1024,
edgeSize: {
none: '0px',
small: '12px',
medium: '24px',
large: '48px',
},
},
xlarge: {
value: 1366,
edgeSize: {
none: '0px',
small: '12px',
medium: '24px',
large: '48px',
},
},
},
},
};
export const CustomBreakpoints = () => (
<Grommet theme={customBreakpoints} full>
<ResponsiveContext.Consumer>
{size => (
<Box fill background="brand">
<Heading>{`Hi, I'm ${size}, resize me!`}</Heading>
</Box>
)}
</ResponsiveContext.Consumer>
</Grommet>
);
CustomBreakpoints.storyName = 'Custom breakpoints';
export default {
title: 'Utilities/ResponsiveContext/Custom breakpoints',
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.