path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
node_modules/react-router/es6/Link.js | jwilkinson/tiff16-films | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { routerShape } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = React.createClass({
displayName: 'Link',
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([string, object]).isRequired,
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
};
},
handleClick: function handleClick(event) {
if (this.props.onClick) this.props.onClick(event);
if (event.defaultPrevented) return;
!this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0;
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) return;
event.preventDefault();
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(location);
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(location);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(location, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ' ' + activeClassName;
} else {
props.className = activeClassName;
}
}
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return React.createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
export default Link; |
fixtures/attribute-behavior/src/App.js | aickin/react | import React from 'react';
import {createElement} from 'glamor/react'; // eslint-disable-line
/* @jsx createElement */
import {MultiGrid, AutoSizer} from 'react-virtualized';
import 'react-virtualized/styles.css';
import FileSaver from 'file-saver';
import {
inject as injectErrorOverlay,
uninject as uninjectErrorOverlay,
} from 'react-error-overlay/lib/overlay';
import attributes from './attributes';
const types = [
{
name: 'string',
testValue: 'a string',
testDisplayValue: "'a string'",
},
{
name: 'empty string',
testValue: '',
testDisplayValue: "''",
},
{
name: 'array with string',
testValue: ['string'],
testDisplayValue: "['string']",
},
{
name: 'empty array',
testValue: [],
testDisplayValue: '[]',
},
{
name: 'object',
testValue: {
toString() {
return 'result of toString()';
},
},
testDisplayValue: "{ toString() { return 'result of toString()'; } }",
},
{
name: 'numeric string',
testValue: '42',
displayValue: "'42'",
},
{
name: '-1',
testValue: -1,
},
{
name: '0',
testValue: 0,
},
{
name: 'integer',
testValue: 1,
},
{
name: 'NaN',
testValue: NaN,
},
{
name: 'float',
testValue: 99.99,
},
{
name: 'true',
testValue: true,
},
{
name: 'false',
testValue: false,
},
{
name: "string 'true'",
testValue: 'true',
displayValue: "'true'",
},
{
name: "string 'false'",
testValue: 'false',
displayValue: "'false'",
},
{
name: "string 'on'",
testValue: 'on',
displayValue: "'on'",
},
{
name: "string 'off'",
testValue: 'off',
displayValue: "'off'",
},
{
name: 'symbol',
testValue: Symbol('foo'),
testDisplayValue: "Symbol('foo')",
},
{
name: 'function',
testValue: function f() {},
},
{
name: 'null',
testValue: null,
},
{
name: 'undefined',
testValue: undefined,
},
];
const ALPHABETICAL = 'alphabetical';
const REV_ALPHABETICAL = 'reverse_alphabetical';
const GROUPED_BY_ROW_PATTERN = 'grouped_by_row_pattern';
const ALL = 'all';
const COMPLETE = 'complete';
const INCOMPLETE = 'incomplete';
function getCanonicalizedValue(value) {
switch (typeof value) {
case 'undefined':
return '<undefined>';
case 'object':
if (value === null) {
return '<null>';
}
if ('baseVal' in value) {
return getCanonicalizedValue(value.baseVal);
}
if (value instanceof SVGLength) {
return '<SVGLength: ' + value.valueAsString + '>';
}
if (value instanceof SVGRect) {
return (
'<SVGRect: ' +
[value.x, value.y, value.width, value.height].join(',') +
'>'
);
}
if (value instanceof SVGPreserveAspectRatio) {
return (
'<SVGPreserveAspectRatio: ' +
value.align +
'/' +
value.meetOrSlice +
'>'
);
}
if (value instanceof SVGNumber) {
return value.value;
}
if (value instanceof SVGMatrix) {
return (
'<SVGMatrix ' +
value.a +
' ' +
value.b +
' ' +
value.c +
' ' +
value.d +
' ' +
value.e +
' ' +
value.f +
'>'
);
}
if (value instanceof SVGTransform) {
return (
getCanonicalizedValue(value.matrix) +
'/' +
value.type +
'/' +
value.angle
);
}
if (typeof value.length === 'number') {
return (
'[' +
Array.from(value)
.map(v => getCanonicalizedValue(v))
.join(', ') +
']'
);
}
let name = (value.constructor && value.constructor.name) || 'object';
return '<' + name + '>';
case 'function':
return '<function>';
case 'symbol':
return '<symbol>';
case 'number':
return `<number: ${value}>`;
case 'string':
if (value === '') {
return '<empty string>';
}
return '"' + value + '"';
case 'boolean':
return `<boolean: ${value}>`;
default:
throw new Error('Switch statement should be exhaustive.');
}
}
let _didWarn = false;
function warn(str) {
_didWarn = true;
}
const UNKNOWN_HTML_TAGS = new Set(['keygen', 'time', 'command']);
function getRenderedAttributeValue(
react,
renderer,
serverRenderer,
attribute,
type
) {
const originalConsoleError = console.error;
console.error = warn;
const containerTagName = attribute.containerTagName || 'div';
const tagName = attribute.tagName || 'div';
function createContainer() {
if (containerTagName === 'svg') {
return document.createElementNS('http://www.w3.org/2000/svg', 'svg');
} else if (containerTagName === 'document') {
return document.implementation.createHTMLDocument('');
} else {
return document.createElement(containerTagName);
}
}
const read = attribute.read;
let testValue = type.testValue;
if (attribute.overrideStringValue !== undefined) {
switch (type.name) {
case 'string':
testValue = attribute.overrideStringValue;
break;
case 'array with string':
testValue = [attribute.overrideStringValue];
break;
default:
break;
}
}
let baseProps = {
...attribute.extraProps,
};
if (attribute.type) {
baseProps.type = attribute.type;
}
const props = {
...baseProps,
[attribute.name]: testValue,
};
let defaultValue;
let canonicalDefaultValue;
let result;
let canonicalResult;
let ssrResult;
let canonicalSsrResult;
let didWarn;
let didError;
let ssrDidWarn;
let ssrDidError;
_didWarn = false;
try {
let container = createContainer();
renderer.render(react.createElement(tagName, baseProps), container);
defaultValue = read(container.firstChild);
canonicalDefaultValue = getCanonicalizedValue(defaultValue);
container = createContainer();
renderer.render(react.createElement(tagName, props), container);
result = read(container.firstChild);
canonicalResult = getCanonicalizedValue(result);
didWarn = _didWarn;
didError = false;
} catch (error) {
result = null;
didWarn = _didWarn;
didError = true;
}
_didWarn = false;
let hasTagMismatch = false;
let hasUnknownElement = false;
try {
let container;
if (containerTagName === 'document') {
const html = serverRenderer.renderToString(
react.createElement(tagName, props)
);
container = createContainer();
container.innerHTML = html;
} else {
const html = serverRenderer.renderToString(
react.createElement(
containerTagName,
null,
react.createElement(tagName, props)
)
);
const outerContainer = document.createElement('div');
outerContainer.innerHTML = html;
container = outerContainer.firstChild;
}
if (
!container.lastChild ||
container.lastChild.tagName.toLowerCase() !== tagName.toLowerCase()
) {
hasTagMismatch = true;
}
if (
container.lastChild instanceof HTMLUnknownElement &&
!UNKNOWN_HTML_TAGS.has(container.lastChild.tagName.toLowerCase())
) {
hasUnknownElement = true;
}
ssrResult = read(container.lastChild);
canonicalSsrResult = getCanonicalizedValue(ssrResult);
ssrDidWarn = _didWarn;
ssrDidError = false;
} catch (error) {
ssrResult = null;
ssrDidWarn = _didWarn;
ssrDidError = true;
}
console.error = originalConsoleError;
if (hasTagMismatch) {
throw new Error('Tag mismatch. Expected: ' + tagName);
}
if (hasUnknownElement) {
throw new Error('Unexpected unknown element: ' + tagName);
}
let ssrHasSameBehavior;
let ssrHasSameBehaviorExceptWarnings;
if (didError && ssrDidError) {
ssrHasSameBehavior = true;
} else if (!didError && !ssrDidError) {
if (canonicalResult === canonicalSsrResult) {
ssrHasSameBehaviorExceptWarnings = true;
ssrHasSameBehavior = didWarn === ssrDidWarn;
}
ssrHasSameBehavior =
didWarn === ssrDidWarn && canonicalResult === canonicalSsrResult;
} else {
ssrHasSameBehavior = false;
}
return {
tagName,
containerTagName,
testValue,
defaultValue,
result,
canonicalResult,
canonicalDefaultValue,
didWarn,
didError,
ssrResult,
canonicalSsrResult,
ssrDidWarn,
ssrDidError,
ssrHasSameBehavior,
ssrHasSameBehaviorExceptWarnings,
};
}
function prepareState(initGlobals) {
function getRenderedAttributeValues(attribute, type) {
const {
ReactStable,
ReactDOMStable,
ReactDOMServerStable,
ReactNext,
ReactDOMNext,
ReactDOMServerNext,
} = initGlobals(attribute, type);
const reactStableValue = getRenderedAttributeValue(
ReactStable,
ReactDOMStable,
ReactDOMServerStable,
attribute,
type
);
const reactNextValue = getRenderedAttributeValue(
ReactNext,
ReactDOMNext,
ReactDOMServerNext,
attribute,
type
);
let hasSameBehavior;
if (reactStableValue.didError && reactNextValue.didError) {
hasSameBehavior = true;
} else if (!reactStableValue.didError && !reactNextValue.didError) {
hasSameBehavior =
reactStableValue.didWarn === reactNextValue.didWarn &&
reactStableValue.canonicalResult === reactNextValue.canonicalResult &&
reactStableValue.ssrHasSameBehavior ===
reactNextValue.ssrHasSameBehavior;
} else {
hasSameBehavior = false;
}
return {
reactStable: reactStableValue,
reactNext: reactNextValue,
hasSameBehavior,
};
}
const table = new Map();
const rowPatternHashes = new Map();
// Disable error overlay while testing each attribute
uninjectErrorOverlay();
for (let attribute of attributes) {
const results = new Map();
let hasSameBehaviorForAll = true;
let rowPatternHash = '';
for (let type of types) {
const result = getRenderedAttributeValues(attribute, type);
results.set(type.name, result);
if (!result.hasSameBehavior) {
hasSameBehaviorForAll = false;
}
rowPatternHash += [result.reactStable, result.reactNext]
.map(res =>
[
res.canonicalResult,
res.canonicalDefaultValue,
res.didWarn,
res.didError,
].join('||')
)
.join('||');
}
const row = {
results,
hasSameBehaviorForAll,
rowPatternHash,
// "Good enough" id that we can store in localStorage
rowIdHash: `${attribute.name} ${attribute.tagName} ${
attribute.overrideStringValue
}`,
};
const rowGroup = rowPatternHashes.get(rowPatternHash) || new Set();
rowGroup.add(row);
rowPatternHashes.set(rowPatternHash, rowGroup);
table.set(attribute, row);
}
// Renable error overlay
injectErrorOverlay();
return {
table,
rowPatternHashes,
};
}
const successColor = 'white';
const warnColor = 'yellow';
const errorColor = 'red';
function RendererResult({
result,
canonicalResult,
defaultValue,
canonicalDefaultValue,
didWarn,
didError,
ssrHasSameBehavior,
ssrHasSameBehaviorExceptWarnings,
}) {
let backgroundColor;
if (didError) {
backgroundColor = errorColor;
} else if (didWarn) {
backgroundColor = warnColor;
} else if (canonicalResult !== canonicalDefaultValue) {
backgroundColor = 'cyan';
} else {
backgroundColor = successColor;
}
let style = {
display: 'flex',
alignItems: 'center',
position: 'absolute',
height: '100%',
width: '100%',
backgroundColor,
};
if (!ssrHasSameBehavior) {
const color = ssrHasSameBehaviorExceptWarnings ? 'gray' : 'magenta';
style.border = `3px dotted ${color}`;
}
return <div css={style}>{canonicalResult}</div>;
}
function ResultPopover(props) {
return (
<pre
css={{
padding: '1em',
width: '25em',
}}>
{JSON.stringify(
{
reactStable: props.reactStable,
reactNext: props.reactNext,
hasSameBehavior: props.hasSameBehavior,
},
null,
2
)}
</pre>
);
}
class Result extends React.Component {
state = {showInfo: false};
onMouseEnter = () => {
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = setTimeout(() => {
this.setState({showInfo: true});
}, 250);
};
onMouseLeave = () => {
if (this.timeout) {
clearTimeout(this.timeout);
}
this.setState({showInfo: false});
};
componentWillUnmount() {
if (this.timeout) {
clearTimeout(this.interval);
}
}
render() {
const {reactStable, reactNext, hasSameBehavior} = this.props;
const style = {
position: 'absolute',
width: '100%',
height: '100%',
};
let highlight = null;
let popover = null;
if (this.state.showInfo) {
highlight = (
<div
css={{
position: 'absolute',
height: '100%',
width: '100%',
border: '2px solid blue',
}}
/>
);
popover = (
<div
css={{
backgroundColor: 'white',
border: '1px solid black',
position: 'absolute',
top: '100%',
zIndex: 999,
}}>
<ResultPopover {...this.props} />
</div>
);
}
if (!hasSameBehavior) {
style.border = '4px solid purple';
}
return (
<div
css={style}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}>
<div css={{position: 'absolute', width: '50%', height: '100%'}}>
<RendererResult {...reactStable} />
</div>
<div
css={{
position: 'absolute',
width: '50%',
left: '50%',
height: '100%',
}}>
<RendererResult {...reactNext} />
</div>
{highlight}
{popover}
</div>
);
}
}
function ColumnHeader({children}) {
return (
<div
css={{
position: 'absolute',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
}}>
{children}
</div>
);
}
function RowHeader({children, checked, onChange}) {
return (
<div
css={{
position: 'absolute',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
}}>
<input type="checkbox" checked={checked} onChange={onChange} />
{children}
</div>
);
}
function CellContent(props) {
const {
columnIndex,
rowIndex,
attributesInSortedOrder,
completedHashes,
toggleAttribute,
table,
} = props;
const attribute = attributesInSortedOrder[rowIndex - 1];
const type = types[columnIndex - 1];
if (columnIndex === 0) {
if (rowIndex === 0) {
return null;
}
const row = table.get(attribute);
const rowPatternHash = row.rowPatternHash;
return (
<RowHeader
checked={completedHashes.has(rowPatternHash)}
onChange={() => toggleAttribute(rowPatternHash)}>
{row.hasSameBehaviorForAll ? (
attribute.name
) : (
<b css={{color: 'purple'}}>{attribute.name}</b>
)}
</RowHeader>
);
}
if (rowIndex === 0) {
return <ColumnHeader>{type.name}</ColumnHeader>;
}
const row = table.get(attribute);
const result = row.results.get(type.name);
return <Result {...result} />;
}
function saveToLocalStorage(completedHashes) {
const str = JSON.stringify([...completedHashes]);
localStorage.setItem('completedHashes', str);
}
function restoreFromLocalStorage() {
const str = localStorage.getItem('completedHashes');
if (str) {
const completedHashes = new Set(JSON.parse(str));
return completedHashes;
}
return new Set();
}
const useFastMode = /[?&]fast\b/.test(window.location.href);
class App extends React.Component {
state = {
sortOrder: ALPHABETICAL,
filter: ALL,
completedHashes: restoreFromLocalStorage(),
table: null,
rowPatternHashes: null,
};
renderCell = props => {
return (
<div style={props.style}>
<CellContent
toggleAttribute={this.toggleAttribute}
completedHashes={this.state.completedHashes}
table={this.state.table}
attributesInSortedOrder={this.attributes}
{...props}
/>
</div>
);
};
onUpdateSort = e => {
this.setState({sortOrder: e.target.value});
};
onUpdateFilter = e => {
this.setState({filter: e.target.value});
};
toggleAttribute = rowPatternHash => {
const completedHashes = new Set(this.state.completedHashes);
if (completedHashes.has(rowPatternHash)) {
completedHashes.delete(rowPatternHash);
} else {
completedHashes.add(rowPatternHash);
}
this.setState({completedHashes}, () => saveToLocalStorage(completedHashes));
};
async componentDidMount() {
const sources = {
ReactStable: 'https://unpkg.com/react@latest/umd/react.development.js',
ReactDOMStable:
'https://unpkg.com/react-dom@latest/umd/react-dom.development.js',
ReactDOMServerStable:
'https://unpkg.com/react-dom@latest/umd/react-dom-server.browser.development.js',
ReactNext: '/react.development.js',
ReactDOMNext: '/react-dom.development.js',
ReactDOMServerNext: '/react-dom-server.browser.development.js',
};
const codePromises = Object.values(sources).map(src =>
fetch(src).then(res => res.text())
);
const codesByIndex = await Promise.all(codePromises);
const pool = [];
function initGlobals(attribute, type) {
if (useFastMode) {
// Note: this is not giving correct results for warnings.
// But it's much faster.
if (pool[0]) {
return pool[0].globals;
}
} else {
document.title = `${attribute.name} (${type.name})`;
}
// Creating globals for every single test is too slow.
// However caching them between runs won't work for the same attribute names
// because warnings will be deduplicated. As a result, we only share globals
// between different attribute names.
for (let i = 0; i < pool.length; i++) {
if (!pool[i].testedAttributes.has(attribute.name)) {
pool[i].testedAttributes.add(attribute.name);
return pool[i].globals;
}
}
let globals = {};
Object.keys(sources).forEach((name, i) => {
eval.call(window, codesByIndex[i]); // eslint-disable-line
globals[name] = window[name.replace(/Stable|Next/g, '')];
});
// Cache for future use (for different attributes).
pool.push({
globals,
testedAttributes: new Set([attribute.name]),
});
return globals;
}
const {table, rowPatternHashes} = prepareState(initGlobals);
document.title = 'Ready';
this.setState({
table,
rowPatternHashes,
});
}
componentWillUpdate(nextProps, nextState) {
if (
nextState.sortOrder !== this.state.sortOrder ||
nextState.filter !== this.state.filter ||
nextState.completedHashes !== this.state.completedHashes ||
nextState.table !== this.state.table
) {
this.attributes = this.getAttributes(
nextState.table,
nextState.rowPatternHashes,
nextState.sortOrder,
nextState.filter,
nextState.completedHashes
);
if (this.grid) {
this.grid.forceUpdateGrids();
}
}
}
getAttributes(table, rowPatternHashes, sortOrder, filter, completedHashes) {
// Filter
let filteredAttributes;
switch (filter) {
case ALL:
filteredAttributes = attributes.filter(() => true);
break;
case COMPLETE:
filteredAttributes = attributes.filter(attribute => {
const row = table.get(attribute);
return completedHashes.has(row.rowPatternHash);
});
break;
case INCOMPLETE:
filteredAttributes = attributes.filter(attribute => {
const row = table.get(attribute);
return !completedHashes.has(row.rowPatternHash);
});
break;
default:
throw new Error('Switch statement should be exhuastive');
}
// Sort
switch (sortOrder) {
case ALPHABETICAL:
return filteredAttributes.sort(
(attr1, attr2) =>
attr1.name.toLowerCase() < attr2.name.toLowerCase() ? -1 : 1
);
case REV_ALPHABETICAL:
return filteredAttributes.sort(
(attr1, attr2) =>
attr1.name.toLowerCase() < attr2.name.toLowerCase() ? 1 : -1
);
case GROUPED_BY_ROW_PATTERN: {
return filteredAttributes.sort((attr1, attr2) => {
const row1 = table.get(attr1);
const row2 = table.get(attr2);
const patternGroup1 = rowPatternHashes.get(row1.rowPatternHash);
const patternGroupSize1 = (patternGroup1 && patternGroup1.size) || 0;
const patternGroup2 = rowPatternHashes.get(row2.rowPatternHash);
const patternGroupSize2 = (patternGroup2 && patternGroup2.size) || 0;
return patternGroupSize2 - patternGroupSize1;
});
}
default:
throw new Error('Switch statement should be exhuastive');
}
}
handleSaveClick = e => {
e.preventDefault();
if (useFastMode) {
alert(
'Fast mode is not accurate. Please remove ?fast from the query string, and reload.'
);
return;
}
let log = '';
for (let attribute of attributes) {
log += `## \`${attribute.name}\` (on \`<${attribute.tagName ||
'div'}>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`;
log += '| Test Case | Flags | Result |\n';
log += '| --- | --- | --- |\n';
const attributeResults = this.state.table.get(attribute).results;
for (let type of types) {
const {
didError,
didWarn,
canonicalResult,
canonicalDefaultValue,
ssrDidError,
ssrHasSameBehavior,
ssrHasSameBehaviorExceptWarnings,
} = attributeResults.get(type.name).reactNext;
let descriptions = [];
if (canonicalResult === canonicalDefaultValue) {
descriptions.push('initial');
} else {
descriptions.push('changed');
}
if (didError) {
descriptions.push('error');
}
if (didWarn) {
descriptions.push('warning');
}
if (ssrDidError) {
descriptions.push('ssr error');
}
if (!ssrHasSameBehavior) {
if (ssrHasSameBehaviorExceptWarnings) {
descriptions.push('ssr warning');
} else {
descriptions.push('ssr mismatch');
}
}
log +=
`| \`${attribute.name}=(${type.name})\`` +
`| (${descriptions.join(', ')})` +
`| \`${canonicalResult || ''}\` |\n`;
}
log += '\n';
}
const blob = new Blob([log], {type: 'text/plain;charset=utf-8'});
FileSaver.saveAs(blob, 'AttributeTableSnapshot.md');
};
render() {
if (!this.state.table) {
return (
<div>
<h1>Loading...</h1>
{!useFastMode && (
<h3>The progress is reported in the window title.</h3>
)}
</div>
);
}
return (
<div>
<div>
<select value={this.state.sortOrder} onChange={this.onUpdateSort}>
<option value={ALPHABETICAL}>alphabetical</option>
<option value={REV_ALPHABETICAL}>reverse alphabetical</option>
<option value={GROUPED_BY_ROW_PATTERN}>
grouped by row pattern :)
</option>
</select>
<select value={this.state.filter} onChange={this.onUpdateFilter}>
<option value={ALL}>all</option>
<option value={INCOMPLETE}>incomplete</option>
<option value={COMPLETE}>complete</option>
</select>
<button style={{marginLeft: '10px'}} onClick={this.handleSaveClick}>
Save latest results to a file{' '}
<span role="img" aria-label="Save">
💾
</span>
</button>
</div>
<AutoSizer disableHeight={true}>
{({width}) => (
<MultiGrid
ref={input => {
this.grid = input;
}}
cellRenderer={this.renderCell}
columnWidth={200}
columnCount={1 + types.length}
fixedColumnCount={1}
enableFixedColumnScroll={true}
enableFixedRowScroll={true}
height={1200}
rowHeight={40}
rowCount={this.attributes.length + 1}
fixedRowCount={1}
width={width}
/>
)}
</AutoSizer>
</div>
);
}
}
export default App;
|
client/src/app/components/navigation/components/BigBreadcrumbs.js | zraees/sms-project | import React from 'react'
import _ from 'lodash'
// import NavigationStore from '../stores/NavigationStore'
export default class BigBreadcrumbs extends React.Component {
// mixins: [Reflux.listenTo(NavigationStore, 'onNavigationChange')],
constructor(props) {
super(props);
this.state = {
items: this.props.items || [],
icon: this.props.icon || 'fa fa-fw fa-home'
}
}
componentWillMount() {
// if(!this.props.items && NavigationStore.getData().item){
// this.onNavigationChange({
// item: NavigationStore.getData().item
// })
// }
}
onNavigationChange(data) {
let item = data.item;
if (item.route) {
this.state.items = [];
this.state.icon = '';
this._addCrumb(item);
this.forceUpdate()
}
}
_addCrumb(item) {
this.state.items.unshift(item.title)
if (!this.state.icon && item.icon)
this.state.icon = item.icon
if (item.parent)
this._addCrumb(item.parent)
}
render() {
const first = _.head(this.state.items);
return (
<div className={this.props.className + ' big-breadcrumbs'}>
<h1 className="page-title txt-color-blueDark">
<i className={this.state.icon}/>{' ' + first}
{_.tail(this.state.items).map((item) => {
return <span key={_.uniqueId('big-breadcrumb-')}>
<span className="page-title-separator">></span>
{item}</span>
})}
</h1>
</div>
)
}
} |
app/components/Header/components/SessionInfo.js | kme211/srt-maker | import React from 'react';
import getRelativeTimeAgo from '../../../utils/getRelativeTimeAgo';
import styles from './SessionInfo.css';
const SessionInfo = ({ name, status, lastSaved }) => (
<div className={styles.session}>
<div className={styles.session__name}>{name}</div>
<div
className={
lastSaved ? styles.session__saveTime : styles.session__saveTimeDanger
}
>
{lastSaved
? `${status} ${getRelativeTimeAgo(lastSaved)}`
: '*Session has not been saved yet. Ctrl-S to save.'}
</div>
</div>
);
export default SessionInfo;
|
src/components/companies/companies-edit.js | Xabadu/VendOS | import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import { getCompany, updateCompany } from '../../actions/companies';
class CompaniesEdit extends Component {
constructor(props) {
super(props);
this.state = {
success: false
};
}
componentWillMount() {
this.props.getCompany(this.props.params.id);
}
onSubmit(props) {
this.props.updateCompany(props, this.props.companyId)
.then(() => {
this.setState({success: true});
window.scrollTo(0, 0);
});
}
_successAlert() {
if(this.state.success) {
return (
<div className="row">
<div className="col-md-12">
<div className="alert alert-success">
La empresa ha sido editada exitosamente. <Link to='/companies'>Volver al listado de empresas.</Link>
</div>
</div>
</div>
);
}
}
render() {
const { fields: { name }, handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<div className="page-breadcrumb">
<ol className="breadcrumb container">
<li><Link to='/'>Inicio</Link></li>
<li><a href="#">Empresas</a></li>
<li className="active">Actualizar Empresa</li>
</ol>
</div>
<div className="page-title">
<div className="container">
<h3>Actualizar Empresa</h3>
</div>
</div>
<div id="main-wrapper" className="container">
{this._successAlert()}
<div className="row">
<div className="col-md-6">
<div className="panel panel-white">
<div className="panel-heading clearfix">
<h4 className="panel-title">Información general</h4>
</div>
<div className="panel-body">
<div className="form-group">
<label for="input-Default" className="control-label">Nombre</label>
<input type="text" className={`form-control ${name.touched && name.invalid ? 'b-error' : ''}`} id="input-Default" placeholder="Nombre" {...name} />
<span className="text-danger">{name.touched ? name.error : ''}</span>
</div>
</div>
</div>
</div>
<div className="col-md-6">
</div>
<div className="col-md-6">
</div>
<div className="col-md-12">
<div className="panel panel-white">
<div className="panel-body">
<button type="submit" className="btn btn-info left">Actualizar empresa</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
);
}
}
function validate(values) {
const errors = {};
if(!values.name) {
errors.name = 'Ingresa un nombre';
}
return errors;
}
function mapStateToProps(state) {
return {
initialValues: state.companies.companyDetail,
companyId: state.companies.companyId
};
}
export default reduxForm({
form: 'EditCompanyForm',
fields: ['name'],
validate
}, mapStateToProps, { getCompany, updateCompany })(CompaniesEdit);
|
react-flux-mui/js/material-ui/src/svg-icons/action/verified-user.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionVerifiedUser = (props) => (
<SvgIcon {...props}>
<path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm-2 16l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z"/>
</SvgIcon>
);
ActionVerifiedUser = pure(ActionVerifiedUser);
ActionVerifiedUser.displayName = 'ActionVerifiedUser';
ActionVerifiedUser.muiName = 'SvgIcon';
export default ActionVerifiedUser;
|
nailgun/static/views/cluster_page.js | huntxu/fuel-web | /*
* Copyright 2015 Mirantis, Inc.
*
* Licensed under the Apache License, Version 2.0 (the 'License'); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
import $ from 'jquery';
import _ from 'underscore';
import i18n from 'i18n';
import React from 'react';
import utils from 'utils';
import models from 'models';
import dispatcher from 'dispatcher';
import {backboneMixin, pollingMixin, dispatcherMixin} from 'component_mixins';
import DashboardTab from 'views/cluster_page_tabs/dashboard_tab';
import NodesTab from 'views/cluster_page_tabs/nodes_tab';
import NetworkTab from 'views/cluster_page_tabs/network_tab';
import SettingsTab from 'views/cluster_page_tabs/settings_tab';
import LogsTab from 'views/cluster_page_tabs/logs_tab';
import HealthCheckTab from 'views/cluster_page_tabs/healthcheck_tab';
import {VmWareTab, VmWareModels} from 'plugins/vmware/vmware';
var ClusterPage = React.createClass({
mixins: [
pollingMixin(5),
backboneMixin('cluster', 'change:name change:is_customized change:release'),
backboneMixin({
modelOrCollection: (props) => props.cluster.get('nodes')
}),
backboneMixin({
modelOrCollection: (props) => props.cluster.get('tasks'),
renderOn: 'update change'
}),
dispatcherMixin('networkConfigurationUpdated', 'removeFinishedNetworkTasks'),
dispatcherMixin('deploymentTasksUpdated', 'removeFinishedDeploymentTasks'),
dispatcherMixin('deploymentTaskStarted', function() {
this.refreshCluster().always(this.startPolling);
}),
dispatcherMixin('networkVerificationTaskStarted', function() {
this.startPolling();
}),
dispatcherMixin('deploymentTaskFinished', function() {
this.refreshCluster().always(() => dispatcher.trigger('updateNotifications'));
})
],
statics: {
navbarActiveElement: 'clusters',
breadcrumbsPath(pageOptions) {
var cluster = pageOptions.cluster;
var tabOptions = pageOptions.tabOptions[0];
var addScreenBreadcrumb = tabOptions && tabOptions.match(/^(?!list$)\w+$/);
var breadcrumbs = [
['home', '#'],
['environments', '#clusters'],
[cluster.get('name'), '#cluster/' + cluster.get('id'), {skipTranslation: true}],
[i18n('cluster_page.tabs.' + pageOptions.activeTab), '#cluster/' + cluster.get('id') + '/' + pageOptions.activeTab, {active: !addScreenBreadcrumb}]
];
if (addScreenBreadcrumb) {
breadcrumbs.push([i18n('cluster_page.nodes_tab.breadcrumbs.' + tabOptions), null, {active: true}]);
}
return breadcrumbs;
},
title(pageOptions) {
return pageOptions.cluster.get('name');
},
getTabs() {
return [
{url: 'dashboard', tab: DashboardTab},
{url: 'nodes', tab: NodesTab},
{url: 'network', tab: NetworkTab},
{url: 'settings', tab: SettingsTab},
{url: 'vmware', tab: VmWareTab},
{url: 'logs', tab: LogsTab},
{url: 'healthcheck', tab: HealthCheckTab}
];
},
fetchData(id, activeTab, ...tabOptions) {
var cluster, promise, currentClusterId;
var nodeNetworkGroups = app.nodeNetworkGroups;
var tab = _.find(this.getTabs(), {url: activeTab}).tab;
try {
currentClusterId = app.page.props.cluster.id;
} catch (ignore) {}
if (currentClusterId == id) {
// just another tab has been chosen, do not load cluster again
cluster = app.page.props.cluster;
promise = tab.fetchData ? tab.fetchData({cluster: cluster, tabOptions: tabOptions}) : $.Deferred().resolve();
} else {
cluster = new models.Cluster({id: id});
var settings = new models.Settings();
settings.url = _.result(cluster, 'url') + '/attributes';
cluster.set({settings: settings});
var roles = new models.Roles();
roles.url = _.result(cluster, 'url') + '/roles';
cluster.set({roles: roles});
var pluginLinks = new models.PluginLinks();
pluginLinks.url = _.result(cluster, 'url') + '/plugin_links';
cluster.set({pluginLinks: pluginLinks});
cluster.get('nodes').fetch = function(options) {
return this.constructor.__super__.fetch.call(this, _.extend({data: {cluster_id: id}}, options));
};
promise = $.when(
cluster.fetch(),
cluster.get('settings').fetch(),
cluster.get('roles').fetch(),
cluster.get('pluginLinks').fetch({cache: true}),
cluster.fetchRelated('nodes'),
cluster.fetchRelated('tasks'),
nodeNetworkGroups.fetch({cache: true})
)
.then(() => {
var networkConfiguration = new models.NetworkConfiguration();
networkConfiguration.url = _.result(cluster, 'url') + '/network_configuration/' + cluster.get('net_provider');
cluster.set({
networkConfiguration: networkConfiguration,
release: new models.Release({id: cluster.get('release_id')})
});
return $.when(cluster.get('networkConfiguration').fetch(), cluster.get('release').fetch());
})
.then(() => {
var useVcenter = cluster.get('settings').get('common.use_vcenter.value');
if (!useVcenter) {
return true;
}
var vcenter = new VmWareModels.VCenter({id: id});
cluster.set({vcenter: vcenter});
return vcenter.fetch();
})
.then(() => {
return tab.fetchData ? tab.fetchData({cluster: cluster, tabOptions: tabOptions}) : $.Deferred().resolve();
});
}
return promise.then((data) => {
return {
cluster: cluster,
nodeNetworkGroups: nodeNetworkGroups,
activeTab: activeTab,
tabOptions: tabOptions,
tabData: data
};
});
}
},
getDefaultProps() {
return {
defaultLogLevel: 'INFO'
};
},
getInitialState() {
return {
activeSettingsSectionName: this.pickDefaultSettingGroup(),
activeNetworkSectionName: this.props.nodeNetworkGroups.find({is_default: true}).get('name'),
selectedNodeIds: {},
selectedLogs: {type: 'local', node: null, source: 'app', level: this.props.defaultLogLevel}
};
},
removeFinishedNetworkTasks(callback) {
var request = this.removeFinishedTasks(this.props.cluster.tasks({group: 'network'}));
if (callback) request.always(callback);
return request;
},
removeFinishedDeploymentTasks() {
return this.removeFinishedTasks(this.props.cluster.tasks({group: 'deployment'}));
},
removeFinishedTasks(tasks) {
var requests = [];
_.each(tasks, (task) => {
if (task.match({active: false})) {
this.props.cluster.get('tasks').remove(task);
requests.push(task.destroy({silent: true}));
}
});
return $.when(...requests);
},
shouldDataBeFetched() {
return this.props.cluster.task({group: ['deployment', 'network'], active: true});
},
fetchData() {
var task = this.props.cluster.task({group: 'deployment', active: true});
if (task) {
return task.fetch()
.done(() => {
if (task.match({active: false})) dispatcher.trigger('deploymentTaskFinished');
})
.then(() =>
this.props.cluster.fetchRelated('nodes')
);
} else {
task = this.props.cluster.task({name: 'verify_networks', active: true});
return task ? task.fetch() : $.Deferred().resolve();
}
},
refreshCluster() {
return $.when(
this.props.cluster.fetch(),
this.props.cluster.fetchRelated('nodes'),
this.props.cluster.fetchRelated('tasks'),
this.props.cluster.get('pluginLinks').fetch()
);
},
componentWillMount() {
this.props.cluster.on('change:release_id', () => {
var release = new models.Release({id: this.props.cluster.get('release_id')});
release.fetch().done(() => {
this.props.cluster.set({release: release});
});
});
this.updateLogSettings();
},
componentWillReceiveProps(newProps) {
this.updateLogSettings(newProps);
},
updateLogSettings(props) {
props = props || this.props;
// FIXME: the following logs-related logic should be moved to Logs tab code
// to keep parent component tightly coupled to its children
if (props.activeTab == 'logs') {
var selectedLogs;
if (props.tabOptions[0]) {
selectedLogs = utils.deserializeTabOptions(_.compact(props.tabOptions).join('/'));
selectedLogs.level = selectedLogs.level ? selectedLogs.level.toUpperCase() : props.defaultLogLevel;
this.setState({selectedLogs: selectedLogs});
}
}
},
changeLogSelection(selectedLogs) {
this.setState({selectedLogs: selectedLogs});
},
getAvailableTabs(cluster) {
return _.filter(this.constructor.getTabs(),
(tabData) => !tabData.tab.isVisible || tabData.tab.isVisible(cluster));
},
pickDefaultSettingGroup() {
return _.first(this.props.cluster.get('settings').getGroupList());
},
setActiveSettingsGroupName(value) {
if (_.isUndefined(value)) value = this.pickDefaultSettingGroup();
this.setState({activeSettingsSectionName: value});
},
setActiveNetworkSectionName(name) {
this.setState({activeNetworkSectionName: name});
},
selectNodes(ids, checked) {
if (ids && ids.length) {
var nodeSelection = this.state.selectedNodeIds;
_.each(ids, (id) => {
if (checked) {
nodeSelection[id] = true;
} else {
delete nodeSelection[id];
}
});
this.setState({selectedNodeIds: nodeSelection});
} else {
this.setState({selectedNodeIds: {}});
}
},
render() {
var cluster = this.props.cluster;
var availableTabs = this.getAvailableTabs(cluster);
var tabUrls = _.pluck(availableTabs, 'url');
var tab = _.find(availableTabs, {url: this.props.activeTab});
if (!tab) return null;
var Tab = tab.tab;
return (
<div className='cluster-page' key={cluster.id}>
<div className='page-title'>
<h1 className='title'>
{cluster.get('name')}
<div className='title-node-count'>({i18n('common.node', {count: cluster.get('nodes').length})})</div>
</h1>
</div>
<div className='tabs-box'>
<div className='tabs'>
{tabUrls.map((url) => {
return (
<a
key={url}
className={url + ' ' + utils.classNames({'cluster-tab': true, active: this.props.activeTab == url})}
href={'#cluster/' + cluster.id + '/' + url}
>
<div className='icon'></div>
<div className='label'>{i18n('cluster_page.tabs.' + url)}</div>
</a>
);
})}
</div>
</div>
<div key={tab.url + cluster.id} className={'content-box tab-content ' + tab.url + '-tab'}>
<Tab
ref='tab'
cluster={cluster}
nodeNetworkGroups={this.props.nodeNetworkGroups}
tabOptions={this.props.tabOptions}
setActiveSettingsGroupName={this.setActiveSettingsGroupName}
setActiveNetworkSectionName={this.setActiveNetworkSectionName}
selectNodes={this.selectNodes}
changeLogSelection={this.changeLogSelection}
{...this.state}
{...this.props.tabData}
/>
</div>
</div>
);
}
});
export default ClusterPage;
|
config/routes.js | dkfann/cinesythesia | import React from 'react';
import {Route, Router, IndexRoute, hashHistory} from 'react-router';
import MainContainer from '../containers/MainContainer';
import HomeContainer from '../containers/HomeContainer';
export default (
<Router history={hashHistory}>
<Route path="/" component={ MainContainer }>
<IndexRoute component={ HomeContainer }/>
</Route>
</Router>
);
|
mobile/Simplenote/src/components/screen-activity-indicator.js | abhaydgarg/Simplenote | import React from 'react';
import PropTypes from 'prop-types';
import { ActivityIndicator, View } from 'react-native';
const ScreenActivityIndicator = (props) => {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator
animating
color={props.color}
size='large'
/>
</View>
);
};
ScreenActivityIndicator.defaultProps = {
color: 'black'
};
ScreenActivityIndicator.propTypes = {
color: PropTypes.string
};
export default ScreenActivityIndicator;
|
ui/js/components/Image.js | ericsoderberg/pbc-web | import React from 'react';
import PropTypes from 'prop-types';
const Image = (props) => {
const { avatar, className, full, image, style } = props;
const classes = ['image'];
if (avatar) {
classes.push('image--avatar');
}
if (full) {
classes.push('image--full');
}
if (className) {
classes.push(className);
}
return (
<img className={classes.join(' ')}
alt=""
src={image ? (image.data || image.path) : ''}
style={style} />
);
};
Image.propTypes = {
avatar: PropTypes.bool,
className: PropTypes.string,
full: PropTypes.bool,
image: PropTypes.shape({
data: PropTypes.string,
}),
style: PropTypes.object,
};
Image.defaultProps = {
avatar: false,
className: undefined,
full: false,
image: {},
style: undefined,
};
export default Image;
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/data/ScopeValidation.js | thusithak/carbon-apimgt | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
"use strict";
import React from 'react';
import AuthManager from './AuthManager'
import {Button} from 'antd'
const resourcePath = {
APIS : "/apis",
SINGLE_API :"/apis/{apiId}",
API_SWAGGER : "/apis/{apiId}/swagger",
API_WSDL : "/apis/{apiId}/wsdl",
API_GW_CONFIG : "/apis/{apiId}/gateway-config",
API_THUMBNAIL : "/apis/{apiId}/thumbnail",
API_COPY : "/apis/copy-api",
API_LC_HISTORY : "/apis/{apiId}/lifecycle-history",
API_CHANGE_LC : "/apis/change-lifecycle",
API_LC : "/apis/{apiId}/lifecycle",
API_LC_PENDING_TASK : "/apis/{apiId}/lifecycle/lifecycle-pending-task",
API_DEF : "/apis/import-definition",
API_VALIDATE_DEF : "/apis/validate-definition",
API_DOCS : "/apis/{apiId}/documents",
API_DOC : "'/apis/{apiId}/documents/{documentId}'",
API_DOC_CONTENT : "'/apis/{apiId}/documents/{documentId}/content'",
EXPORT_APIS : "/export/apis",
IMPORT_APIS : "/import/apis",
SUBSCRIPTION : "/subscriptions",
SUBSCRIPTIONS : "/subscriptions",
BLOCK_SUBSCRIPTION : "/subscriptions/block-subscription:",
UNBLOCK_SUBSCRIPTION : "/subscriptions/unblock-subscription",
POLICIES : "'/policies/{tierLevel}'",
POLICY : "'/policies/{tierLevel}/{tierName}'",
ENDPOINTS : "/endpoints",
ENDPOINT : "/endpoints/{endpointId}",
LABLES : "/labels",
WORKFLOW : "/workflows/{workflowReferenceId}"
};
const resourceMethod = {
POST : "post",
PUT : "put",
GET : "get",
DELETE : "delete"
}
class ScopeValidation extends React.Component {
constructor(props){
super(props);
this.state = {};
}
componentDidMount(){
let hasScope = AuthManager.hasScopes(this.props.resourcePath, this.props.resourceMethod);
hasScope.then(haveScope => {this.setState({haveScope: haveScope})})
}
render() {
if(this.state.haveScope) {
return (this.props.children);
}
return null;
}
}
module.exports = {
ScopeValidation,
resourceMethod,
resourcePath
} |
app/components/About.js | kdemoya/seriesly | import React, { Component } from 'react';
import { Text, View } from 'react-native';
class About extends Component {
static navigationOptions = {
title: 'About',
};
render() {
return (
<View>
<Text>
This is an awesome app!
Nothing to watch here... Yet.
</Text>
</View>
);
}
}
export default About;
|
node_modules/@material-ui/core/esm/Breadcrumbs/BreadcrumbSeparator.js | pcclarke/civ-techs | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
var styles = {
root: {
display: 'flex',
userSelect: 'none',
marginLeft: 8,
marginRight: 8
}
};
/**
* @ignore - internal component.
*/
function BreadcrumbSeparator(props) {
var classes = props.classes,
className = props.className,
other = _objectWithoutProperties(props, ["classes", "className"]);
return React.createElement("li", _extends({
"aria-hidden": true,
className: clsx(classes.root, className)
}, other));
}
process.env.NODE_ENV !== "production" ? BreadcrumbSeparator.propTypes = {
children: PropTypes.node.isRequired,
classes: PropTypes.object.isRequired,
className: PropTypes.string
} : void 0;
export default withStyles(styles, {
name: 'PrivateBreadcrumbSeparator'
})(BreadcrumbSeparator); |
DevTools.js | mattkrick/redux-operations-counter-example | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'>
<LogMonitor />
</DockMonitor>
);
|
blueocean-material-icons/src/js/components/svg-icons/action/settings-ethernet.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionSettingsEthernet = (props) => (
<SvgIcon {...props}>
<path d="M7.77 6.76L6.23 5.48.82 12l5.41 6.52 1.54-1.28L3.42 12l4.35-5.24zM7 13h2v-2H7v2zm10-2h-2v2h2v-2zm-6 2h2v-2h-2v2zm6.77-7.52l-1.54 1.28L20.58 12l-4.35 5.24 1.54 1.28L23.18 12l-5.41-6.52z"/>
</SvgIcon>
);
ActionSettingsEthernet.displayName = 'ActionSettingsEthernet';
ActionSettingsEthernet.muiName = 'SvgIcon';
export default ActionSettingsEthernet;
|
app/javascript/mastodon/components/column.js | nonoz/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import detectPassiveEvents from 'detect-passive-events';
import { scrollTop } from '../scroll';
export default class Column extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
};
scrollTop () {
const scrollable = this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = c => {
this.node = c;
}
componentDidMount () {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents ? { passive: true } : false);
}
componentWillUnmount () {
this.node.removeEventListener('wheel', this.handleWheel);
}
render () {
const { children } = this.props;
return (
<div role='region' className='column' ref={this.setRef}>
{children}
</div>
);
}
}
|
milestones/05-webpack-intro-css/After/src/index.js | jaketrent/react-drift | import React from 'react'
import ReactDOM from 'react-dom'
import DriftApp from './app.js'
ReactDOM.render(<DriftApp />, document.getElementById('app'))
|
src/svg-icons/toggle/radio-button-checked.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ToggleRadioButtonChecked = (props) => (
<SvgIcon {...props}>
<path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/>
</SvgIcon>
);
ToggleRadioButtonChecked = pure(ToggleRadioButtonChecked);
ToggleRadioButtonChecked.displayName = 'ToggleRadioButtonChecked';
export default ToggleRadioButtonChecked;
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/DestructuringAndAwait.js | andrewmaudsley/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
async function load() {
return {
users: [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
],
};
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const { users } = await load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-destructuring-and-await">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
components/react-semantify/src/collections/table.js | react-douban/douban-book-web | import React from 'react';
import ClassGenerator from '../mixins/classGenerator';
let defaultClassName = 'ui table';
const Table = React.createClass({
mixins: [ClassGenerator],
render: function () {
let {className, ...other} = this.props;
return (
<table {...other} className={this.getClassName(defaultClassName)} >
{this.props.children}
</table>
);
}
});
export default Table;
|
packages/vx-glyph/src/glyphs/Square.js | Flaque/vx | import React from 'react';
import cx from 'classnames';
import { symbol, symbolSquare } from 'd3-shape';
import Glyph from './Glyph';
import additionalProps from '../util/additionalProps';
export default function GlyphSquare({
children,
className,
top,
left,
size,
...restProps
}) {
const path = symbol();
path.type(symbolSquare);
if (size) path.size(size);
return (
<Glyph top={top} left={left}>
<path
className={cx('vx-glyph-square', className)}
d={path()}
{...additionalProps(restProps)}
/>
{children}
</Glyph>
);
}
|
src/svg-icons/device/access-alarm.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceAccessAlarm = (props) => (
<SvgIcon {...props}>
<path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
</SvgIcon>
);
DeviceAccessAlarm = pure(DeviceAccessAlarm);
DeviceAccessAlarm.displayName = 'DeviceAccessAlarm';
DeviceAccessAlarm.muiName = 'SvgIcon';
export default DeviceAccessAlarm;
|
src/svg-icons/social/sentiment-very-satisfied.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSentimentVerySatisfied = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-10.06L14.06 11l1.06-1.06L16.18 11l1.06-1.06-2.12-2.12zm-4.12 0L9.94 11 11 9.94 8.88 7.82 6.76 9.94 7.82 11zM12 17.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</SvgIcon>
);
SocialSentimentVerySatisfied = pure(SocialSentimentVerySatisfied);
SocialSentimentVerySatisfied.displayName = 'SocialSentimentVerySatisfied';
SocialSentimentVerySatisfied.muiName = 'SvgIcon';
export default SocialSentimentVerySatisfied;
|
examples/week.js | react-component/calendar | /* eslint react/no-multi-comp:0, no-console:0 */
import '../assets/index.less';
import React from 'react';
import moment from 'moment';
import Calendar from '../src';
import DatePicker from '../src/Picker';
import zhCN from '../src/locale/zh_CN';
import enUS from '../src/locale/en_US';
import 'moment/locale/zh-cn';
import 'moment/locale/en-gb';
const format = 'YYYY-Wo';
const cn = window.location.search.indexOf('cn') !== -1;
const now = moment();
if (cn) {
now.locale('zh-cn').utcOffset(8);
} else {
now.locale('en-gb').utcOffset(0);
}
const style = `
.week-calendar {
width: 386px;
}
.week-calendar .rc-calendar-tbody > tr:hover
.rc-calendar-date {
background: #ebfaff;
}
.week-calendar .rc-calendar-tbody > tr:hover
.rc-calendar-selected-day .rc-calendar-date {
background: #3fc7fa;
}
.week-calendar .week-calendar-sidebar {
position:absolute;
top:0;
left:0;
bottom:0;
width:100px;
border-right: 1px solid #ccc;
}
.week-calendar .rc-calendar-panel {
margin-left: 100px;
}
`;
class Demo extends React.Component {
state = {
value: undefined,
open: false,
};
onChange = value => {
console.log('DatePicker change: ', value && value.format(format));
this.setState({
value,
});
};
onOpenChange = open => {
this.setState({
open,
});
};
dateRender = current => {
const selectedValue = this.state.value;
if (
selectedValue &&
current.year() === selectedValue.year() &&
current.week() === selectedValue.week()
) {
return (
<div className="rc-calendar-selected-day">
<div className="rc-calendar-date">{current.date()}</div>
</div>
);
}
return <div className="rc-calendar-date">{current.date()}</div>;
};
lastWeek = () => {
const { state } = this;
const value = state.value || now;
value.add(-1, 'weeks');
this.setState({
value,
open: false,
});
};
renderSidebar = () => (
<div className="week-calendar-sidebar" key="sidebar">
<button onClick={() => this.lastWeek()} type="button" style={{ margin: 20 }}>
上一周
</button>
</div>
);
render() {
const { state } = this;
const calendar = (
<Calendar
className="week-calendar"
showWeekNumber
renderSidebar={this.renderSidebar}
dateRender={this.dateRender}
locale={cn ? zhCN : enUS}
format={format}
style={{ zIndex: 1000 }}
dateInputPlaceholder="please input"
defaultValue={now}
showDateInput
/>
);
return (
<div style={{ width: 400, margin: 20 }}>
<div
style={{
boxSizing: 'border-box',
position: 'relative',
display: 'block',
lineHeight: 1.5,
marginBottom: 22,
}}
>
<DatePicker
onOpenChange={this.onOpenChange}
open={this.state.open}
animation="slide-up"
calendar={calendar}
value={state.value}
onChange={this.onChange}
>
{({ value }) => (
<span tabIndex="0">
<input
placeholder="please select week"
style={{ width: 250 }}
disabled={state.disabled}
readOnly
tabIndex="-1"
className="ant-calendar-picker-input ant-input"
value={(value && value.format(format)) || ''}
/>
</span>
)}
</DatePicker>
</div>
</div>
);
}
}
export default () => (
<div
style={{
zIndex: 1000,
position: 'relative',
width: 900,
margin: '20px auto',
}}
>
<style dangerouslySetInnerHTML={{ __html: style }} />
<div>
<Demo />
</div>
</div>
);
|
app/components/Work/ToolsSection/index.js | yasserhennawi/yasserhennawi | import React from 'react';
import PropTypes from 'prop-types';
import styled from 'utils/styled-components';
import WorkSection from '../WorkSection';
import Tool from '../Tool';
const StyledTool = styled(Tool)`
margin: 10px 20px 0 0;
`;
const ToolsWrapper = styled.div`
display: flex;
flex-wrap: wrap;
`;
const getTools = (tools, toolsBgColor, width, secondary) => (
<ToolsWrapper>
{tools.map((tool, index) => (
<StyledTool
bgColor={toolsBgColor}
key={index}
padding={tool.padding}
secondary={secondary}
width={width}
name={tool.name}
logoImage={tool.logoImage}
logo={tool.logo}
/>
))}
</ToolsWrapper>
);
const ToolsSection = ({ toolsBgColor, secondary, tools, width }) => (
<WorkSection title="Tools">
{getTools(tools, toolsBgColor, width, secondary)}
</WorkSection>
);
ToolsSection.propTypes = {
toolsBgColor: PropTypes.string,
secondary: PropTypes.bool,
tools: PropTypes.array,
width: PropTypes.string,
};
export default ToolsSection;
|
src/components/Surrounder.js | codeforboston/cliff-effects | import React from 'react';
const Surrounder = function ({ Top, Left, Right, Bottom, children }) {
let contents = { top: null, left: null, right: null, bottom: null };
if (Top) {
contents.top = (<div className={ `top horizontal` }>{ Top }</div>);
}
if (Left) {
contents.left = (<div className={ `left vertical` }>{ Left }</div>);
}
if (Right) {
contents.right = (<div className={ `right vertical` }>{ Right }</div>);
}
if (Bottom) {
contents.bottom = (<div className={ `bottom horizontal` }>{ Bottom }</div>);
}
return (
<div className={ `surrounder` }>
{ contents.top }
<div className={ `middle horizontal` }>
{ contents.left }
<div className={ `center horizontal content` }>
{ children }
</div>
{ contents.right }
</div>
{ contents.bottom }
</div>
);
}; // Ends <Surrounder>
export { Surrounder };
|
src/components/App.js | sivael/simpleBlogThingie | import React from 'react'
import Header from 'components/Header'
import { Link } from 'react-router'
class App extends React.Component {
render() {
return (
<div>
<Header />
{ this.props.children }
</div>
)
}
}
export default App;
|
app-course-sync/containers/PageContainer.js | globant-ui-rosario/progress-tracker | import React, { Component } from 'react';
class PageContainer extends Component {
render () {
return (
<div>{this.props.children}</div>
);
}
};
export default PageContainer;
|
src/components/searchbar.js | ShaneFairweather/React-iTunes | import React, { Component } from 'react';
export default class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' }
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(term) {
this.setState({term})
this.props.getResults(term);
}
render() {
return (
<div className='searchBarContainer'>
<input type='text'
value={this.state.term}
onChange={event => this.onInputChange(event.target.value)}
/>
</div>
)
}
}
{/*<button><i id="searchIcon" className="fa fa-search" /></button>*/}
|
src/resources/assets/react-app/components/PreHeader.js | darrenmerrett/ruf | import React, { Component } from 'react';
class PreHeader extends Component {
render() {
return null;
}
}
export default PreHeader;
|
src/components/TabIcon.js | phodal/growth-ng | import React from 'react';
import PropTypes from 'prop-types';
import { View, Text } from 'react-native';
import { Icon } from 'react-native-elements';
import AppColors from '../theme/colors';
class TabIcon extends React.Component {
componentName = 'TabIcon';
render() {
return (
<View>
<Icon name={this.props.iconName} type={this.props.iconType} color={this.props.selected ? AppColors.brand.primary : '#767676'} />
<Text style={{ color: this.props.selected ? AppColors.brand.primary : '#767676' }}>{this.props.title}</Text>
</View>
);
}
}
TabIcon.propTypes = {
title: PropTypes.string.isRequired,
selected: PropTypes.bool,
iconName: PropTypes.string.isRequired,
iconType: PropTypes.string.isRequired };
TabIcon.defaultProps = { title: 'Home', selected: false, iconName: 'md-home', iconType: 'ionicon' };
export default TabIcon;
|
pages/product.js | NigelEarle/SSR-shopping | import React, { Component } from 'react';
import { Provider } from 'mobx-react';
import { initProductStore } from '../store/product';
import { SingleProduct } from '../components';
class Product extends Component {
static async getInitialProps(context) {
const isServer = !!context.req;
const store = initProductStore(isServer);
await store.fetchSingleProduct(parseInt(context.query.id));
return {
products: store.products,
singleProduct: store.singleProduct,
error: store.error,
isServer,
}
}
constructor(props) {
super(props);
this.store = initProductStore(
props.isServer,
props.products,
props.singleProduct,
props.error
);
}
render() {
return (
<Provider productStore={this.store}>
<SingleProduct />
</Provider>
);
}
};
export default Product; |
src/Table.js | kwnccc/react-bootstrap | import React from 'react';
import classNames from 'classnames';
const Table = React.createClass({
propTypes: {
striped: React.PropTypes.bool,
bordered: React.PropTypes.bool,
condensed: React.PropTypes.bool,
hover: React.PropTypes.bool,
responsive: React.PropTypes.bool
},
getDefaultProps() {
return {
bordered: false,
condensed: false,
hover: false,
responsive: false,
striped: false
};
},
render() {
let classes = {
'table': true,
'table-striped': this.props.striped,
'table-bordered': this.props.bordered,
'table-condensed': this.props.condensed,
'table-hover': this.props.hover
};
let table = (
<table {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</table>
);
return this.props.responsive ? (
<div className="table-responsive">
{table}
</div>
) : table;
}
});
export default Table;
|
demo/src/demo-components/user-list.js | Strikersoft/striker-store | import React from 'react';
import { shape, func, number, arrayOf } from 'prop-types';
import { observer } from 'mobx-react';
import Status from './indicators';
import UserItem from './user-item';
const UserList = observer(({ users, isReloading, isLoading, ...rest }) => (
<div>
{users.map(
user => (
<UserItem
key={user.id}
user={user}
{...rest}
/>
)
)}
{isReloading ? <Status indicator={isReloading} type="Reloading..." /> : null}
{isLoading ? <Status indicator={isLoading} type="Loading..." /> : null}
</div>
));
UserList.propTypes = {
users: arrayOf(
shape({ id: number })
).isRequired,
isReloading: shape({
get: func,
set: func
}),
isLoading: shape({
get: func,
set: func
})
};
UserList.displayName = 'UserList';
export default UserList;
|
src/components/shared/import-geometry/import-geometry.component.js | GeoTIFF/geotiff.io | import React from 'react';
const ImportGeometryComponent = ({ geometry, importGeometry }) => (
<div className='import-geojson'>
<p>Import Geometry from file</p>
<div className='content-row'>
<label
className='gt-button-secondary'
htmlFor="import-geojson-input"
>
Import GeoJSON
</label>
<input
id='import-geojson-input'
type='file'
className='gt-input'
onChange={importGeometry}
/>
</div>
</div>
);
export default ImportGeometryComponent;
|
exemplos/ExemploMenuItem.js | vitoralvesdev/react-native-componentes | import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity
} from 'react-native';
import { MenuItem } from 'react-native-componentes';
const ITENS = [
{nome: 'Criar'},
{nome: 'Atualizar'},
{nome: 'Deletar'},
]
export default class ExemploMenuItem extends Component {
constructor(props) {
super(props);
this.state = {
abrirMenu: false
}
}
_itemSelecionado(item) {
console.log(item)
this.setState({ abrirMenu: false })
}
render() {
return(
<View style={estilos.corpo}>
<MenuItem
visivel={this.state.abrirMenu}
fechar={()=>this.setState({ abrirMenu: false })}
itens={ITENS}
itemSelecionado={(item)=>this._itemSelecionado(item)}
/>
<TouchableOpacity onPress={()=>this.setState({ abrirMenu: true })}>
<Text style={estilos.titulo}>
Abrir o Menu
</Text>
</TouchableOpacity>
</View>
)
}
}
const estilos = StyleSheet.create({
corpo : {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
titulo : {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
}
})
|
src/svg-icons/content/drafts.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentDrafts = (props) => (
<SvgIcon {...props}>
<path d="M21.99 8c0-.72-.37-1.35-.94-1.7L12 1 2.95 6.3C2.38 6.65 2 7.28 2 8v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2l-.01-10zM12 13L3.74 7.84 12 3l8.26 4.84L12 13z"/>
</SvgIcon>
);
ContentDrafts = pure(ContentDrafts);
ContentDrafts.displayName = 'ContentDrafts';
ContentDrafts.muiName = 'SvgIcon';
export default ContentDrafts;
|
components/link/Link.js | showings/react-toolbox | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { themr } from 'react-css-themr';
import { LINK } from '../identifiers';
import { FontIcon } from '../font_icon/FontIcon';
const Link = ({ active, children, className, count, icon, label, theme, ...others }) => {
const _className = classnames(theme.link, {
[theme.active]: active,
}, className);
return (
<a data-react-toolbox="link" className={_className} {...others}>
{icon ? <FontIcon className={theme.icon} value={icon} /> : null}
{label ? <abbr>{label}</abbr> : null}
{count && parseInt(count, 10) !== 0 ? <small>{count}</small> : null}
{children}
</a>
);
};
Link.propTypes = {
active: PropTypes.bool,
children: PropTypes.node,
className: PropTypes.string,
count: PropTypes.number,
icon: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
label: PropTypes.string,
theme: PropTypes.shape({
active: PropTypes.string,
icon: PropTypes.string,
link: PropTypes.string,
}),
};
Link.defaultProps = {
active: false,
className: '',
};
export default themr(LINK)(Link);
export { Link };
|
lib/Components/IdeaInput.js | DanGrund/Daily-Bullet | import React from 'react';
export default class IdeaInput extends React.Component{
constructor(props){
super(props);
this.state = {
newTask: {value: ''},
}
}
handleChange(e){
let task = this.state.newTask
task.value = e.target.value
this.setState({newTask: task})
}
handleSave(){
this.props.saveNewTask(this.state.newTask);
this.setState({newTask: {value: ''}})
}
render(){
return(
<div>
<input className = "journalInput"
value={this.state.newTask.value}
onChange={(e) => this.handleChange(e)}
placeholder="write down yo' task"
></input>
<button
className = "saveButton"
disabled={!this.state.newTask.value}
onClick={()=> this.handleSave()}>Save</button>
</div>
)
}
}
|
app/views/STF/Voting/Panels/Vote/Vote.js | RcKeller/STF-Refresh | import React from 'react'
import PropTypes from 'prop-types'
import { compose, bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { Form, Alert, Switch, Button, message } from 'antd'
const FormItem = Form.Item
const connectForm = Form.create()
import { layout } from '../../../../../util/form'
import api from '../../../../../services'
import { makeManifestByID, makeManifestReview } from '../../../../../selectors'
import { Loading } from '../../../../../components'
/*
VOTE PANEL:
Allows members to cast their FINAL, OVERALL VOTES
NOTE: The requirements for voting changed at the end of the project,
so this is slightly unintuitive. Please refactor when bandwith is avail.
*/
@compose(
connect(
(state, props) => {
const manifest = makeManifestByID(props.id)(state)
const review = makeManifestReview(manifest)(state) || {}
const { docket, proposal } = manifest
return {
review,
manifest: manifest._id,
author: state.user._id,
active: docket.voting,
proposal: proposal._id
// review: reviews
// .find(review => review.author._id === state.user._id) || {},
}
},
dispatch => ({ api: bindActionCreators(api, dispatch) })
),
connectForm
)
class Vote extends React.Component {
static propTypes = {
form: PropTypes.object,
api: PropTypes.object,
id: PropTypes.string.isRequired,
proposal: PropTypes.string,
review: PropTypes.object,
manifest: PropTypes.string,
author: PropTypes.string
}
componentDidMount () {
const { form, review } = this.props
if (form && review) {
// Consistent fields
let { approved } = review
if (typeof approved === 'undefined') approved = false
form.setFieldsValue({ approved })
}
}
handleSubmit = (e) => {
e.preventDefault()
let { form, api, proposal, manifest, review, author } = this.props
form.validateFields((err, values) => {
if (!err) {
const { _id: id } = review
const submission = {
proposal,
manifest,
author,
...values
}
const params = {
id,
populate: ['author'],
transform: manifests => ({ manifests }),
update: ({ manifests: (prev, next) => {
let change = prev.slice()
let manifestIndex = change.findIndex(m => m._id === manifest)
let reviewIndex = manifestIndex >= 0
? change[manifestIndex].reviews
.findIndex(r => r._id === id)
: -1
reviewIndex >= 0
? change[manifestIndex].reviews[reviewIndex] = next
: change[manifestIndex].reviews.push(next)
return change
}})
}
params.id
? api.patch('review', submission, params)
.then(message.success('Vote updated!'), 10)
.catch(err => {
message.warning('Vote failed to update - Unexpected client error')
console.warn(err)
})
: api.post('review', submission, params)
.then(message.success('Vote posted!'))
.catch(err => {
message.warning('Vote failed to post - Unexpected client error')
console.warn(err)
})
}
})
}
render (
{ form, active, questions, manifest, review } = this.props
) {
return (
<section>
<Loading render={manifest} title='Voting Panel'>
{review && typeof review.approved === 'boolean' &&
<Alert showIcon banner
type={review.approved ? 'success' : 'error'}
message={`You have voted ${review.approved ? 'in favor' : 'against'} this budget`}
description='You may change this value later if this was a mistake.'
/>
}
<Form onSubmit={this.handleSubmit} style={{ paddingTop: 16 }}>
<FormItem label={<b>Final Vote</b>} {...layout} >
{form.getFieldDecorator('approved', { valuePropName: 'checked' })(
// Valueprop is a selector for antd switches, it's in the docs.
<Switch checkedChildren='APPROVE' unCheckedChildren='DENY' />
)}
</FormItem>
<FormItem label='Submit' {...layout}>
<Button size='large' type='primary'
htmlType='submit' ghost disabled={!active}
>Save Vote</Button>
</FormItem>
</Form>
</Loading>
</section>
)
}
}
export default Vote
|
client/modules/App/components/DevTools.js | mygithub1216/MERN_SelfCar_Dashboard | 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-w"
>
<LogMonitor />
</DockMonitor>
);
|
src/components/buttons/CreateButton.js | shrimpliu/shradmin | import React from 'react';
import PropTypes from 'prop-types';
import { Button } from 'antd';
import { actions } from 'mirrorx';
import { translate } from '../../i18n';
const CreateButton = ({ translate, model }) => (
<Button type="primary" icon="plus" onClick={() => actions.routing.push(`/${model}/create`)}>
{translate("actions.create")}
</Button>
);
CreateButton.propTypes = {
model: PropTypes.string.isRequired,
translate: PropTypes.func.isRequired,
};
export default translate(CreateButton); |
node_modules/react-bootstrap/es/DropdownMenu.js | firdiansyah/crud-req | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _Array$from from 'babel-runtime/core-js/array/from';
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 keycode from 'keycode';
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper';
import { bsClass, getClassSet, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = {
open: PropTypes.bool,
pullRight: PropTypes.bool,
onClose: PropTypes.func,
labelledBy: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
onSelect: PropTypes.func,
rootCloseEvent: PropTypes.oneOf(['click', 'mousedown'])
};
var defaultProps = {
bsRole: 'menu',
pullRight: false
};
var DropdownMenu = function (_React$Component) {
_inherits(DropdownMenu, _React$Component);
function DropdownMenu(props) {
_classCallCheck(this, DropdownMenu);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.handleRootClose = _this.handleRootClose.bind(_this);
_this.handleKeyDown = _this.handleKeyDown.bind(_this);
return _this;
}
DropdownMenu.prototype.handleRootClose = function handleRootClose(event) {
this.props.onClose(event, { source: 'rootClose' });
};
DropdownMenu.prototype.handleKeyDown = function handleKeyDown(event) {
switch (event.keyCode) {
case keycode.codes.down:
this.focusNext();
event.preventDefault();
break;
case keycode.codes.up:
this.focusPrevious();
event.preventDefault();
break;
case keycode.codes.esc:
case keycode.codes.tab:
this.props.onClose(event, { source: 'keydown' });
break;
default:
}
};
DropdownMenu.prototype.getItemsAndActiveIndex = function getItemsAndActiveIndex() {
var items = this.getFocusableMenuItems();
var activeIndex = items.indexOf(document.activeElement);
return { items: items, activeIndex: activeIndex };
};
DropdownMenu.prototype.getFocusableMenuItems = function getFocusableMenuItems() {
var node = ReactDOM.findDOMNode(this);
if (!node) {
return [];
}
return _Array$from(node.querySelectorAll('[tabIndex="-1"]'));
};
DropdownMenu.prototype.focusNext = function focusNext() {
var _getItemsAndActiveInd = this.getItemsAndActiveIndex(),
items = _getItemsAndActiveInd.items,
activeIndex = _getItemsAndActiveInd.activeIndex;
if (items.length === 0) {
return;
}
var nextIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1;
items[nextIndex].focus();
};
DropdownMenu.prototype.focusPrevious = function focusPrevious() {
var _getItemsAndActiveInd2 = this.getItemsAndActiveIndex(),
items = _getItemsAndActiveInd2.items,
activeIndex = _getItemsAndActiveInd2.activeIndex;
if (items.length === 0) {
return;
}
var prevIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1;
items[prevIndex].focus();
};
DropdownMenu.prototype.render = function render() {
var _extends2,
_this2 = this;
var _props = this.props,
open = _props.open,
pullRight = _props.pullRight,
labelledBy = _props.labelledBy,
onSelect = _props.onSelect,
className = _props.className,
rootCloseEvent = _props.rootCloseEvent,
children = _props.children,
props = _objectWithoutProperties(_props, ['open', 'pullRight', 'labelledBy', 'onSelect', 'className', 'rootCloseEvent', 'children']);
var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['onClose']),
bsProps = _splitBsPropsAndOmit[0],
elementProps = _splitBsPropsAndOmit[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'right')] = pullRight, _extends2));
return React.createElement(
RootCloseWrapper,
{
disabled: !open,
onRootClose: this.handleRootClose,
event: rootCloseEvent
},
React.createElement(
'ul',
_extends({}, elementProps, {
role: 'menu',
className: classNames(className, classes),
'aria-labelledby': labelledBy
}),
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
onKeyDown: createChainedFunction(child.props.onKeyDown, _this2.handleKeyDown),
onSelect: createChainedFunction(child.props.onSelect, onSelect)
});
})
)
);
};
return DropdownMenu;
}(React.Component);
DropdownMenu.propTypes = propTypes;
DropdownMenu.defaultProps = defaultProps;
export default bsClass('dropdown-menu', DropdownMenu); |
src/svg-icons/hardware/keyboard.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboard = (props) => (
<SvgIcon {...props}>
<path d="M20 5H4c-1.1 0-1.99.9-1.99 2L2 17c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z"/>
</SvgIcon>
);
HardwareKeyboard = pure(HardwareKeyboard);
HardwareKeyboard.displayName = 'HardwareKeyboard';
HardwareKeyboard.muiName = 'SvgIcon';
export default HardwareKeyboard;
|
local-cli/templates/HelloWorld/index.android.js | tadeuzagallo/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class HelloWorld extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
|
docs/app/Components/ComponentDoc/ComponentProps/ComponentPropsHeader.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import { Header, Icon } from 'shengnian-ui-react'
import { updateForKeys } from 'docs/app/HOC'
const headerStyle = {
cursor: 'pointer',
display: 'inline-flex',
margin: '1em 0.5em',
marginLeft: 0,
}
const linkStyle = { color: 'inherit' }
const ComponentPropsHeader = ({ hasSubComponents, onClick, showProps }) => {
const iconClasses = cx(
showProps ? 'on' : 'off',
'toggle',
)
return (
<Header
as='h4'
className='no-anchor'
color={showProps ? 'green' : 'grey'}
style={headerStyle}
onClick={onClick}
>
<a style={linkStyle}>
<Icon name={iconClasses} />
Props{hasSubComponents && ':'}
</a>
</Header>
)
}
ComponentPropsHeader.propTypes = {
hasSubComponents: PropTypes.bool,
onClick: PropTypes.func,
showProps: PropTypes.bool,
}
export default updateForKeys(['hasSubComponents', 'showProps'])(ComponentPropsHeader)
|
app/index.js | feijihn/lotto | require('smoothscroll-polyfill').polyfill();
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import configureStore from './store/configureStore';
import {Router, hashHistory} from 'react-router';
import routes from './routes';
const initialState = window.__INITIAL_STATE__;
const store = configureStore();
const rootElement = document.getElementById('container');
let ComponentEl;
if (process.env.NODE_ENV === 'development') {
const DevTools = require('./containers/DevTools').default;
// If using routes
ComponentEl = (
<div>
<Router history={hashHistory} routes={routes} useAutoKey={true}/>
<DevTools />
</div>
);
} else {
ComponentEl = (
<div>
<Router history={hashHistory} routes={routes} useAutoKey={true}/>
</div>
);
}
ReactDOM.render(
<Provider store={store}>
{ComponentEl}
</Provider>,
rootElement
);
|
stories/AutoComplete/ExampleStandard.js | skyiea/wix-style-react | import React from 'react';
import AutoComplete from 'wix-style-react/AutoComplete';
const style = {
display: 'inline-block',
padding: '0 5px 0',
width: '200px',
lineHeight: '22px'
};
const options = [
{id: 0, value: 'First option'},
{id: 1, value: 'Unselectable option', unselectable: true},
{id: 2, value: 'Third option'},
{id: 4, value: 'Very long option text jldlkasj ldk jsalkdjsal kdjaklsjdlkasj dklasj'}
];
const rtlOptions = [
{id: 0, value: 'אפשרות ראשונה'},
{id: 1, value: 'אפשרות שניה'},
{id: 2, value: 'אפשרות שלישית'}
];
export default () =>
<div>
<div style={style} className="ltr">
Left to right
<AutoComplete
options={options}
/>
</div>
<div style={style} className="rtl">
Right to left<AutoComplete options={rtlOptions}/>
</div>
<div style={style} className="ltr">
Disabled<AutoComplete disabled options={rtlOptions}/>
</div>
</div>;
|
admin/client/Signin/index.js | danielmahon/keystone | /**
* The signin page, it renders a page with a username and password input form.
*
* This is decoupled from the main app (in the "App/" folder) because we inject
* lots of data into the other screens (like the lists that exist) that we don't
* want to have injected here, so this is a completely separate route and template.
*/
import qs from 'qs';
import React from 'react';
import ReactDOM from 'react-dom';
import Signin from './Signin';
const params = qs.parse(window.location.search.replace(/^\?/, ''));
const from = typeof params.from === 'string' && params.from.charAt(0) === '/'
? params.from : undefined;
ReactDOM.render(
<Signin
brand={Keystone.brand}
from={from}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>,
document.getElementById('signin-view')
);
|
node_modules/react-bootstrap/es/MediaBody.js | superKaigon/TheCave | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'prop-types-extra/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'div'
};
var MediaBody = function (_React$Component) {
_inherits(MediaBody, _React$Component);
function MediaBody() {
_classCallCheck(this, MediaBody);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaBody.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaBody;
}(React.Component);
MediaBody.propTypes = propTypes;
MediaBody.defaultProps = defaultProps;
export default bsClass('media-body', MediaBody); |
packages/@lyra/imagetool/src/ImageLoader.js | VegaPublish/vega-studio | import PropTypes from 'prop-types'
import React from 'react'
export default class ImageLoader extends React.Component {
static propTypes = {
src: PropTypes.string.isRequired,
children: PropTypes.func.isRequired
}
state = {
isLoading: true,
image: null,
error: null
}
componentWillMount() {
this.loadImage(this.props.src)
}
loadImage(src) {
const image = new Image()
this.setState({
image: null,
error: null
})
image.onload = () => {
this.setState({
image: image,
error: null,
isLoading: false
})
}
image.onerror = () => {
this.setState({
error: new Error(
`Could not load image from ${JSON.stringify(this.props.src)}`
),
isLoading: false
})
}
image.src = src
}
componentWillReceiveProps(nextProps) {
if (nextProps.src !== this.props.src) {
this.loadImage(nextProps.src)
}
}
render() {
const {error, image, isLoading} = this.state
return this.props.children({image, error, isLoading})
}
}
|
src/components/DoneFooter.js | rollo-zhou/look | import React from 'react';
import {
ActivityIndicator,
StyleSheet,
Image,
Text,
View,
ListView,
TouchableOpacity
} from 'react-native';
import Dimensions from 'Dimensions';
const {width, height} = Dimensions.get('window');
import globalVariables from '../globalVariables.js';
const DoneFooter = React.createClass({
getInitialState() {
return {
};
},
shouldComponentUpdate: function(nextProps, nextState) {
return JSON.stringify(nextState)!=JSON.stringify(this.state);
},
render() {
return(
<View style={styles.doneView}>
<Text style={styles.ILoveYou}>- I Love You -</Text>
</View>
);
},
});
const styles = StyleSheet.create({
doneView: {
flexDirection: 'row',
justifyContent: 'center',
height:40,
width:width,
marginTop:20,
marginBottom:0,
},
ILoveYou: {
paddingTop:10,
fontSize: 10,
color: "#d8d2d6",
// fontWeight: "400",
// lineHeight: 18
},
doneImage: {
width: 302 / 5,
height: 252 / 5
},
});
export default DoneFooter;
|
src/Fade.js | brynjagr/react-bootstrap | import React from 'react';
import Transition from 'react-overlays/lib/Transition';
import CustomPropTypes from './utils/CustomPropTypes';
import deprecationWarning from './utils/deprecationWarning';
class Fade extends React.Component {
render() {
let timeout = this.props.timeout || this.props.duration;
return (
<Transition
{...this.props}
timeout={timeout}
className="fade"
enteredClassName="in"
enteringClassName="in"
>
{this.props.children}
</Transition>
);
}
}
// Explicitly copied from Transition for doc generation.
// TODO: Remove duplication once #977 is resolved.
Fade.propTypes = {
/**
* Show the component; triggers the fade in or fade out animation
*/
in: React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is faded out
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the fade in animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* Duration of the fade animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
timeout: React.PropTypes.number,
/**
* duration
* @private
*/
duration: CustomPropTypes.all([
React.PropTypes.number,
(props)=> {
if (props.duration != null) {
deprecationWarning('Fade `duration`', 'the `timeout` prop');
}
return null;
}
]),
/**
* Callback fired before the component fades in
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the component starts to fade in
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the has component faded in
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the component fades out
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the component starts to fade out
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the component has faded out
*/
onExited: React.PropTypes.func
};
Fade.defaultProps = {
in: false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false
};
export default Fade;
|
packages/mineral-ui-icons/src/IconFolderShared.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconFolderShared(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-5 3c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm4 8h-8v-1c0-1.33 2.67-2 4-2s4 .67 4 2v1z"/>
</g>
</Icon>
);
}
IconFolderShared.displayName = 'IconFolderShared';
IconFolderShared.category = 'file';
|
docs/src/app/components/pages/components/Menu/ExampleDisable.js | w01fgang/material-ui | import React from 'react';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import Divider from 'material-ui/Divider';
const style = {
display: 'inline-block',
margin: '16px 32px 16px 0',
};
const MenuExampleDisable = () => (
<div>
<Paper style={style}>
<Menu desktop={true}>
<MenuItem primaryText="Back" />
<MenuItem primaryText="Forward" disabled={true} />
<Divider />
<MenuItem primaryText="Recently closed" disabled={true} />
<MenuItem primaryText="Google" disabled={true} />
<MenuItem primaryText="YouTube" />
</Menu>
</Paper>
<Paper style={style}>
<Menu desktop={true}>
<MenuItem primaryText="Undo" />
<MenuItem primaryText="Redo" disabled={true} />
<Divider />
<MenuItem primaryText="Cut" disabled={true} />
<MenuItem primaryText="Copy" disabled={true} />
<MenuItem primaryText="Paste" />
</Menu>
</Paper>
</div>
);
export default MenuExampleDisable;
|
src/components/Root.js | kmcarter/karaoke-song-lister | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ConnectedRouter } from 'react-router-redux';
import { Provider } from 'react-redux';
import App from './App';
export default class Root extends Component {
render() {
const { store, history } = this.props;
return (
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
|
src/scripts/NavBar.js | lixmal/keepass4web | import React from 'react'
import Timer from './Timer'
window.$ = window.jQuery = require('jquery')
var Bootstrap = require('bootstrap')
export default class NavBar extends React.Component {
constructor() {
super()
this.onLogout = this.onLogout.bind(this)
this.onCloseDB = this.onCloseDB.bind(this)
this.onTimeUp = this.onTimeUp.bind(this)
}
onLogout() {
this.serverRequest = KeePass4Web.ajax('logout', {
success: function () {
KeePass4Web.clearStorage()
this.props.router.replace('/user_login')
}.bind(this),
error: KeePass4Web.error.bind(this),
})
}
onCloseDB(event, state) {
this.serverRequest = KeePass4Web.ajax('close_db', {
success: function () {
// redirect to home, so checks for proper login can be made
var router = this.props.router
// we haven't changed page, so need a workaround
router.replace('/db_login')
router.replace({
state: state,
pathname: '/'
})
}.bind(this),
error: KeePass4Web.error.bind(this),
})
}
onTimeUp() {
this.onCloseDB(null, {
info: 'Database session expired'
})
}
componentDidMount() {
if (KeePass4Web.getSettings().cn) {
document.getElementById('logout').addEventListener('click', this.onLogout)
document.getElementById('closeDB').addEventListener('click', this.onCloseDB)
}
}
componentWillUnmount() {
if (this.serverRequest)
this.serverRequest.abort()
}
render() {
var cn = KeePass4Web.getSettings().cn
var dropdown, search, timer
if (cn) {
dropdown = (
<ul className="dropdown-menu">
<li><a id="logout">Logout</a></li>
<li role="separator" className="divider"></li>
<li><a id="closeDB">Close Database</a></li>
</ul>
)
}
else {
cn = 'Not logged in'
dropdown = (
<ul className="dropdown-menu">
<li><a href="#/">Login</a></li>
</ul>
)
}
if (this.props.showSearch) {
search = (
<form className="navbar-form navbar-left" role="search" onSubmit={this.props.onSearch.bind(this, this.refs)}>
<div className="input-group">
<input autoComplete="on" type="search" ref="term" className="form-control" placeholder="Search" autoFocus />
<div className="input-group-btn">
<button type="submit" className="btn btn-default"><span className="glyphicon glyphicon-search"></span></button>
</div>
</div>
</form>
)
let timeout = KeePass4Web.getSettings().timeout
if (timeout) {
timer = (
<div className="navbar-text">
<Timer
format='{hh}:{mm}:{ss}'
timeout={timeout}
onTimeUp={this.onTimeUp}
restart={KeePass4Web.restartTimer}
/>
<label type="button" className="btn btn-secondary btn-xs" onClick={KeePass4Web.restartTimer.bind(this, true)}>
<span className="glyphicon glyphicon-repeat"></span>
</label>
</div>
)
}
}
return (
<nav className="navbar navbar-default navbar-fixed-top">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1" aria-expanded="false">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<a className="navbar-brand" href="#">KeePass 4 Web</a>
{timer}
</div>
<div className="collapse navbar-collapse" id="navbar-collapse-1">
{search}
<ul className="nav navbar-nav navbar-right">
<li className="dropdown">
<a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
{cn}
<span className="caret"></span>
</a>
{dropdown}
</li>
</ul>
</div>
</nav>
)
}
}
|
src/js/containers/LoginContainer/LoginContainer.js | shane-arthur/react-redux-and-more-boilerplate | import React, { Component } from 'react'; // eslint-disable-line import/first
import LoginPanel from '../../components/LoginPanel/LoginPanel';
export default class LoginContainer extends Component {
render(){
return (
<div><LoginPanel /></div>
);
}
} |
src/popup/components/PackEdit/Time.js | fluany/fluany | /**
* @fileOverview A component to change interval of the package
* @name Time.js
* @license GNU General Public License v3.0
*/
import React from 'react'
import PropTypes from 'prop-types'
import InputRange from 'react-input-range'
import { connect } from 'react-redux'
import { changeTimePackage } from 'actions/pack'
import { getIndexThingById } from 'reducers/stateManipulate'
import * as translator from 'shared/constants/i18n'
let Time = ({ onChangeTimePackage, packs, packageid }) => {
const handleTimeChange = (component, value) => {
onChangeTimePackage(value, packageid)
}
return (
<section className='time-container'>
<h2 className='time-title'>{translator.INTERVAL_MESSAGE}</h2>
<InputRange
maxValue={60}
minValue={1}
value={packs[getIndexThingById(packs, packageid)].timeMinutes}
onChange={handleTimeChange}
defaultValue={5}
labelSuffix='min'
/>
</section>
)
}
function mapDispatchToProps (dispatch) {
return {
onChangeTimePackage: (...props) => dispatch(changeTimePackage(...props))
}
}
const { func, array, string } = PropTypes
/**
* PropTypes
* @property {Function} onChangeTimePackage A action to change the package interval
* @property {Array} packs All package availables
* @property {String} packageid Id of the package to edit your interval
*/
Time.propTypes = {
onChangeTimePackage: func.isRequired,
packs: array.isRequired,
packageid: string.isRequired
}
export default connect(null, mapDispatchToProps)(Time)
|
src/routes/home/Home.js | bobbybeckner/ha-catalyst-test | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Home.css';
class Home extends React.Component {
static propTypes = {
news: PropTypes.arrayOf(
PropTypes.shape({
title: PropTypes.string.isRequired,
link: PropTypes.string.isRequired,
content: PropTypes.string,
}),
).isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>React.js News</h1>
{this.props.news.map(item =>
<article key={item.link} className={s.newsItem}>
<h1 className={s.newsTitle}>
<a href={item.link}>
{item.title}
</a>
</h1>
<div
className={s.newsDesc}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: item.content }}
/>
</article>,
)}
</div>
</div>
);
}
}
export default withStyles(s)(Home);
|
src/components/LoadingIndicator.js | davendesai/twitchcast | import React, { Component } from 'react';
import { CircularProgress } from 'material-ui';
import '../styles/LoadingIndicator.css';
export default class LoadingIndicator extends Component {
render() {
return(
<div id="twitchcast-loadingindicator">
{this.props.show ? <CircularProgress size={35} color="white" /> : null}
</div>
);
}
}
LoadingIndicator.propTypes = {
show: React.PropTypes.bool.isRequired
} |
_theme/template/NotFound.js | ElemeFE/react-amap | import React from 'react';
import Layout from './Layout';
export default class NotFound extends React.Component {
render() {
return <Layout>
<div id="notfound">
<img src="https://cloud.githubusercontent.com/assets/3898898/23833528/2e1e198c-0782-11e7-8e13-664b39a29d4b.png" alt=""/>
<div className="guide">
You Got Lost
</div>
</div>
</Layout>;
}
}
|
assets/node_modules/react-easy-chart/modules/pie-chart/hybrid/index.js | janta-devs/nyumbani | import React from 'react';
import {
scale,
layout,
svg,
select,
event as lastEvent,
interpolate
} from 'd3';
import {
createUniqueID,
defaultStyles
} from '../../shared';
import { createElement } from 'react-faux-dom';
import { Style } from 'radium';
import merge from 'lodash.merge';
const color = scale.category20();
const pie = layout.pie()
.value((d) => d.value)
.sort(null);
const getSliceFill = (d, i) => (
(d.data.color)
? d.data.color
: color(i));
const getLabelText = (d) => d.data.key;
export default class PieChart extends React.Component {
static get propTypes() {
return {
data: React.PropTypes.array.isRequired,
innerHoleSize: React.PropTypes.number,
size: React.PropTypes.number,
padding: React.PropTypes.number,
labels: React.PropTypes.bool,
styles: React.PropTypes.object,
mouseOverHandler: React.PropTypes.func,
mouseOutHandler: React.PropTypes.func,
mouseMoveHandler: React.PropTypes.func,
clickHandler: React.PropTypes.func
};
}
static get defaultProps() {
return {
size: 400,
innerHoleSize: 0,
padding: 2,
labels: false,
styles: {},
mouseOverHandler: () => {},
mouseOutHandler: () => {},
mouseMoveHandler: () => {},
clickHandler: () => {}
};
}
constructor(props) {
super(props);
this.uid = createUniqueID(props);
this.currentSlices = [];
this.currentLabels = [];
this.tweenSlice = (slice, index) => {
const currentSlice = this.currentSlices[index];
const i = interpolate(currentSlice, slice);
this.currentSlices[index] = slice;
return (t) => this.getSliceArc()(i(t));
};
}
componentDidMount() {
this.initialise();
}
componentDidUpdate() {
this.transition();
}
getSliceArc() {
const {
padding
} = this.props;
const innerRadius = this.getInnerRadius();
const outerRadius = this.getOuterRadius();
return svg.arc()
.innerRadius(innerRadius - padding)
.outerRadius(outerRadius - padding);
}
getLabelArc() {
const {
padding
} = this.props;
const outerRadius = this.getOuterRadius();
const radius = outerRadius - padding - ((20 * outerRadius) / 100);
return svg.arc()
.outerRadius(radius)
.innerRadius(radius);
}
getOuterRadius() {
return this.props.size * 0.5;
}
getInnerRadius() {
return this.props.innerHoleSize * 0.5;
}
getSlices() {
const {
data
} = this.props;
const uid = this.uid;
return select(`#slices-${uid}`)
.datum(data)
.selectAll('path');
}
getLabels() {
const {
data
} = this.props;
const uid = this.uid;
return select(`#labels-${uid}`)
.datum(data)
.selectAll('text');
}
createSvgNode({ size }) {
const node = createElement('svg');
node.setAttribute('width', size);
node.setAttribute('height', size);
return node;
}
createSvgRoot({ node }) {
return select(node);
}
initialiseLabels() {
const text = this.getLabels()
.data(pie);
const getLabelArcTransform = (d) => {
const [labelX, labelY] = this.getLabelArc().centroid(d);
return `translate(${labelX}, ${labelY})`;
};
const currentLabels = this.currentLabels;
text
.enter()
.append('text')
.attr('dy', '.35em')
.attr('class', 'pie-chart-label')
.attr('transform', getLabelArcTransform)
.text(getLabelText)
.each((d) => currentLabels.push(d));
}
initialiseSlices() {
const {
mouseOverHandler,
mouseOutHandler,
mouseMoveHandler,
clickHandler
} = this.props;
const mouseover = (d) => mouseOverHandler(d, lastEvent);
const mouseout = (d) => mouseOutHandler(d, lastEvent);
const mousemove = (d) => mouseMoveHandler(d, lastEvent);
const click = (d) => clickHandler(d, lastEvent);
const currentSlices = this.currentSlices;
const path = this.getSlices()
.data(pie);
path
.enter()
.append('path')
.attr('class', 'pie-chart-slice')
.attr('fill', getSliceFill)
.attr('d', this.getSliceArc())
.on('mouseover', mouseover)
.on('mouseout', mouseout)
.on('mousemove', mousemove)
.on('click', click)
.each((d) => currentSlices.push(d));
}
initialise() {
const {
labels
} = this.props;
this.initialiseSlices();
if (labels) {
this.initialiseLabels();
}
}
transitionSlices() {
const {
data,
mouseOverHandler,
mouseOutHandler,
mouseMoveHandler,
clickHandler
} = this.props;
const mouseover = (d) => mouseOverHandler(d, lastEvent);
const mouseout = (d) => mouseOutHandler(d, lastEvent);
const mousemove = (d) => mouseMoveHandler(d, lastEvent);
const click = (d) => clickHandler(d, lastEvent);
const n = data.length;
const currentSlices = this.currentSlices;
const path = this.getSlices()
.data(pie);
if (n) { // we don't need to do this, but it's fun
/*
* Change current slices
* Transition current slice dimensions
*/
path
.attr('fill', getSliceFill)
.on('mouseover', mouseover)
.on('mouseout', mouseout)
.on('mousemove', mousemove)
.on('click', click)
.transition()
.duration(750)
.attrTween('d', this.tweenSlice);
/*
* Add new slices
*/
path
.enter()
.append('path')
.attr('class', 'pie-chart-slice')
.attr('fill', getSliceFill)
.on('mouseover', mouseover)
.on('mouseout', mouseout)
.on('mousemove', mousemove)
.on('click', click)
.each((d, i) => currentSlices.splice(i, 1, d))
.transition()
.duration(750)
.attrTween('d', this.tweenSlice);
}
/*
* Remove old slices
*/
path
.exit()
.remove();
currentSlices.length = n; // = this.currentSlices.slice(0, n)
}
transitionLabels() {
const {
data
} = this.props;
const getLabelArcTransform = (d) => {
const [labelX, labelY] = this.getLabelArc().centroid(d);
return `translate(${labelX}, ${labelY})`;
};
const n = data.length;
const currentLabels = this.currentLabels;
const text = this.getLabels()
.data(pie);
if (n) { // we don't need to do this, but it's fun
/*
* Change current labels
*/
text
.transition()
.duration(750)
.attr('transform', getLabelArcTransform)
.text(getLabelText);
/*
* Add new labels
*/
text
.enter()
.append('text')
.attr('dy', '.35em')
.attr('class', 'pie-chart-label')
.attr('transform', getLabelArcTransform)
.text(getLabelText)
.each((d, i) => currentLabels.splice(i, 1, d))
.transition()
.duration(750);
}
/*
* Remove old labels
*/
text
.exit()
.remove();
currentLabels.length = n;
}
transition() {
const {
labels
} = this.props;
this.transitionSlices();
if (labels) {
this.transitionLabels();
}
}
createSlices({ root }) {
const uid = this.uid;
const radius = this.getOuterRadius();
root
.append('g')
.attr('id', `slices-${uid}`)
.attr('transform', `translate(${radius}, ${radius})`);
}
createLabels({ root }) {
const uid = this.uid;
const radius = this.getOuterRadius();
root
.append('g')
.attr('id', `labels-${uid}`)
.attr('transform', `translate(${radius}, ${radius})`);
}
createStyle() {
const {
styles
} = this.props;
const uid = this.uid;
const scope = `.pie-chart-${uid}`;
const rules = merge({}, defaultStyles, styles);
return (
<Style
scopeSelector={scope}
rules={rules}
/>
);
}
calculateChartParameters() {
const {
size
} = this.props;
const node = this.createSvgNode({ size });
const root = this.createSvgRoot({ node });
return {
node,
root
};
}
render() {
const {
labels
} = this.props;
const p = this.calculateChartParameters();
this.createSlices(p);
if (labels) {
this.createLabels(p);
}
const uid = this.uid;
const className = `pie-chart-${uid}`;
const {
node
} = p;
return (
<div className={className}>
{this.createStyle()}
{node.toReact()}
</div>
);
}
}
|
frontend/src/components/login/login.js | unicef/un-partner-portal | import React from 'react';
import Card from '../common/cardLogin';
import LoginForm from './loginForm';
const messages = {
title: 'UN Partner Portal',
};
const Login = () => (
<Card title={messages.title}>
<LoginForm />
</Card>
);
export default Login;
|
packages/material-ui-icons/src/AddCircleOutline.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let AddCircleOutline = props =>
<SvgIcon {...props}>
<path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" />
</SvgIcon>;
AddCircleOutline = pure(AddCircleOutline);
AddCircleOutline.muiName = 'SvgIcon';
export default AddCircleOutline;
|
server/dashboard/js/components/BenchLog.react.js | machinezone/mzbench | import React from 'react';
import ReactDOM from 'react-dom';
import LogsStore from '../stores/LogsStore';
import MZBenchActions from '../actions/MZBenchActions';
import MZBenchRouter from '../utils/MZBenchRouter';
import BenchLogEntry from './BenchLogEntry.react';
import LoadingSpinner from './LoadingSpinner.react';
import PropTypes from 'prop-types';
const LOGS_PER_PAGE = 100;
class BenchLog extends React.Component {
constructor(props) {
super(props);
this.streamId = 0;
this.autoSearchHandler = null;
this.filtered = 0;
this.state = this._resolveState();
this.state.tempQ = this.state.form.query;
this.state.tempK = this.state.form.kind;
this.state.tempE = this.state.form.errors;
this.state.logShown = LOGS_PER_PAGE;
this.followFlag = false;
this._onChange = this._onChange.bind(this);
this._onChangeSearch = this._onChangeSearch.bind(this);
this._onUser = this._onUser.bind(this);
this._onSystem = this._onSystem.bind(this);
this._onErrors = this._onErrors.bind(this);
this._onScroll = this._onScroll.bind(this);
this._onResize = this._onResize.bind(this);
this._onFollow = this._onFollow.bind(this);
this._onTop = this._onTop.bind(this);
this.lastLogShown = 0;
}
componentDidMount() {
LogsStore.onChange(this._onChange);
this.streamId = LogsStore.subscribeToLogs(this.props.bench.id);
window.addEventListener("scroll", this._onScroll);
window.addEventListener("resize", this._onResize);
ReactDOM.findDOMNode(this.refs.loglookup).focus();
this._updateFollowPos();
this._updateTopPos();
}
componentWillUnmount() {
LogsStore.off(this._onChange);
LogsStore.unsubscribeFromLogs(this.streamId);
window.removeEventListener("resize", this._onResize);
window.removeEventListener("scroll", this._onScroll);
}
componentDidUpdate() {
if (this.state.isFollow) {
this.goBottom();
}
this._updateFollowPos();
this._updateTopPos();
}
render() {
const url = '/' + (this.state.form.kind == 0 ? 'userlog' : 'log') + '?id=' + this.props.bench.id;
let classUser = "btn btn-" + (this.state.form.kind == 0 ? "primary":"default");
let classSystem = "btn btn-" + (this.state.form.kind == 1 ? "primary":"default");
let classError = "btn btn-" + (this.state.form.errors == 1 ? "danger":"default");
let currentLog = this.state.form.kind == 1 ? this.state.logs.system : this.state.logs.user;
let overflow = this.state.form.kind == 1 ? this.state.logs.systemOverflow : this.state.logs.userOverflow;
let loaded = this.state.form.kind == 1 ? this.state.logs.isSystemLoaded : this.state.logs.isUserLoaded;
let logAfterQuery = this.state.logAfterQuery;
let logsToShow = (logAfterQuery.length < this.state.logShown) ? logAfterQuery.length : this.state.logShown;
this.lastLogShown = logsToShow;
return (
<div>
<form className="form-inline log-lookup-form">
<div className="input-group col-xs-4">
<div className="input-group-addon"><span className="glyphicon glyphicon-search" aria-hidden="true"></span></div>
<input ref="loglookup" type="text" className="form-control" onKeyDown={this._onKeyDown.bind(this)} onChange={this._onChangeSearch} value={this.state.tempQ} placeholder="Lookup Logs" />
</div>
<div className="btn-group" role="group">
<button type="button" className={classUser} onClick={this._onUser}>User</button>
<button type="button" className={classSystem} onClick={this._onSystem}>System</button>
</div>
<button type="button" className={classError} onClick={this._onErrors}>Errors only</button>
</form>
{
!loaded ? (<LoadingSpinner>Loading...</LoadingSpinner>) :
<div>
<div className="top-raw-fixed" ref="followdiv">
<span className="btn-raw">
<a href={url} target="_blank">Raw log</a>
</span>
<span className="btn-raw btn-bottom" style={{fontWeight: this.state.isFollow && this.props.isBenchActive ? 'bold' : 'normal'}} ref="followbtn">
<a href="#" onClick={this._onFollow}>{this.props.isBenchActive ? "Follow log" : "Scroll to end"}</a>
</span>
</div>
<div className="bottom-raw-fixed" ref="topbtn">
<span className="btn-raw btn-top">
<a href="#" onClick={this._onTop}>Top</a>
</span>
</div>
<div className="log-window" ref="logwindow">
<table className="table table-striped table-logs">
<tbody>
{overflow ? <tr className="warning"><td>Warning: due to big size, this log is trimmed</td></tr> : null}
{!currentLog.length ? <tr className="warning"><td>Warning: this log is empty</td></tr> :
(!logAfterQuery.length ? <tr className="warning"><td>Query not found</td></tr> : null)}
</tbody>
</table>
{this.formatLogs(logsToShow, logAfterQuery)}
</div>
</div>
}
</div>
);
}
formatLogs(logsToShow, log) {
let nPages = Math.round(logsToShow / LOGS_PER_PAGE) + 1;
let form = this.state.form;
let prefix = form.kind + "-" + form.errors + "-" + form.query + "-";
let res = [];
for (var page = 0; page < nPages; page++) {
res.push(<BenchLogEntry
key={prefix + page}
log={log}
from={page*LOGS_PER_PAGE}
to={(page + 1)*LOGS_PER_PAGE}
query={this.state.form.query}/>);
}
return res;
}
filterLogs(form, logs, needRefilter) {
let filtered = (needRefilter || !this.state) ? 0 : this.filtered;
var logAfterQuery = (needRefilter || !this.state) ? [] : this.state.logAfterQuery;
let currentLog = form.kind == 1 ? logs.system : logs.user;
let query = form.query;
let errors = form.errors;
if (needRefilter) this.lastLogShown = 0;
if (!query && !errors) {
this.filtered = currentLog.length;
return currentLog;
}
for (; filtered < currentLog.length; filtered++) {
let line = currentLog[filtered];
if (!line) break;
if (query) {
let fullText = line.time + " " + line.severity + " " + line.text;
if (fullText.indexOf(query) == -1) continue;
}
if (errors && line.severity!="[error]") continue;
logAfterQuery.push(line);
};
this.filtered = filtered;
return logAfterQuery;
}
_onScroll(scrollEvent) {
this._updateFollowPos();
this._updateTopPos();
if (this.updatePage()) return;
if (this.followFlag) {
this.followFlag = false;
} else if(this.state.isFollow) {
this.setState({isFollow: false});
}
}
_onResize(resizeEvent) {
this._updateFollowPos();
this._updateTopPos();
}
_updateFollowPos() {
let logElement = ReactDOM.findDOMNode(this.refs.logwindow);
if (!logElement) return;
var rect = logElement.getBoundingClientRect();
let top = (rect.top > 0) ? rect.top : 0;
let right = (document.body.clientWidth - rect.right);
let followDiv = ReactDOM.findDOMNode(this.refs.followdiv);
followDiv.style.top = top + 'px';
followDiv.style.right = right + 'px';
let followBtn = ReactDOM.findDOMNode(this.refs.followbtn);
let visible = document.body.scrollHeight > window.innerHeight;
followBtn.style.visibility = visible ? "visible" : "hidden";
}
_updateTopPos() {
let logElement = ReactDOM.findDOMNode(this.refs.logwindow);
if (!logElement) return;
var rect = logElement.getBoundingClientRect();
let right = (document.body.clientWidth - rect.right);
let topBtn = ReactDOM.findDOMNode(this.refs.topbtn);
topBtn.style.visibility = (window.pageYOffset > 0 ? 'visible' : 'hidden');
topBtn.style.right = right + 'px';
}
_resolveState() {
let currentState = this.state ? this.state : {form: {query: "", kind: 0, errors: 0}, logAfterQuery: [], isFollow: false};
let newForm = LogsStore.getQueryData(this.props.bench.id);
let needRefilter = (!currentState.form ||
currentState.form.query != newForm.query ||
currentState.form.kind != newForm.kind ||
currentState.form.errors != newForm.errors);
currentState.form.kind = newForm.kind;
currentState.form.query = newForm.query;
currentState.form.errors = newForm.errors;
currentState.logs = LogsStore.getLogData(this.streamId);
currentState.logAfterQuery = this.filterLogs(newForm, currentState.logs, needRefilter);
return currentState;
}
_onChange() {
this.setState(this._resolveState());
if (this.state.isFollow) this.updatePage();
}
_runSearch() {
this.state.logShown = LOGS_PER_PAGE;
if (this.autoSearchHandler) {
clearTimeout(this.autoSearchHandler);
}
MZBenchRouter.navigate("/bench/" + this.props.bench.id + "/logs/" +
(this.state.tempK ? "system": "user") + "/" +
(this.state.tempE ? "errors": "all") + (this.state.tempQ ? "/" + encodeURIComponent(this.state.tempQ).replace(/'/g, "%27") : ""), {});
}
_onKeyDown(event) {
if (event.key === 'Enter') {
event.preventDefault();
this._runSearch();
}
}
_onChangeSearch(event) {
let state = this.state;
if (this.autoSearchHandler) {
clearTimeout(this.autoSearchHandler);
}
state.tempQ = event.target.value;
this.setState(state);
this.autoSearchHandler = setTimeout(() => this._runSearch(), this.props.autoSearchInterval);
}
_onUser() {
this.state.tempK = 0;
ReactDOM.findDOMNode(this.refs.loglookup).focus();
this._runSearch();
}
_onSystem() {
this.state.tempK = 1;
ReactDOM.findDOMNode(this.refs.loglookup).focus();
this._runSearch();
}
_onFollow(event) {
event.preventDefault();
this.setState({isFollow: !this.state.isFollow});
let logLen = this.state.logAfterQuery.length;
if (this.state.logShown < logLen) {
this.setState({logShown: logLen});
}
if (this.state.isFollow) this.goBottom();
}
_onTop(event) {
event.preventDefault();
this.setState({isFollow: false});
ReactDOM.findDOMNode(this.refs.loglookup).focus();
this.goTop();
}
_onErrors() {
this.state.tempE = !this.state.tempE;
ReactDOM.findDOMNode(this.refs.loglookup).focus();
this._runSearch();
}
goBottom() {
var newValue = document.body.scrollHeight - window.innerHeight;
if (window.pageYOffset < newValue) {
window.scrollTo(0, newValue);
this.followFlag = true;
}
}
goTop() {
window.scrollTo(0, 0);
}
updatePage () {
let node = document.body;
var shouldIncrementPage = (window.pageYOffset + window.innerHeight + 2000 > node.scrollHeight);
let endReached = (this.state.logAfterQuery.length <= this.state.logShown);
if (shouldIncrementPage && !endReached) {
this.setState({logShown: this.state.logShown + LOGS_PER_PAGE});
return true;
}
return false;
}
};
BenchLog.propTypes = {
bench: PropTypes.object.isRequired,
autoSearchInterval: PropTypes.number
};
BenchLog.defaultProps = {
autoSearchInterval: 500
};
export default BenchLog;
|
src/javascripts/utils.js | aAXEe/online_chart_ol3 | /**
* @license AGPL-3.0
* @author aAXEe (https://github.com/aAXEe)
*/
import viewSize from 'screen-size'
import React from 'react'
import { FormattedMessage } from 'react-intl'
export function floatEqual (num1, num2, eps = 0.0001) {
if (num1 === num2) return true
return Math.abs(num1 - num2) <= eps
}
export function positionsEqual (pos1, pos2) {
if (pos1 === pos2) return true
let epsilon = 0.0001
return floatEqual(pos1.lat, pos2.lat, epsilon) &&
floatEqual(pos1.lan, pos2.lan, epsilon) &&
floatEqual(pos1.zoom, pos2.zoom, epsilon)
}
export function isMobile () {
return (viewSize().x <= 768)
}
export function hashCode (str) {
return str.split('').reduce((prevHash, currVal) =>
((prevHash << 5) - prevHash) + currVal.charCodeAt(0), 0)
}
export const ClickOnMarkersMessage = () => (
<FormattedMessage
id='click-on-markers'
description='Inform users about interactive map elements'
defaultMessage='Click on the markers on the map.'
/>
)
|
src/components/ReplConsole.js | boneskull/Mancy | import React from 'react';
import _ from 'lodash';
import ReplConsoleStore from '../stores/ReplConsoleStore';
import ReplDOM from '../common/ReplDOM';
import ReplConsoleMessageFilters from './ReplConsoleMessageFilters';
import ReplConsoleHook from '../common/ReplConsoleHook';
export default class ReplConsole extends React.Component {
constructor(props) {
super(props);
this.state = _.extend({}, ReplConsoleStore.getStore(), {
debug: true,
log: true,
info: true,
warn: true,
error: true,
all: true
});
_.each([
'onConsoleChange', 'getTypedClassName',
'onAll', 'onFilter', 'onClear', 'getDupCountStyle',
'getDupTooltip'
], (field) => {
this[field] = this[field].bind(this);
});
_.each(['debug', 'log', 'info', 'warn', 'error'], (msg) => {
let key = 'on' + _.capitalize(msg);
this[key] = () => this.onFilter(msg);
this[key] = this[key].bind(this);
});
}
componentDidMount() {
this.unsubscribe = ReplConsoleStore.listen(this.onConsoleChange);
this.element = React.findDOMNode(this);
}
componentWillUnmount() {
this.unsubscribe();
}
onFilter(type) {
let flag = !this.state[type];
let newState = _.extend({}, this.state);
newState[type] = flag;
newState.entries = _.filter(ReplConsoleStore.getStore().entries, (entry) => {
return newState[entry.type];
});
this.setState(newState);
}
onClear() {
ReplConsoleStore.clear();
}
onAll() {
let newState;
if(!this.state.all) {
newState = _.extend({}, ReplConsoleStore.getStore(), {
debug: true,
log: true,
info: true,
warn: true,
error: true,
all: true
});
} else {
newState = { all: false }
}
this.setState(newState);
}
onConsoleChange() {
this.setState(ReplConsoleStore.getStore());
}
getTypedClassName(className, type) {
return className + ' ' + type;
}
getDupCountStyle(count) {
let widthLength = `${count}`.length;
return { width: `${widthLength + 0.2}em` };
}
getDupTooltip(count, type) {
return `${count} ${type} messages`;
}
render() {
//scroll to bottom
ReplDOM.scrollToEnd(this.element);
return (
<div className='repl-console-message'>
<ReplConsoleMessageFilters
filter={this.state}
onAll={this.onAll}
onError={this.onError}
onWarn={this.onWarn}
onInfo={this.onInfo}
onLog={this.onLog}
onClear={this.onClear}
onDebug={this.onDebug}/>
{
_.map(this.state.entries, ({type, data, time, count}) => {
return (
<div className={this.getTypedClassName('repl-console-message-entry', type)} key={time}>
{count > 1 ? <span className='console-message-count' title={this.getDupTooltip(count, type)} style={this.getDupCountStyle(count)}>{count}</span>: null}
{ReplConsole.getTypeIcon[type]}
<span className={this.getTypedClassName('repl-console-message-entry-content', type)}>
{data}
</span>
</div>
);
})
}
<div className="repl-status-bar-cover" key='cover'></div>
</div>
);
}
static getTypeIcon = (() => {
let cache = {};
cache.error = <i className="fa fa-exclamation-circle repl-console-message-error" title='error'></i>
cache.warn = <i className="fa fa-exclamation-triangle repl-console-message-warning" title='warning'></i>
cache.info = <i className="fa fa-info-circle repl-console-message-info" title='info'></i>
return cache;
})();
}
|
app/js/components/ui/containers/field.js | blockstack/blockstack-browser | import React from 'react'
import PropTypes from 'prop-types'
import { StyledField } from '@ui/components/form'
import { slugify } from '@ui/common'
import AlertCircleIcon from 'mdi-react/AlertCircleIcon'
import CheckCircleOutlineIcon from 'mdi-react/CheckCircleOutlineIcon'
/* eslint-disable */
class Field extends React.Component {
static propTypes = {
label: PropTypes.string.isRequired,
type: PropTypes.string,
value: PropTypes.string,
message: PropTypes.node,
autoFocus: PropTypes.bool,
error: PropTypes.any,
positive: PropTypes.bool,
overlay: PropTypes.node,
name: PropTypes.node,
mh: PropTypes.any,
handleChange: PropTypes.func,
handleChangeOverride: PropTypes.func,
handleBlur: PropTypes.func,
onBlur: PropTypes.func
}
ref = React.createRef()
componentDidMount() {
if (this.props.autoFocus) {
this.ref.current.focus()
}
}
render() {
/* eslint-enable */
const {
label,
type = 'text',
message,
autoFocus,
error,
positive,
overlay,
name = slugify(label),
mh,
value,
handleChange,
handleChangeOverride,
handleBlur, // these are here to prevent them from being used (fixes form bug double click)
onBlur, // these are here to prevent them from being used (fixes form bug double click)
...rest
} = this.props
const InputComponent =
type === 'textarea' ? StyledField.Textarea : StyledField.Input
const LabelIconComponent = positive
? CheckCircleOutlineIcon
: AlertCircleIcon
const LabelIcon = (error || positive) && (
<StyledField.Label.Icon positive={positive}>
<LabelIconComponent size={16} />
</StyledField.Label.Icon>
)
/**
* TODO: abstract out qualified message to one component that takes multiple states
*/
const MessageComponent = error
? StyledField.Input.Error
: StyledField.Input.Positive
const Message = p =>
positive || error ? (
<MessageComponent overlay={!!overlay} {...p}>
{positive || error}
</MessageComponent>
) : null
const Overlay = overlay ? (
<StyledField.Input.Overlay>{overlay}</StyledField.Input.Overlay>
) : null
const _handleChange = e => {
if (handleChangeOverride) {
handleChangeOverride(e, handleChange)
} else {
handleChange(e)
}
}
const Label = () => (
<StyledField.Label htmlFor={name}>
{label}
{LabelIcon}
</StyledField.Label>
)
return (
<StyledField.Group error={error} {...rest}>
<StyledField.Input.Wrapper>
{Overlay}
<InputComponent
ref={this.ref}
placeholder={label}
autoComplete="new-password"
required
name={name}
type={type}
defaultValue={value}
mh={mh}
onChange={_handleChange}
lowercase={type !== 'password'}
/>
<Message />
<Label />
<StyledField.Input.Bar />
</StyledField.Input.Wrapper>
{message && (
<StyledField.Input.Message>{message}</StyledField.Input.Message>
)}
</StyledField.Group>
)
}
}
// eslint-enable
export { Field }
|
src/scenes/home/families/facts/facts.js | tal87/operationcode_frontend | import React from 'react';
import styles from './facts.css';
import family3 from '../../../../images/Family-3.jpg';
const Facts = () => (
<div className={styles.facts}>
<div className={styles.factsList}>
<div className={styles.factsHeading}>
<h5>The Facts</h5>
</div>
<ul>
<li className={styles.factItem}>
There are approximately 710,000 active duty spouses, 93% of whom are female.
An additional 500,000 spouses are married to a Reservist or National Guardsman.
</li>
<li className={styles.factItem}>
84% have some college education; 25% hold an undergraduate degree;
and 10% hold a postgraduate degree.
</li>
<li className={styles.factItem}>
77% of spouses report that they want or need to work.
38% of military spouses are underemployed,
compared to approximately 6% rate for civilian spouses.
</li>
<li className={styles.factItem}>
Only 19% of military spouses have adequate full-time employment.
</li>
</ul>
</div>
<div className={styles.factsRight}>
<img className={styles.factsImage} src={family3} alt="" />
</div>
</div>
);
export default Facts;
|
src/scenes/home/chapterLeader/chapterLeader.js | hollomancer/operationcode_frontend | import React from 'react';
import Section from 'shared/components/section/section';
const chapterLeaders = () => (
<div>
<Section title="Chapter Leaders" theme="white">
<div>
<p>
Operation Code is looking for volunteer Chapter Leaders to build local communities
nationwide! Tell us more about yourself
<a
href="http://op.co.de/chapter-leader-volunteer"
target="_blank"
rel="noopener noreferrer"
>
here
</a>
and help further our mission to get the military community into the tech industry!
</p>
<p>
{' '}
An Operation Code Chapter Leader organizes meetups and events at the local level, and
establishes relationships with local companies, educational institutions, and other
organizations, in order to help build the community and support the mission.
</p>
<h5>Who is a Chapter Leader?</h5>
<ul>
<li>Represents the Operation Code values.</li>
<li>
Dedicated, reliable and has consistently displayed participation in the community.
</li>
<li>
Understands the community dynamics and encourages members to have a voice. Empowers
people.
</li>
<li>
Organized, and able to stay on top of their multiple responsibilities, such as managing
events and recruiting new members.
</li>
<li>
Passionate communicators that have a strong desire to connect with like-minded people.
</li>
<li>
Able to explain basic programming concepts to chapter members if necessary, as new
chapter members may range from being senior software developers, to having little or no
experience with software development.
</li>
</ul>
<h5>Responsibilities</h5>
<ul>
<li>Enforce the Code of Conduct on Operation Code web communities.</li>
<li>Host events, including trainings, talks, hack nights, etc.</li>
<li>Build partnerships in the local community.</li>
<li>
<a
href="https://opencollective.com/operationcode"
target="_blank"
rel="noopener noreferrer"
>
Raise funds
</a>
and in-kind donations in support of the mission.
</li>
<li>Build and integrate the infrastructure necessary to sustain the chapter.</li>
<li>Reach out to potential new members, receiving and integrating them to the team.</li>
<li>Advocate for and promote the organization in the local community.</li>
<li>Help members learn, grow, and find jobs!</li>
</ul>
<p>
Think you are interested in becoming a Chapter Leader? Click
<a
href="http://op.co.de/chapter-leader-volunteer"
target="_blank"
rel="noopener noreferrer"
>
here.
</a>
</p>
</div>
</Section>
</div>
);
export default chapterLeaders;
|
src/svg-icons/action/group-work.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionGroupWork = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM8 17.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5zM9.5 8c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5S9.5 9.38 9.5 8zm6.5 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
</SvgIcon>
);
ActionGroupWork = pure(ActionGroupWork);
ActionGroupWork.displayName = 'ActionGroupWork';
ActionGroupWork.muiName = 'SvgIcon';
export default ActionGroupWork;
|
web-server/v0.4/src/pages/Summary/index.js | k-rister/pbench | import React from 'react';
import { connect } from 'dva';
import { Spin, Tag, Card, List, Typography, Divider } from 'antd';
import { filterIterations } from '../../utils/parse';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Table from '@/components/Table';
import TableFilterSelection from '@/components/TableFilterSelection';
const tabList = [
{
key: 'iterations',
tab: 'Iterations',
},
{
key: 'toc',
tab: 'Table of Contents',
},
{
key: 'metadata',
tab: 'Metadata',
},
{
key: 'tools',
tab: 'Tools & Parameters',
},
];
const tocColumns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
width: '60%',
},
{
title: 'Size',
dataIndex: 'size',
key: 'size',
width: '20%',
},
{
title: 'Mode',
dataIndex: 'mode',
key: 'mode',
},
];
@connect(({ global, dashboard, loading }) => ({
iterations: dashboard.iterations,
iterationParams: dashboard.iterationParams,
iterationPorts: dashboard.iterationPorts,
result: dashboard.result,
tocResult: dashboard.tocResult,
datastoreConfig: global.datastoreConfig,
selectedControllers: global.selectedControllers,
selectedResults: global.selectedResults,
selectedIndices: global.selectedIndices,
loadingSummary:
loading.effects['dashboard/fetchIterations'] ||
loading.effects['dashboard/fetchResult'] ||
loading.effects['dashboard/fetchTocResult'],
}))
class Summary extends React.Component {
constructor(props) {
super(props);
const { iterations } = props;
this.state = {
activeSummaryTab: 'iterations',
resultIterations: iterations[0],
};
}
componentDidMount() {
const { dispatch, datastoreConfig, selectedIndices, selectedResults } = this.props;
dispatch({
type: 'dashboard/fetchIterations',
payload: { selectedResults, datastoreConfig },
});
dispatch({
type: 'dashboard/fetchResult',
payload: {
datastoreConfig,
selectedIndices,
result: selectedResults[0]['run.name'],
},
});
dispatch({
type: 'dashboard/fetchTocResult',
payload: {
datastoreConfig,
selectedIndices,
id: selectedResults[0].id,
},
});
}
componentWillReceiveProps(nextProps) {
const { iterations } = this.props;
if (nextProps.iterations !== iterations) {
this.setState({ resultIterations: nextProps.iterations[0] });
}
}
onFilterTable = (selectedParams, selectedPorts) => {
const { iterations } = this.props;
const filteredIterations = filterIterations(iterations, selectedParams, selectedPorts);
this.setState({ resultIterations: filteredIterations[0] });
};
onTabChange = key => {
this.setState({ activeSummaryTab: key });
};
render() {
const { activeSummaryTab, resultIterations } = this.state;
const {
selectedResults,
loadingSummary,
iterationParams,
iterationPorts,
selectedControllers,
tocResult,
result,
} = this.props;
const contentList = {
iterations: (
<Card title="Result Iterations" style={{ marginTop: 32 }}>
<Spin spinning={loadingSummary} tip="Loading Iterations...">
<TableFilterSelection
onFilterTable={this.onFilterTable}
filters={iterationParams}
ports={iterationPorts}
/>
<Table
style={{ marginTop: 16 }}
columns={resultIterations ? resultIterations.columns : []}
dataSource={resultIterations ? resultIterations.iterations : []}
bordered
/>
</Spin>
</Card>
),
toc: (
<Card title="Table of Contents" style={{ marginTop: 32 }}>
<Table columns={tocColumns} dataSource={tocResult} defaultExpandAllRows />
</Card>
),
metadata: (
<Card title="Run Metadata" style={{ marginTop: 32 }}>
{result.runMetadata && (
<List
size="small"
bordered
dataSource={Object.entries(result.runMetadata)}
renderItem={([label, value]) => (
<List.Item key={label}>
<Typography.Text strong>{label}</Typography.Text>
<Divider type="vertical" />
{value}
</List.Item>
)}
/>
)}
</Card>
),
tools: (
<Card title="Host Tools & Parameters" style={{ marginTop: 32 }}>
{result.hostTools &&
result.hostTools.map(host => (
<List
key={host.hostname}
style={{ marginBottom: 16 }}
size="small"
bordered
header={
<div>
<Typography.Text strong>hostname</Typography.Text>
<Divider type="vertical" />
{host.hostname}
</div>
}
dataSource={Object.entries(host.tools)}
renderItem={([label, value]) => (
<List.Item key={label}>
<Typography.Text strong>{label}</Typography.Text>
<Divider type="vertical" />
{value}
</List.Item>
)}
/>
))}
</Card>
),
};
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<div>
<PageHeaderLayout
title={selectedResults[0]['run.name']}
content={
<Tag color="blue" key={selectedControllers[0]}>
{`controller: ${selectedControllers[0]}`}
</Tag>
}
tabList={tabList}
tabActiveKey={activeSummaryTab}
onTabChange={this.onTabChange}
/>
{contentList[activeSummaryTab]}
</div>
</div>
);
}
}
export default connect(() => ({}))(Summary);
|
code/web/node_modules/react-bootstrap/es/DropdownToggle.js | zyxcambridge/RecordExistence | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import classNames from 'classnames';
import Button from './Button';
import SafeAnchor from './SafeAnchor';
import { bsClass as setBsClass } from './utils/bootstrapUtils';
var propTypes = {
noCaret: React.PropTypes.bool,
open: React.PropTypes.bool,
title: React.PropTypes.string,
useAnchor: React.PropTypes.bool
};
var defaultProps = {
open: false,
useAnchor: false,
bsRole: 'toggle'
};
var DropdownToggle = function (_React$Component) {
_inherits(DropdownToggle, _React$Component);
function DropdownToggle() {
_classCallCheck(this, DropdownToggle);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
DropdownToggle.prototype.render = function render() {
var _props = this.props;
var noCaret = _props.noCaret;
var open = _props.open;
var useAnchor = _props.useAnchor;
var bsClass = _props.bsClass;
var className = _props.className;
var children = _props.children;
var props = _objectWithoutProperties(_props, ['noCaret', 'open', 'useAnchor', 'bsClass', 'className', 'children']);
delete props.bsRole;
var Component = useAnchor ? SafeAnchor : Button;
var useCaret = !noCaret;
// This intentionally forwards bsSize and bsStyle (if set) to the
// underlying component, to allow it to render size and style variants.
// FIXME: Should this really fall back to `title` as children?
return React.createElement(
Component,
_extends({}, props, {
role: 'button',
className: classNames(className, bsClass),
'aria-haspopup': true,
'aria-expanded': open
}),
children || props.title,
useCaret && ' ',
useCaret && React.createElement('span', { className: 'caret' })
);
};
return DropdownToggle;
}(React.Component);
DropdownToggle.propTypes = propTypes;
DropdownToggle.defaultProps = defaultProps;
export default setBsClass('dropdown-toggle', DropdownToggle); |
src/layouts/CoreLayout/CoreLayout.js | harijoe/redux-dollar | import React from 'react'
import Header from '../../components/Header'
import './CoreLayout.scss'
import '../../styles/core.scss'
export const CoreLayout = ({ children }) => (
<div className='container text-center'>
<Header />
<div className='core-layout__viewport'>
{children}
</div>
</div>
)
CoreLayout.propTypes = {
children : React.PropTypes.element.isRequired
}
export default CoreLayout
|
actor-apps/app-web/src/app/components/common/MessageItem.react.js | Ajunboys/actor-platform | import _ from 'lodash';
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import memoize from 'memoizee';
import classNames from 'classnames';
import emojify from 'emojify.js';
import hljs from 'highlight.js';
import marked from 'marked';
import emojiCharacters from 'emoji-named-characters';
import VisibilitySensor from 'react-visibility-sensor';
import AvatarItem from 'components/common/AvatarItem.react';
import Image from './Image.react';
import DialogActionCreators from 'actions/DialogActionCreators';
import { MessageContentTypes } from 'constants/ActorAppConstants';
let lastMessageSenderId = null,
lastMessageContentType = null;
var MessageItem = React.createClass({
displayName: 'MessageItem',
propTypes: {
message: React.PropTypes.object.isRequired,
newDay: React.PropTypes.bool,
index: React.PropTypes.number,
onVisibilityChange: React.PropTypes.func
},
mixins: [PureRenderMixin],
onClick() {
DialogActionCreators.selectDialogPeerUser(this.props.message.sender.peer.id);
},
onVisibilityChange(isVisible) {
this.props.onVisibilityChange(this.props.message, isVisible);
},
render() {
const message = this.props.message;
const newDay = this.props.newDay;
const isFirstMessage = this.props.index === 0;
let header,
visibilitySensor,
leftBlock;
let isSameSender = message.sender.peer.id === lastMessageSenderId &&
lastMessageContentType !== MessageContentTypes.SERVICE &&
message.content.content !== MessageContentTypes.SERVICE &&
!isFirstMessage &&
!newDay;
let messageClassName = classNames({
'message': true,
'row': true,
'message--same-sender': isSameSender
});
if (isSameSender) {
leftBlock = (
<div className="message__info text-right">
<time className="message__timestamp">{message.date}</time>
<MessageItem.State message={message}/>
</div>
);
} else {
leftBlock = (
<div className="message__info message__info--avatar">
<a onClick={this.onClick}>
<AvatarItem image={message.sender.avatar}
placeholder={message.sender.placeholder}
title={message.sender.title}/>
</a>
</div>
);
header = (
<header className="message__header">
<h3 className="message__sender">
<a onClick={this.onClick}>{message.sender.title}</a>
</h3>
<time className="message__timestamp">{message.date}</time>
<MessageItem.State message={message}/>
</header>
);
}
if (message.content.content === MessageContentTypes.SERVICE) {
leftBlock = null;
header = null;
}
if (this.props.onVisibilityChange) {
visibilitySensor = <VisibilitySensor onChange={this.onVisibilityChange}/>;
}
lastMessageSenderId = message.sender.peer.id;
lastMessageContentType = message.content.content;
return (
<li className={messageClassName}>
{leftBlock}
<div className="message__body col-xs">
{header}
<MessageItem.Content content={message.content}/>
{visibilitySensor}
</div>
</li>
);
}
});
emojify.setConfig({
mode: 'img',
img_dir: 'assets/img/emoji' // eslint-disable-line
});
const mdRenderer = new marked.Renderer();
// target _blank for links
mdRenderer.link = function(href, title, text) {
let external, newWindow, out;
external = /^https?:\/\/.+$/.test(href);
newWindow = external || title === 'newWindow';
out = '<a href=\"' + href + '\"';
if (newWindow) {
out += ' target="_blank"';
}
if (title && title !== 'newWindow') {
out += ' title=\"' + title + '\"';
}
return (out + '>' + text + '</a>');
};
const markedOptions = {
sanitize: true,
breaks: true,
highlight: function (code) {
return hljs.highlightAuto(code).value;
},
renderer: mdRenderer
};
const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character));
const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) {
return name.replace(/\+/g, '\\+');
});
const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi');
const processText = function(text) {
let markedText = marked(text, markedOptions);
// need hack with replace because of https://github.com/Ranks/emojify.js/issues/127
const noPTag = markedText.replace(/<p>/g, '<p> ');
let emojifiedText = emojify
.replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':'));
return emojifiedText;
};
const memoizedProcessText = memoize(processText, {
length: 1000,
maxAge: 60 * 60 * 1000,
max: 10000
});
MessageItem.Content = React.createClass({
propTypes: {
content: React.PropTypes.object.isRequired
},
render() {
const content = this.props.content;
// TODO: move all types to subcomponents
let contentClassName = classNames('message__content', {
'message__content--service': content.content === MessageContentTypes.SERVICE,
'message__content--text': content.content === MessageContentTypes.TEXT,
'message__content--document': content.content === MessageContentTypes.DOCUMENT,
'message__content--unsupported': content.content === MessageContentTypes.UNSUPPORTED
});
switch (content.content) {
case 'service':
return (
<div className={contentClassName}>
{content.text}
</div>
);
case 'text':
return (
<div className={contentClassName}
dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}>
</div>
);
case 'photo':
return (
<Image content={content}
loadingClassName="message__content--photo"
loadedClassName="message__content--photo message__content--photo--loaded"/>
);
case 'document':
contentClassName = classNames(contentClassName, 'row');
let availableActions;
if (content.isUploading === true) {
availableActions = <span>Loading...</span>;
} else {
availableActions = <a href={content.fileUrl}>Open</a>;
}
return (
<div className={contentClassName}>
<div className="document row">
<div className="document__icon">
<i className="material-icons">attach_file</i>
</div>
<div className="col-xs">
<span className="document__filename">{content.fileName}</span>
<div className="document__meta">
<span className="document__meta__size">{content.fileSize}</span>
<span className="document__meta__ext">{content.fileExtension}</span>
</div>
<div className="document__actions">
{availableActions}
</div>
</div>
</div>
<div className="col-xs"></div>
</div>
);
default:
}
}
});
MessageItem.State = React.createClass({
propTypes: {
message: React.PropTypes.object.isRequired
},
render() {
const message = this.props.message;
if (message.content.content === MessageContentTypes.SERVICE) {
return null;
} else {
let icon = null;
switch(message.state) {
case 'pending':
icon = <i className="status status--penging material-icons">access_time</i>;
break;
case 'sent':
icon = <i className="status status--sent material-icons">done</i>;
break;
case 'received':
icon = <i className="status status--received material-icons">done_all</i>;
break;
case 'read':
icon = <i className="status status--read material-icons">done_all</i>;
break;
case 'error':
icon = <i className="status status--error material-icons">report_problem</i>;
break;
default:
}
return (
<div className="message__status">{icon}</div>
);
}
}
});
export default MessageItem;
|
packages/benchmarks/src/implementations/radium/Dot.js | css-components/styled-components | /* eslint-disable react/prop-types */
import Radium from 'radium';
import React from 'react';
const styles = {
root: {
position: 'absolute',
cursor: 'pointer',
width: 0,
height: 0,
borderColor: 'transparent',
borderStyle: 'solid',
borderTopWidth: 0,
transform: 'translate(50%, 50%)',
},
};
export default Radium(({ size, x, y, children, color }) => (
<div
style={[
styles.root,
{
borderBottomColor: color,
borderRightWidth: `${size / 2}px`,
borderBottomWidth: `${size / 2}px`,
borderLeftWidth: `${size / 2}px`,
marginLeft: `${x}px`,
marginTop: `${y}px`,
},
]}
>
{children}
</div>
));
|
examples/counter/containers/App.js | mikekidder/redux-devtools | import React, { Component } from 'react';
import CounterApp from './CounterApp';
import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import { devTools, persistState } from 'redux-devtools';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import * as reducers from '../reducers';
const finalCreateStore = compose(
applyMiddleware(thunk),
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)(createStore);
const reducer = combineReducers(reducers);
const store = finalCreateStore(reducer);
if (module.hot) {
module.hot.accept('../reducers', () =>
store.replaceReducer(combineReducers(require('../reducers')))
);
}
export default class App extends Component {
render() {
return (
<div>
<Provider store={store}>
{() => <CounterApp />}
</Provider>
<DebugPanel top right bottom>
<DevTools store={store}
monitor={LogMonitor}
visibleOnLoad={true} />
</DebugPanel>
</div>
);
}
}
|
app/assets/scripts/views/location/metadata.js | openaq/openaq.org | import React from 'react';
import { PropTypes as T } from 'prop-types';
import moment from 'moment';
import { schemas } from 'openaq-data-format';
import config from '../../config';
const locationSchema = schemas.location;
export default function Metadata({
loc,
loc: {
data: { metadata },
},
}) {
if (!metadata) return null;
const exclude = [
'id',
'coordinates',
'city',
'country',
'instruments',
'parameters',
'attribution',
];
const allProperties = Object.keys(locationSchema.properties).filter(key => {
return !exclude.includes(key) && metadata[key];
});
const propertiesMain = [];
const propertiesSec = [];
const length = Math.ceil(allProperties.length / 2);
allProperties.forEach((key, i) => {
const prop = locationSchema.properties[key];
prop.key = key;
let val = metadata[prop.key];
if (prop.format && prop.format === 'date-time') {
val = moment.utc(val).format('YYYY/MM/DD');
}
if (prop.type && prop.type === 'boolean') {
val = val ? 'Yes' : 'No';
}
const sectionIndex = Math.floor(i / length);
switch (sectionIndex) {
case 0: {
propertiesMain.push(
<dt key={`${key}-${prop.title}`} className="metadata-detail-title">
{prop.title}
</dt>
);
propertiesMain.push(<dd key={`${key}-${prop.title}-val`}>{val}</dd>);
break;
}
case 1: {
propertiesSec.push(
<dt key={`${key}-${prop.title}`} className="metadata-detail-title">
{prop.title}
</dt>
);
propertiesSec.push(<dd key={`${key}-${prop.title}-val`}>{val}</dd>);
break;
}
}
});
return (
<section className="fold" id="location-fold-metadata">
<div className="inner">
<header className="fold__header">
<h1 className="fold__title">Metadata</h1>
</header>
<div className="fold__body">
<div className="col-main">
<dl className="global-details-list">{propertiesMain}</dl>
</div>
<div className="col-sec">
<dl className="global-details-list">{propertiesSec}</dl>
</div>
</div>
<div className="update-metadata-callout">
<p>
Have more information about this location?{' '}
<a
href={`${config.metadata}/location/${loc.data.id}`}
title="Update the metadata"
>
Update the metadata
</a>
</p>
</div>
</div>
</section>
);
}
Metadata.propTypes = {
loc: T.shape({
fetching: T.bool,
fetched: T.bool,
error: T.string,
data: T.object,
}),
};
|
client/source/js/models/u_groups_m.js | Vladimir37/Planshark | import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {submitting, getData} from '../submitting.js';
import {Waiting, Error, Empty, Menu, Forbidden} from './templates.js';
import toast from '../toaster.js';
import {colorpick} from '../picker.js';
//responses
var actions_r = ['Success!', 'Server error' , 'Required fields are empty', 'Incorrect color'];
//RegExp
var re_color = new RegExp("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$");
//refresh groups list
var refresh;
var Creating = React.createClass({
getInitialState() {
return null;
},
componentDidMount() {
setTimeout(colorpick, 100);
},
submit(elem) {
var ajax_data = getData(elem.target);
if(!ajax_data) {
toast(actions_r[2]);
}
else if(!re_color.test(ajax_data.color)) {
toast(actions_r[3]);
$(elem.target).parent().find('input[name="color"]').val('');
}
else {
submitting(ajax_data, '/api/user_manage/create', 'POST', function(data) {
var response_status = +data;
if(isNaN(response_status)) {
response_status = 1;
}
if(response_status == 0) {
toast(actions_r[0]);
$(elem.target).parent().find('input[type="text"]').val('');
refresh();
}
else {
toast(actions_r[response_status]);
}
}, function(err) {
toast(actions_r[1]);
});
}
},
switching() {
$('.creatingFormBody').slideToggle();
},
render() {
return <section className="creatingForm">
<article className="creatingFormHead" onClick={this.switching}>Creating user group</article>
<article className="creatingFormBody">
<article className="creatingFormTop">
<input type="text" name="name" placeholder="Name" data-req="true" />
<input type="text" name="color" placeholder="Color" className="color_field" data-req="true" />
</article>
<article className="creatingFormMiddle">
<table>
<tr>
<td><label>Creating tasks<input type="checkbox" name="creating" value="1" /></label></td>
<td><label>Editing tasks<input type="checkbox" name="editing" value="1" /></label></td>
</tr>
<tr>
<td><label>Reassignment tasks<input type="checkbox" name="reassignment" value="1" /></label></td>
<td><label>Deleting tasks<input type="checkbox" name="deleting" value="1" /></label></td>
</tr>
<tr>
<td><label>Users control<input type="checkbox" name="user_manage" value="1" /></label></td>
<td><label>Tasks control<input type="checkbox" name="task_manage" value="1" /></label></td>
</tr>
<tr>
<td><label>View all tasks<input type="checkbox" name="all_view" value="1"/></label></td>
</tr>
</table>
</article>
<button className="sub" onClick={this.submit}>Create</button>
</article>
</section>;
}
});
var UserGroup = React.createClass({
getInitialState() {
var data = this.props.data;
return {
id: data.id,
name: data.name,
color: data.color,
creating: data.creating,
editing: data.editing,
reassignment: data.reassignment,
deleting: data.deleting,
task_manage: data.t_group_manage,
user_manage: data.u_group_manage,
all_view: data.all_view,
users_count: data.users.length,
users: data.users
}
},
expand(elem) {
var target = $(elem.target).closest('.user');
target.find('.user_additional').slideToggle();
},
actions(type) {
return function(elem) {
var target = $(elem.target).closest('.user');
target.find('.user_action:not(.user_' + type + ')').hide();
target.find('.user_' + type).slideToggle();
}
},
submit(type) {
var self = this;
return function(elem) {
var target = elem.target;
var ajax_data = {};
ajax_data = getData(target);
ajax_data.id = self.state.id;
if(ajax_data) {
submitting(ajax_data, '/api/user_manage/' + type, 'POST', function (data) {
var response_status = +data;
if (isNaN(response_status)) {
response_status = 1;
}
toast(actions_r[response_status]);
refresh();
}, function (err) {
toast(actions_r[1]);
});
}
else if(!re_color.test(ajax_data.color)) {
toast(actions_r[3]);
$(elem.target).parent().find('input[name="color"]').val('');
}
else {
toast(actions_r[2]);
}
}
},
selectBoxes(elem) {
var target = $(elem.target);
var elemParent = target.closest('.select_box');
elemParent.find('label').removeClass('active_elem');
target.parent().addClass('active_elem');
},
render() {
var self = this;
var group_classes = 'user user_group_color user_group_color_' + this.state.id;
//all users in groups
var users_list = [];
this.state.users.forEach(function(task) {
users_list.push(<article className="item_list">{task.name}</article>);
});
var user_list_block = <article className="select_box">
{users_list}
</article>;
//all groups
var groups_list = [];
groups_list.push(<label className='active_elem'>No group<input type="radio" name="u_group"
defaultChecked onChange={self.selectBoxes} value=''/></label>);
this.props.all_groups.forEach(function(group) {
if(group.id != self.state.id) {
groups_list.push(<label>{group.name}<input type="radio" name="u_group"
onChange={self.selectBoxes} value={group.id}/></label>);
}
});
var group_list_block = <article className="select_box">
{groups_list}
</article>;
var user_group_buttons = '';
if(this.state.id != 0) {
user_group_buttons = <article className="user_bottom">
<button onClick={this.actions('edit')} className="solve_but">Edit</button>
<button onClick={this.actions('delete')}>Delete</button>
</article>;
}
//classes
var create_c = this.state.creating ? 'detect_elem active_elem' : 'detect_elem inactive_elem';
var edit_c = this.state.editing ? 'detect_elem active_elem' : 'detect_elem inactive_elem';
var reassign_c = this.state.reassignment ? 'detect_elem active_elem' : 'detect_elem inactive_elem';
var delete_c = this.state.deleting ? 'detect_elem active_elem' : 'detect_elem inactive_elem';
var users_c = this.state.user_manage ? 'detect_elem active_elem' : 'detect_elem inactive_elem';
var tasks_c = this.state.task_manage ? 'detect_elem active_elem' : 'detect_elem inactive_elem';
var view_c = this.state.all_view ? 'detect_elem active_elem' : 'detect_elem inactive_elem';
return <article className={group_classes}>
<article className="user_top">
<article className="user_head">
<span className="user_name">{this.state.name}</span><br/>
<span className="user_group">Users: {this.state.users_count}</span>
</article>
<article className="user_expand" onClick={this.expand}></article>
</article>
<article className="user_additional">
<article className="user_middle">
<article className="column_half">
<h3>Rights</h3>
<article className={create_c}>Creating</article>
<article className={edit_c}>Editing</article>
<br/>
<article className={reassign_c}>Reassignment</article>
<article className={delete_c}>Deleting</article>
<br/>
<article className={users_c}>Users manage</article>
<article className={tasks_c}>Tasks manage</article>
<br/>
<article className={view_c}>View all tasks</article>
</article>
<article className="column_half">
<h3>Users</h3>
{user_list_block}
</article>
</article>
{user_group_buttons}
<article className="user_action user_edit hidden">
<form>
<input type="text" name="name" placeholder="Name" defaultValue={this.state.name}/><br/>
<input type="text" name="color" placeholder="Color" defaultValue={this.state.color}
className="color_field"/><br/>
<table>
<tr>
<td><label>Creating<input type="checkbox" name="creating" value="1" defaultChecked={this.state.creating}/></label></td>
<td><label>Editing<input type="checkbox" name="editing" value="1" defaultChecked={this.state.editing}/></label></td>
</tr>
<tr>
<td><label>Reassignment<input type="checkbox" name="reassignment" value="1" defaultChecked={this.state.reassignment}/></label></td>
<td><label>Deleting<input type="checkbox" name="deleting" value="1" defaultChecked={this.state.deleting}/></label></td>
</tr>
<tr>
<td><label>Users manage<input type="checkbox" name="user_manage" value="1" defaultChecked={this.state.user_manage}/></label></td>
<td><label>Tasks manage<input type="checkbox" name="task_manage" value="1" defaultChecked={this.state.task_manage}/></label></td>
</tr>
<tr>
<td><label>View all tasks<input type="checkbox" name="all_view" value="1" defaultChecked={this.state.all_view}/></label></td>
</tr>
</table>
</form>
<button onClick={this.submit('edit')}>Edit</button>
</article>
<article className="user_action user_delete hidden">
<h3>Move all users in {this.state.name} to other group?</h3>
<form>
{group_list_block}
</form>
<button onClick={this.submit('deleting')}>Delete</button>
</article>
</article>
</article>;
}
});
var UsersGroupsList = React.createClass({
getInitialState() {
return {
received: false,
error: false,
status: null,
groups: null,
masters: null
}
},
receive() {
var self = this;
submitting(null, '/api/account/status', 'GET', function(status) {
if (typeof status == 'string') {
status = JSON.parse(status);
}
submitting(null, '/api/manage_data/users_group', 'GET', function (data) {
if (typeof data == 'string') {
data = JSON.parse(data);
}
submitting(null, '/api/data_viewing/masters', 'GET', function (masters) {
if (typeof masters == 'string') {
masters = JSON.parse(masters);
}
if (data.status == 0 && masters.status == 0) {
data.body.reverse();
self.setState({
received: true,
error: false,
status,
groups: data.body,
masters: masters.body
});
}
else {
self.setState({
error: true
});
}
}, function (err) {
self.setState({
error: true
});
});
}, function (err) {
self.setState({
error: true
});
});
}, function(err) {
self.setState({
error: true
});
});
},
render() {
var self = this;
refresh = this.receive;
//first load
if(!this.state.received && !this.state.error) {
this.receive();
return <Waiting />;
}
else if(!this.state.received && this.state.error) {
return <Error />;
}
else if(!Boolean(this.state.status.u_manage || this.state.room)) {
return <Forbidden />;
}
//render
else {
var groups = [];
//master group
var master_group_data = {
id: 0,
name: 'Masters',
color: 'none',
creating: 1,
editing: 1,
reassignment: 1,
deleting: 1,
t_group_manage: 1,
u_group_manage: 1,
all_view: 1,
users_count: this.state.masters.length,
users: this.state.masters
};
groups.push(<UserGroup key='0' data={master_group_data} all_groups={self.state.groups} />);
//user groups
this.state.groups.forEach(function(group) {
groups.push(<UserGroup key={group.id + new Date().getTime()} data={group} all_groups={self.state.groups} />);
});
return <article className="task_group_page_inner">
<Menu active="u_groups" data={this.state.status} />
<Creating />
{groups}
</article>;
}
}
});
export default UsersGroupsList; |
index.android.js | kilimondjaro/react-native-couchsurfing-app | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class CouchsurfingApp extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('CouchsurfingApp', () => CouchsurfingApp);
|
src/client/components/profile/ProfileUpdateUser.component.js | DBCDK/content-first | import React from 'react';
import Spinner from '../general/Spinner/Spinner.component';
import T from '../base/T';
export default class ProfileUpdateUser extends React.Component {
onSubmit = e => {
const obj = {
name: this.state.name,
image: this.props.imageId,
acceptedTerms: true,
over13: this.props.acceptedAge
};
e.preventDefault();
this.props.updateProfile(e, obj);
};
constructor(props) {
super(props);
this.state = {
name: props.name,
acceptedAge: props.acceptedAge
};
}
componentDidUpdate(prevProps) {
if (this.props.name !== prevProps.name) {
this.setState({name: this.props.name});
}
}
render() {
const checkActive = () => {
if (this.props.deactivate) {
return {
color: 'var(--silver-chalice)',
backgroundColor: 'var(--alto)'
};
}
return {
color: 'var(--petroleum)',
backgroundColor: 'var(--korn)'
};
};
return (
<div className="d-flex">
<div className="profile__accept-buttonbuffer" />
<button
className="btn Button profile__cancel-button"
data-cy="profile-cancel-btn"
onClick={this.props.cancelLogin}
>
<T component="general" name="cancel" />
</button>
<button
className={'btn Button profile__accept-button'}
style={checkActive()}
onClick={this.onSubmit}
disabled={this.props.deactivate}
data-cy="user-form-submit"
>
<T component="profile" name="acceptAndSubmit" />
{(this.props.isSaving && (
<Spinner size={12} color="white" style={{marginLeft: '10px'}} />
)) ||
''}
</button>
</div>
);
}
}
|
js/components/loaders/Spinner.ios.js | LetsBuildSomething/vmag_mobile |
import React, { Component } from 'react';
import { ActivityIndicatorIOS } from 'react-native';
export default class SpinnerNB extends Component {
prepareRootProps() {
const type = {
height: 80,
};
const defaultProps = {
style: type,
};
return computeProps(this.props, defaultProps);
}
render() {
const getColor = () => {
if (this.props.color) {
return this.props.color;
} else if (this.props.inverse) {
return this.getTheme().inverseSpinnerColor;
}
return this.getTheme().defaultSpinnerColor;
};
return (
<ActivityIndicatorIOS
{...this.prepareRootProps()}
color={getColor()}
size={this.props.size ? this.props.size : 'large'}
/>
);
}
}
|
node_modules/react-color/src/components/sketch-2/Sketch.js | ottomajik/react-demo | 'use strict'; /* @flow */
import React from 'react';
import ReactCSS from 'reactcss';
import { Saturation, Hue, Alpha, Checkboard } from '../common';
import SketchFields from './SketchFields';
import SketchPresetColors from './SketchPresetColors';
export class Sketch extends ReactCSS.Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
}
classes(): any {
return {
'default': {
picker: {
width: this.props.width,
padding: '10px 10px 0',
boxSizing: 'initial',
background: '#fff',
borderRadius: '4px',
boxShadow: '0 0 0 1px rgba(0,0,0,.15), 0 8px 16px rgba(0,0,0,.15)',
},
saturation: {
width: '100%',
paddingBottom: '75%',
position: 'relative',
overflow: 'hidden',
},
Saturation: {
radius: '3px',
shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)',
},
controls: {
display: 'flex',
},
sliders: {
padding: '4px 0',
flex: '1',
},
color: {
width: '24px',
height: '24px',
position: 'relative',
marginTop: '4px',
marginLeft: '4px',
borderRadius: '3px',
},
activeColor: {
Absolute: '0 0 0 0',
borderRadius: '2px',
background: 'rgba(' + this.props.rgb.r + ', ' + this.props.rgb.g + ', ' + this.props.rgb.b + ', ' + this.props.rgb.a + ')',
boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)',
zIndex: '2',
},
hue: {
position: 'relative',
height: '10px',
overflow: 'hidden',
},
Hue: {
radius: '2px',
shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)',
},
alpha: {
position: 'relative',
height: '10px',
marginTop: '4px',
overflow: 'hidden',
},
Alpha: {
radius: '2px',
shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)',
},
},
};
}
handleChange(data: any) {
this.props.onChange(data);
}
render(): any {
return (
<div is="picker">
<div is="saturation">
<Saturation is="Saturation" {...this.props} onChange={ this.handleChange }/>
</div>
<div is="controls" className="flexbox-fix">
<div is="sliders">
<div is="hue">
<Hue is="Hue" {...this.props} onChange={ this.handleChange } />
</div>
<div is="alpha">
<Alpha is="Alpha" {...this.props} onChange={ this.handleChange } />
</div>
</div>
<div is="color">
<div is="activeColor"/>
<Checkboard />
</div>
</div>
<div is="fields">
<SketchFields {...this.props} onChange={ this.handleChange } />
</div>
<div is="presets">
<SketchPresetColors colors={ this.props.presetColors } onClick={ this.handleChange } />
</div>
</div>
);
}
}
Sketch.defaultProps = {
presetColors: ['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#BD10E0', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF'],
width: 200,
};
export default Sketch;
|
components/Table/Holders/Card/Modifiers/Face.js | mattbajorek/blackJackReact | import React, { Component } from 'react';
import center from './Positions/posFace';
import selector from './Positions/symbol';
class Face extends Component {
render() {
let symbol = this.props.symbol;
let number = this.props.number;
// Fixes club positioning issue
if (symbol === '\u2663') {
center[2]['top'] = '68.5714285714%'
} else {
center[2]['top'] = '65.7142857143%'
}
return (
<div>
{center.map((x,i) => {
var insert;
if (i === 0) insert = <img src={require('../../../../../images/'+ selector(symbol) + number + '.png')} />
else insert = symbol
return <div key={i} style={x} className="center-symbol">{insert}</div>;
})}
</div>
)
}
}
export default Face |
app/javascript/mastodon/components/timeline_hint.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
const TimelineHint = ({ resource, url }) => (
<div className='timeline-hint'>
<strong><FormattedMessage id='timeline_hint.remote_resource_not_displayed' defaultMessage='{resource} from other servers are not displayed.' values={{ resource }} /></strong>
<br />
<a href={url} target='_blank'><FormattedMessage id='account.browse_more_on_origin_server' defaultMessage='Browse more on the original profile' /></a>
</div>
);
TimelineHint.propTypes = {
resource: PropTypes.node.isRequired,
url: PropTypes.string.isRequired,
};
export default TimelineHint;
|
test/async-suggestions/AutosuggestApp.js | JacksonKearl/react-autosuggest-ie11-compatible | import React, { Component } from 'react';
import sinon from 'sinon';
import Autosuggest from '../../src/Autosuggest';
import languages from '../plain-list/languages';
import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js';
const getMatchingLanguages = value => {
const escapedValue = escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return languages.filter(language => regex.test(language.name));
};
let app = null;
export const getSuggestionValue = sinon.spy(suggestion => suggestion.name);
export const renderSuggestion = sinon.spy(suggestion => suggestion.name);
export const onChange = sinon.spy((event, { newValue }) => {
app.setState({
value: newValue
});
});
const loadSuggestions = value => {
setTimeout(() => {
if (value === app.state.value) {
app.setState({
suggestions: getMatchingLanguages(value)
});
}
}, 100);
};
export const onSuggestionsFetchRequested = sinon.spy(({ value }) => {
loadSuggestions(value);
});
export const onSuggestionsClearRequested = sinon.spy(() => {
app.setState({
suggestions: []
});
});
export default class AutosuggestApp extends Component {
constructor() {
super();
app = this;
this.state = {
value: '',
suggestions: []
};
}
render() {
const { value, suggestions } = this.state;
const inputProps = {
value,
onChange
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={onSuggestionsFetchRequested}
onSuggestionsClearRequested={onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
highlightFirstSuggestion={true}
/>
);
}
}
|
app/javascript/mastodon/features/public_timeline/index.js | yukimochi/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandPublicTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import ColumnSettingsContainer from './containers/column_settings_container';
import { connectPublicStream } from '../../actions/streaming';
const messages = defineMessages({
title: { id: 'column.public', defaultMessage: 'Federated timeline' },
});
const mapStateToProps = (state, { columnId }) => {
const uuid = columnId;
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === uuid);
const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']);
const onlyRemote = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyRemote']) : state.getIn(['settings', 'public', 'other', 'onlyRemote']);
const timelineState = state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`]);
return {
hasUnread: !!timelineState && timelineState.get('unread') > 0,
onlyMedia,
onlyRemote,
};
};
export default @connect(mapStateToProps)
@injectIntl
class PublicTimeline extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static defaultProps = {
onlyMedia: false,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasUnread: PropTypes.bool,
onlyMedia: PropTypes.bool,
onlyRemote: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch, onlyMedia, onlyRemote } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn(onlyRemote ? 'REMOTE' : 'PUBLIC', { other: { onlyMedia, onlyRemote } }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, onlyMedia, onlyRemote } = this.props;
dispatch(expandPublicTimeline({ onlyMedia, onlyRemote }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote }));
}
componentDidUpdate (prevProps) {
if (prevProps.onlyMedia !== this.props.onlyMedia || prevProps.onlyRemote !== this.props.onlyRemote) {
const { dispatch, onlyMedia, onlyRemote } = this.props;
this.disconnect();
dispatch(expandPublicTimeline({ onlyMedia, onlyRemote }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote }));
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { dispatch, onlyMedia, onlyRemote } = this.props;
dispatch(expandPublicTimeline({ maxId, onlyMedia, onlyRemote }));
}
render () {
const { intl, columnId, hasUnread, multiColumn, onlyMedia, onlyRemote } = this.props;
const pinned = !!columnId;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='globe'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer columnId={columnId} />
</ColumnHeader>
<StatusListContainer
timelineId={`public${onlyRemote ? ':remote' : ''}${onlyMedia ? ':media' : ''}`}
onLoadMore={this.handleLoadMore}
trackScroll={!pinned}
scrollKey={`public_timeline-${columnId}`}
emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other servers to fill it up' />}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
components/Deck/ActivityFeedPanel/ActivityItem.js | slidewiki/slidewiki-platform | import PropTypes from 'prop-types';
import React from 'react';
import likeActivity from '../../../actions/activityfeed/likeActivity';
import {formatDate} from './util/ActivityFeedUtil';
import {navigateAction} from 'fluxible-router';
import {connectToStores} from 'fluxible-addons-react';
import cheerio from 'cheerio';
import DeckTreeStore from '../../../stores/DeckTreeStore';
import Util from '../../common/Util';
import {getLanguageName} from '../../../common';
import {FormattedMessage, defineMessages} from 'react-intl';
class ActivityItem extends React.Component {
handleLike() {
this.context.executeAction(likeActivity, {
id: this.props.activity.id
});
}
//return the position of the node in the deck
getPath(node){
const flatTree = this.props.DeckTreeStore.flatTree;
let path = '';
for (let i=0; i < flatTree.size; i++) {
if (flatTree.get(i).get('type') === node.content_kind && flatTree.get(i).get('id') === node.content_id) {
path = flatTree.get(i).get('path');
let nodeSelector = {id: this.props.selector.id, stype: node.content_kind, sid: node.content_id, spath: path};
let nodeURL = Util.makeNodeURL(nodeSelector, 'deck', 'view', undefined, undefined, true);
return nodeURL;
}
}
return path;
}
handleRefClick(e) {
e.preventDefault();
this.context.executeAction(navigateAction, {
url: this.getPath(this.props.activity)
});
// return false;
}
render() {
const node = this.props.activity;
let IconNode = '';
let SummaryNode = '';
const DateDiv = (
<div className="date">
{formatDate(node.timestamp)}
</div>
);
const commentStyles = {
fontStyle: 'italic',
fontWeight: 400
};
const cheerioContentName = (node.content_name) ? cheerio.load(node.content_name).text() : '';
const viewPath = ((node.content_kind === 'slide') ? '/deck/' + this.props.selector.id + '/slide/' : '/deck/') + node.content_id;
let contentType = node.content_kind;
if (contentType === 'deck') {
contentType = <FormattedMessage id='activity.feed.item.deck' defaultMessage='deck'/>;
} else if (contentType === 'slide') {
contentType = <FormattedMessage id='activity.feed.item.slide' defaultMessage='slide'/>;
}
const nodeRef = (node.content_kind === this.props.selector.stype && node.content_id.split('-')[0] === this.props.selector.sid.split('-')[0]) ? (<span><FormattedMessage id='activity.feed.item.this' defaultMessage='this'/> {contentType}</span>) : (<span>{contentType} <a href={this.getPath(node)} onClick={this.handleRefClick.bind(this)}>{cheerioContentName}</a></span>);
if (node.user_id === '0'|| node.user_id === 'undefined') {
node.user_id = undefined;
}
switch (node.activity_type) {
case 'translate':
IconNode = (<i className="ui translate icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.translated' defaultMessage='translated'/> {nodeRef} <FormattedMessage id='activity.feed.item.to' defaultMessage='to'/>
{/*<a href={'/slideview/' + node.translation_info.content_id}>{node.translation_info.language}</a>*/}
{getLanguageName(node.translation_info.language)}
<br/>
{DateDiv}
</div>
);
break;
case 'share':
IconNode = (<i className="ui share alternate icon"></i>);
const onPlatform = (node.share_info.platform === 'E-mail') ? 'by E-mail' : (' on ' + node.share_info.platform);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.shared' defaultMessage='shared'/> {nodeRef} {onPlatform}
<br/>
{DateDiv}
</div>
);
break;
case 'add':
IconNode = (<i className="ui pencil alternate icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.created' defaultMessage='created'/> {nodeRef}
<br/>
{DateDiv}
</div>
);
break;
case 'edit':
IconNode = (<i className="ui edit icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.edited' defaultMessage='edited'/> {nodeRef}
<br/>
{DateDiv}
</div>
);
break;
case 'move':
IconNode = (<i className="ui arrows alternate icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.moved' defaultMessage='moved'/> {nodeRef}
<br/>
{DateDiv}
</div>
);
break;
case 'comment':
IconNode = (<i className="ui comment outline icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.commented' defaultMessage='commented on'/> {nodeRef}
<br/>
<span style={commentStyles}>{'"' + node.comment_info.text + '"'}</span>
<br/>
{DateDiv}
</div>
);
break;
case 'reply':
IconNode = (<i className="ui comment outline icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a>
<span> <FormattedMessage id='activity.feed.item.reply' defaultMessage='replied to a comment on'/> </span> {nodeRef}
<br/>
<span style={commentStyles}>{'"' + node.comment_info.text + '"'}</span>
<br/>
{DateDiv}
</div>
);
break;
case 'use':
IconNode = (<i className="ui clone outline icon"></i>);
const title = (node.use_info.target_name !== '') ? node.use_info.target_name : node.use_info.target_id;
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.used' defaultMessage='used'/> {nodeRef}
<FormattedMessage id='activity.feed.item.indeck' defaultMessage='in deck'/> <a href={'/deck/' + node.use_info.target_id}>{title}</a>
<br/>
{DateDiv}
</div>
);
break;
case 'attach':
IconNode = (<i className="ui attach icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.attached' defaultMessage='attached'/> {nodeRef}
<br/>
{DateDiv}
</div>
);
break;
case 'rate'://TODO modify rate display
IconNode = (<i className="ui star outline icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.rated' defaultMessage='rated'/> {nodeRef}
<br/>
{DateDiv}
</div>
);
break;
case 'react'://TODO modify react display
IconNode = (<i className="ui thumbs outline up icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ?node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.liked' defaultMessage='liked'/> {nodeRef}
<br/>
{DateDiv}
</div>
);
break;
case 'download':
IconNode = (<i className="ui download icon"></i>);
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.downloaded' defaultMessage='downloaded'/> {nodeRef}
<br/>
{DateDiv}
</div>
);
break;
case 'fork':
IconNode = (<i className="ui fork icon"></i>);
const forkRef = (node.fork_info) ? (<span>, creating a <a href={'/deck/' + node.fork_info.content_id}>new deck</a></span>) : '';
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <FormattedMessage id='activity.feed.item.forked' defaultMessage='forked'/> {nodeRef}{forkRef}
<br/>
{DateDiv}
</div>
);
break;
case 'delete':
IconNode = (<i className="ui trash alternate icon"></i>);
const cheerioDeletedName = (node.delete_info.content_name) ? cheerio.load(node.delete_info.content_name).text() : '';
SummaryNode = (
<div className="summary">
<a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank">
{node.author ? node.author.displayName || node.author.username : 'unknown'}
</a> <span> <FormattedMessage id='activity.feed.item.deleted' defaultMessage='deleted'/> {node.delete_info.content_kind + ' "' + cheerioDeletedName + '" '}</span>
<br/>
<span><FormattedMessage id='activity.feed.item.from' defaultMessage='from'/> {nodeRef}</span>
<br/>
{DateDiv}
</div>
);
break;
default:
}
return (
<div className="ui feed">
<div className="event">
<div className="activity-icon">
{IconNode}
</div>
<div className="content" style={{marginLeft: '1em'}}>
{SummaryNode}
</div>
</div>
</div>
);
}
}
ActivityItem.contextTypes = {
executeAction: PropTypes.func.isRequired
};
ActivityItem = connectToStores(ActivityItem, [DeckTreeStore], (context, props) => {
return {
DeckTreeStore: context.getStore(DeckTreeStore).getState()
};
});
export default ActivityItem;
|
lib/DragContainer.js | deanmcpherson/react-native-drag-drop | import React from 'react';
import {
View,
PanResponder,
Modal,
Easing,
Animated,
TouchableOpacity,
TouchableWithoutFeedback,
} from 'react-native';
global.Easing = Easing;
const allOrientations = [
'portrait', 'portrait-upside-down',
'landscape', 'landscape-left', 'landscape-right'
];
class DragModal extends React.Component {
render() {
let {startPosition} = this.props.content;
return <Modal transparent={true} supportedOrientations={allOrientations}>
<TouchableWithoutFeedback onPressIn={this.props.drop}>
<Animated.View style={this.props.location.getLayout()}>
{this.props.content.children}
</Animated.View>
</TouchableWithoutFeedback>
</Modal>
}
}
class DragContainer extends React.Component {
constructor(props) {
super(props);
this.displayName = 'DragContainer';
this.containerLayout;
let location = new Animated.ValueXY();
this.state = {
location
}
this.dropZones = [];
this.draggables = [];
this.onDrag = this.onDrag.bind(this);
this._handleDragging = this._handleDragging.bind(this);
this._handleDrop = this._handleDrop.bind(this);
this._listener = location.addListener(this._handleDragging);
this.updateZone = this.updateZone.bind(this);
this.removeZone = this.removeZone.bind(this);
}
static propTypes = {
onDragStart: React.PropTypes.func,
onDragEnd: React.PropTypes.func,
}
componentWillUnmount() {
if (this._listener) this.state.location.removeListener(this._listener);
}
getDragContext() {
return {
dropZones: this.dropZones,
onDrag: this.onDrag,
container: this.containerLayout,
dragging: this.state.draggingComponent,
updateZone: this.updateZone,
removeZone: this.removeZone
}
}
getChildContext() {
return {dragContext: this.getDragContext()}
}
static childContextTypes = {
dragContext: React.PropTypes.any
}
updateZone(details) {
let zone = this.dropZones.find(x => x.ref === details.ref);
if (!zone) {
this.dropZones.push(details);
} else {
let i = this.dropZones.indexOf(zone);
this.dropZones.splice(i, 1, details);
}
}
removeZone(ref) {
let i = this.dropZones.find(x => x.ref === ref);
if (i !== -1) {
this.dropZones.splice(i, 1);
}
}
inZone({x, y}, zone) {
return zone.x <= x && (zone.width + zone.x) >= x && zone.y <= y && (zone.height + zone.y) >= y;
}
_addLocationOffset(point) {
if (!this.state.draggingComponent) return point;
return {
x: point.x + (this.state.draggingComponent.startPosition.width / 2),
y: point.y + (this.state.draggingComponent.startPosition.height / 2),
}
}
_handleDragging(point) {
this._point = point;
if (this._locked || !point) return;
this.dropZones.forEach((zone) => {
if (this.inZone(point, zone)) {
zone.onEnter(point);
} else {
zone.onLeave(point);
}
})
}
_handleDrop() {
let hitZones = []
this.dropZones.forEach((zone) => {
if (!this._point) return;
if (this.inZone(this._point, zone)) {
hitZones.push(zone);
zone.onDrop(this.state.draggingComponent.data);
}
})
if (this.props.onDragEnd) this.props.onDragEnd(this.state.draggingComponent, hitZones);
if (!hitZones.length && this.state.draggingComponent && this.state.draggingComponent.ref) {
this._locked = true;
return Animated
.timing(this.state.location, {
duration: 400,
easing:Easing.elastic(1),
toValue: {
x: 0, //this._offset.x - x,
y: 0 //his._offset.y - y
}
}).start(() => {
this._locked = false;
this._handleDragging({x: -100000, y: -100000});
this.setState({
draggingComponent: null
})
})
}
this._handleDragging({x: -100000, y: -100000});
this.setState({
draggingComponent: null
})
}
componentWillMount() {
this._panResponder = PanResponder.create({
// Ask to be the responder:
onStartShouldSetPanResponder: () => {
if (this.state.draggingComponent) {
this._handleDrop();
}
return false
},
onMoveShouldSetPanResponder: (evt, gestureState) => !!this.state.draggingComponent,
// onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
onPanResponderMove: (...args) => Animated.event([null, {
dx: this.state.location.x, // x,y are Animated.Value
dy: this.state.location.y,
}]).apply(this, args),
onPanResponderTerminationRequest: (evt, gestureState) => true,
onPanResponderRelease: (evt, gestureState) => {
if (!this.state.draggingComponent) return;
//Ensures we exit all of the active drop zones
this._handleDrop();
}
});
}
onDrag(ref, children, data) {
ref.measure((...args) => {
if (this._listener) this.state.location.removeListener(this._listener);
let location = new Animated.ValueXY();
this._listener = location.addListener(args => this._handleDragging(this._addLocationOffset(args)));
this._offset = {x: args[4], y: args[5]};
location.setOffset(this._offset);
this.setState({
location,
draggingComponent: {
ref,
data,
children: React.Children.map(children, child => {
return React.cloneElement(child, {dragging: true})
}),
startPosition: {
x: args[4],
y: args[5],
width: args[2],
height: args[3]
}
}}, () => {
if (this.props.onDragStart) this.props.onDragStart(this.state.draggingComponent);
})
});
}
render() {
return <View style={[{flex: 1}, this.props.style]} onLayout={e => this.containerLayout = e.nativeEvent.layout} {...this._panResponder.panHandlers}>
{this.props.children}
{this.state.draggingComponent ? <DragModal content={this.state.draggingComponent} location={this.state.location} drop={this._handleDrop} /> : null}
</View>;
}
}
export default DragContainer;
|
blueprints/view/files/__root__/views/__name__View/__name__View.js | PetrosGit/poker-experiment | import React from 'react'
type Props = {
};
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render () {
return (
<div></div>
)
}
}
export default <%= pascalEntityName %>
|
src/svg-icons/av/pause-circle-filled.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvPauseCircleFilled = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14H9V8h2v8zm4 0h-2V8h2v8z"/>
</SvgIcon>
);
AvPauseCircleFilled = pure(AvPauseCircleFilled);
AvPauseCircleFilled.displayName = 'AvPauseCircleFilled';
AvPauseCircleFilled.muiName = 'SvgIcon';
export default AvPauseCircleFilled;
|
Prac/js/ClientApp.js | JRFrazier/complete-intro-to-react | import React from 'react'
import { render } from 'react-dom'
import '../public/normalize.css'
import '../public/style.css'
const App = React.createClass ({
render () {
return (
<div className='app'>
<div className='landing'>
<h1>svideo</h1>
<input type='text' placeholder='Search' />
<a> or Growse All</a>
</div>
</div>
)
}
})
render(<App />, document.getElementById('app'))
|
node_modules/react-bootstrap/es/Button.js | rblin081/drafting-client | import _Object$values from 'babel-runtime/core-js/object/values';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import elementType from 'prop-types-extra/lib/elementType';
import { bsClass, bsSizes, bsStyles, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
import { Size, State, Style } from './utils/StyleConfig';
import SafeAnchor from './SafeAnchor';
var propTypes = {
active: PropTypes.bool,
disabled: PropTypes.bool,
block: PropTypes.bool,
onClick: PropTypes.func,
componentClass: elementType,
href: PropTypes.string,
/**
* Defines HTML button type attribute
* @defaultValue 'button'
*/
type: PropTypes.oneOf(['button', 'reset', 'submit'])
};
var defaultProps = {
active: false,
block: false,
disabled: false
};
var Button = function (_React$Component) {
_inherits(Button, _React$Component);
function Button() {
_classCallCheck(this, Button);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Button.prototype.renderAnchor = function renderAnchor(elementProps, className) {
return React.createElement(SafeAnchor, _extends({}, elementProps, {
className: classNames(className, elementProps.disabled && 'disabled')
}));
};
Button.prototype.renderButton = function renderButton(_ref, className) {
var componentClass = _ref.componentClass,
elementProps = _objectWithoutProperties(_ref, ['componentClass']);
var Component = componentClass || 'button';
return React.createElement(Component, _extends({}, elementProps, {
type: elementProps.type || 'button',
className: className
}));
};
Button.prototype.render = function render() {
var _extends2;
var _props = this.props,
active = _props.active,
block = _props.block,
className = _props.className,
props = _objectWithoutProperties(_props, ['active', 'block', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {
active: active
}, _extends2[prefix(bsProps, 'block')] = block, _extends2));
var fullClassName = classNames(className, classes);
if (elementProps.href) {
return this.renderAnchor(elementProps, fullClassName);
}
return this.renderButton(elementProps, fullClassName);
};
return Button;
}(React.Component);
Button.propTypes = propTypes;
Button.defaultProps = defaultProps;
export default bsClass('btn', bsSizes([Size.LARGE, Size.SMALL, Size.XSMALL], bsStyles([].concat(_Object$values(State), [Style.DEFAULT, Style.PRIMARY, Style.LINK]), Style.DEFAULT, Button))); |
packages/material-ui-icons/src/CropSquare.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H6V6h12v12z" /></g>
, 'CropSquare');
|
src/lens/positive-space/index.js | ethanselzer/react-image-magnify | import React, { Component } from 'react';
import objectAssign from 'object-assign';
import LensPropTypes from '../../prop-types/Lens';
import clamp from 'clamp';
import dataUri from './assets/textured-lens-data-uri';
export default class PositiveSpaceLens extends Component {
static propTypes = LensPropTypes
static defaultProps = {
style: {}
}
get dimensions() {
const {
cursorOffset: {
x: cursorOffsetX,
y: cursorOffsetY
}
} = this.props;
return {
width: cursorOffsetX * 2,
height: cursorOffsetY * 2
};
}
get positionOffset() {
const {
cursorOffset: {
x: cursorOffsetX,
y: cursorOffsetY
},
position: {
x: positionX,
y: positionY
},
smallImage: {
height: imageHeight,
width: imageWidth
}
} = this.props;
const {
width,
height
} = this.dimensions
const top = positionY - cursorOffsetY;
const left = positionX - cursorOffsetX;
const maxTop = imageHeight - height;
const maxLeft = imageWidth - width;
const minOffset = 0;
return {
top: clamp(top, minOffset, maxTop),
left: clamp(left, minOffset, maxLeft)
};
}
get defaultStyle() {
const { fadeDurationInMs } = this.props;
return {
transition: `opacity ${fadeDurationInMs}ms ease-in`,
backgroundImage: `url(${dataUri})`
};
}
get userSpecifiedStyle() {
const {
style
} = this.props;
return style;
}
get isVisible() {
const {
isActive,
isPositionOutside
} = this.props;
return (
isActive &&
!isPositionOutside
);
}
get priorityStyle() {
const {
width,
height
} = this.dimensions
const {
top,
left
} = this.positionOffset
return {
position: 'absolute',
top: `${top}px`,
left: `${left}px`,
width: `${width}px`,
height: `${height}px`,
opacity: this.isVisible ? 1 : 0
};
}
get compositStyle() {
return objectAssign(
this.defaultStyle,
this.userSpecifiedStyle,
this.priorityStyle
);
}
render() {
return (
<div style={this.compositStyle} />
);
}
}
|
src/MyProfilePage/Team/Team.js | velesin/retroinator | import React from 'react';
import { Link } from 'react-router-dom';
import { Icon, ICONS } from '../../shared';
export function Team({ team }) {
return (
<Link to={`/team/${team.$key}`} className="MyProfilePage_Teams_Team">
<Icon>{ICONS.TEAM}</Icon>
<div>{team.name}</div>
</Link>
);
}
|
src/js/components/Drop/stories/AllNotStretched.js | grommet/grommet | import React from 'react';
import PropTypes from 'prop-types';
import { Box, Drop, Text, ThemeContext } from 'grommet';
const OneDrop = ({ align, target }) => (
<Drop align={align} target={target} stretch={false}>
<Box pad="small" />
</Drop>
);
OneDrop.propTypes = {
align: PropTypes.shape({}).isRequired,
target: PropTypes.shape({}).isRequired,
};
const Set = ({ aligns, label }) => {
const [target, setTarget] = React.useState();
const targetRef = React.useCallback(setTarget, [setTarget]);
return (
<Box border pad="small">
<Text>{label}</Text>
<Box
margin="xlarge"
background="dark-3"
pad={{ horizontal: 'large', vertical: 'medium' }}
align="center"
justify="center"
ref={targetRef}
>
</Box>
{target && (
<>
{aligns.map((align, index) => (
<OneDrop
// eslint-disable-next-line react/no-array-index-key
key={index}
align={align}
target={target}
/>
))}
</>
)}
</Box>
);
};
Set.propTypes = {
aligns: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
label: PropTypes.string.isRequired,
};
const AllDrops = () => (
// Uncomment <Grommet> lines when using outside of storybook
// <Grommet theme={...}>
<ThemeContext.Extend
value={{
global: {
drop: { background: { color: 'white', opacity: 'medium' } },
},
}}
>
<Box direction="row" wrap pad="large" align="center" justify="center">
<Set
label="left: left"
aligns={[
{ top: 'top', left: 'left' },
{ top: 'bottom', left: 'left' },
{ bottom: 'top', left: 'left' },
{ bottom: 'bottom', left: 'left' },
]}
/>
<Set
label="left: right"
aligns={[
{ top: 'top', left: 'right' },
{ top: 'bottom', left: 'right' },
{ bottom: 'top', left: 'right' },
{ bottom: 'bottom', left: 'right' },
]}
/>
<Set
label="(center horizontal)"
aligns={[
{ top: 'top' },
{ top: 'bottom' },
{ bottom: 'top' },
{ bottom: 'bottom' },
]}
/>
<Set
label="right: left"
aligns={[
{ top: 'top', right: 'left' },
{ top: 'bottom', right: 'left' },
{ bottom: 'top', right: 'left' },
{ bottom: 'bottom', right: 'left' },
]}
/>
<Set
label="right: right"
aligns={[
{ top: 'top', right: 'right' },
{ top: 'bottom', right: 'right' },
{ bottom: 'top', right: 'right' },
{ bottom: 'bottom', right: 'right' },
]}
/>
<Set
label="top: top"
aligns={[
{ left: 'left', top: 'top' },
{ left: 'right', top: 'top' },
{ right: 'left', top: 'top' },
{ right: 'right', top: 'top' },
]}
/>
<Set
label="top: bottom"
aligns={[
{ left: 'left', top: 'bottom' },
{ left: 'right', top: 'bottom' },
{ right: 'left', top: 'bottom' },
{ right: 'right', top: 'bottom' },
]}
/>
<Set
label="(center vertical)"
aligns={[
{ left: 'left' },
{ left: 'right' },
{ right: 'left' },
{ right: 'right' },
]}
/>
<Set
label="bottom: top"
aligns={[
{ left: 'left', bottom: 'top' },
{ left: 'right', bottom: 'top' },
{ right: 'left', bottom: 'top' },
{ right: 'right', bottom: 'top' },
]}
/>
<Set
label="bottom: bottom"
aligns={[
{ left: 'left', bottom: 'bottom' },
{ left: 'right', bottom: 'bottom' },
{ right: 'left', bottom: 'bottom' },
{ right: 'right', bottom: 'bottom' },
]}
/>
<Set label="(center vertical and horizontal)" aligns={[{}]} />
</Box>
</ThemeContext.Extend>
// </Grommet>
);
export const AllNotStretched = () => <AllDrops />;
AllNotStretched.storyName = 'All not stretched';
export default {
title: 'Controls/Drop/All not stretched',
};
|
src/index.js | sebpearce/cycad-react | import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { App } from './App';
import { Provider } from 'react-redux';
import createBrowserHistory from 'history/createBrowserHistory';
import { store } from './store';
import { saveState } from './localStorage';
import { throttle } from 'lodash';
import './index.scss';
const history = createBrowserHistory();
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>,
document.getElementById('root'),
);
store.subscribe(throttle(() => {
saveState({
transactions: store.getState().transactions,
categories: store.getState().categories,
});
}, 1000));
|
src/assets/icons/check.js | HackArdennes2017/Project06 | import React from 'react'
export default props =>
<svg viewBox="0 0 100 125" {...props}>
<path
d="M47.215 8.002a42.128 42.128 0 0 0-11.063 1.437C13.799 15.43.476 38.522 6.466 60.877c5.99 22.355 29.083 35.677 51.438 29.687 22.355-5.99 35.677-29.082 29.687-51.437a4 4 0 1 0-7.719 2.062c4.871 18.179-5.852 36.785-24.03 41.656-18.18 4.871-36.786-5.852-41.657-24.03-4.871-18.18 5.852-36.786 24.031-41.657a34.018 34.018 0 0 1 28.844 5.375 4.003 4.003 0 1 0 4.719-6.469 41.972 41.972 0 0 0-24.563-8.062zm43.563 2.969a4 4 0 0 0-2.72 1.28C77.516 23.284 56.444 46.077 44.747 58.409L30.684 46.002a4.007 4.007 0 1 0-5.313 6l17 15a4 4 0 0 0 5.563-.25c11.185-11.702 34.869-37.452 45.906-49a4 4 0 0 0-3.062-6.781z"
overflow="visible"
style={{
textIndent: '0',
textTransform: 'none',
direction: 'ltr',
blockProgression: 'tb',
baselineShift: 'baseline',
color: '#000',
enableBackground: 'accumulate',
}}
/>
</svg>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.