path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ObjectSpread.js | TondaHack/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';
function load(baseUser) {
return [
{ id: 1, name: '1', ...baseUser },
{ id: 2, name: '2', ...baseUser },
{ id: 3, name: '3', ...baseUser },
{ id: 4, name: '4', ...baseUser },
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load({ age: 42 });
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-object-spread">
{this.state.users.map(user => (
<div key={user.id}>{user.name}: {user.age}</div>
))}
</div>
);
}
}
|
examples/sidebar/app.js | rkaneriya/react-router | import React from 'react'
import { createHistory, useBasename } from 'history'
import { Router, Route, Link } from 'react-router'
import data from './data'
require('./app.css')
const history = useBasename(createHistory)({
basename: '/sidebar'
})
class Category extends React.Component {
render() {
const category = data.lookupCategory(this.props.params.category)
return (
<div>
<h1>{category.name}</h1>
{this.props.children || (
<p>{category.description}</p>
)}
</div>
)
}
}
class CategorySidebar extends React.Component {
render() {
const category = data.lookupCategory(this.props.params.category)
return (
<div>
<Link to="/">◀︎ Back</Link>
<h2>{category.name} Items</h2>
<ul>
{category.items.map((item, index) => (
<li key={index}>
<Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link>
</li>
))}
</ul>
</div>
)
}
}
class Item extends React.Component {
render() {
const { category, item } = this.props.params
const menuItem = data.lookupItem(category, item)
return (
<div>
<h1>{menuItem.name}</h1>
<p>${menuItem.price}</p>
</div>
)
}
}
class Index extends React.Component {
render() {
return (
<div>
<h1>Sidebar</h1>
<p>
Routes can have multiple components, so that all portions of your UI
can participate in the routing.
</p>
</div>
)
}
}
class IndexSidebar extends React.Component {
render() {
return (
<div>
<h2>Categories</h2>
<ul>
{data.getAll().map((category, index) => (
<li key={index}>
<Link to={`/category/${category.name}`}>{category.name}</Link>
</li>
))}
</ul>
</div>
)
}
}
class App extends React.Component {
render() {
const { children } = this.props
return (
<div>
<div className="Sidebar">
{children ? children.sidebar : <IndexSidebar />}
</div>
<div className="Content">
{children ? children.content : <Index />}
</div>
</div>
)
}
}
React.render((
<Router history={history}>
<Route path="/" component={App}>
<Route path="category/:category" components={{ content: Category, sidebar: CategorySidebar }}>
<Route path=":item" component={Item} />
</Route>
</Route>
</Router>
), document.getElementById('example'))
|
examples/basic/index.js | hhhonzik/react-createjs | import React from 'react';
import { render } from 'react-dom';
import { App } from './App';
render(<App />, document.getElementById('main'));
|
app/components/ItemInput.js | dxu/electric-trumpet | import React from 'react'
// renders a single list, handles the list of lists
const ItemInput = React.createClass({
onKeyAddContent: function(evt) {
if (evt.keyCode === 13 && !evt.shiftKey) {
evt.preventDefault()
this.props.dispatchAddItem({
// NOTE: ASSUMING CLIENT ONLY, no xss sanitization
content: this._inputContentEl.innerHTML,
archive_id: this.props.activeArchive.get('_id')
})
this._inputContentEl.innerHTML = ''
}
},
onKeyAddTitle: function(evt) {
if (evt.keyCode === 13) {
evt.preventDefault()
this.props.dispatchAddItem({
// NOTE: ASSUMING CLIENT ONLY, no xss sanitization
title: this._inputTitleEl.value,
archive_id: this.props.activeArchive.get('_id')
})
this._inputTitleEl.value = ''
}
},
render: function() {
const { activeArchive, displayArchive=false, contentPlaceholderText="" , titlePlaceholderText="" } = this.props
return (
<div className="items-input" ref={ el => this._wrapperEl = el }>
{
displayArchive ?
<p>Adding to { activeArchive.get('name') }</p> :
null
}
<input className="items-input-title"
contentEditable="true"
placeholder={titlePlaceholderText}
onKeyDown={ this.onKeyAddTitle }
ref={ el => this._inputTitleEl = el } />
<div className="items-input-content"
contentEditable="true"
data-placeholder={contentPlaceholderText}
onKeyDown={ this.onKeyAddTitle }
ref={ el => this._inputContentEl = el }>
</div>
</div>
)
}
})
export default ItemInput
|
src/client.js | sandfox/webdebs-links | import React from 'react';
import Router from 'react-router';
import routes from './routes';
import fetchData from './utils/fetch-data';
let first = true;
const rehydrate = () => {
const data = window.DATA;
delete window.DATA;
return data;
};
const render = (Root, state, data) => {
React.render(<Root data={data} state={state} />, document.getElementById('app'));
};
Router.run(routes, Router.HistoryLocation, (Root, state) => {
if (first) {
first = false;
render(Root, state, rehydrate());
} else {
fetchData(state).then((data) => {
render(Root, state, data);
});
}
});
|
src/app.js | vk92kokil/My-react-boilerplate | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
/* eslint-disable */
import 'babel/polyfill';
import React from 'react';
import Router from 'react-router';
var Redirect = Router.Redirect;
import FastClick from 'fastclick';
import App from './components/App';
import HomePage from './components/HomePage';
import NotFoundHandler from './components/NotFoundPage';
/* react tap event plugin !important for material ui*/
import injectTapEventPlugin from "react-tap-event-plugin";
injectTapEventPlugin();
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var DefaultRoute = Router.DefaultRoute;
var NotFoundRoute = Router.NotFoundRoute;
var routes = (
<Route handler={App} path="/">
{/*<DefaultRoute name="home" handler={CrmApp} />*/}
<Route path='/crm' handler={HomePage}/>
<Redirect from='/' to='/crm'/>
<NotFoundRoute handler={NotFoundHandler}/>
</Route>
);
function run () {
Router.run(routes, Router.HistoryLocation , function(Handler,state) {
React.render(<Handler/>, document.getElementById('app'));
});
};
Promise.all([
new Promise((resolve) => {
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', resolve);
} else {
window.attachEvent('onload', resolve);
}
}).then(() => FastClick.attach(document.body))
]).then(run);
|
src/browser/createRoutes.js | jks8787/react-redux-yay | import App from './app/App.react';
import Auth from './auth/Page.react';
import Firebase from './firebase/Page.react';
import Home from './home/Page.react';
import Me from './me/Page.react';
import NotFound from './notfound/Page.react';
import Profile from './me/Profile.react';
import React from 'react';
import Settings from './me/Settings.react';
import Todos from './todos/Page.react';
import { IndexRoute, Route } from 'react-router';
export default function createRoutes(getState) {
const requireAuth = (nextState, replace) => {
const loggedInUser = getState().users.viewer;
if (!loggedInUser) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
});
}
};
return (
<Route component={App} path="/">
<IndexRoute component={Home} />
<Route component={Auth} path="login" />
<Route component={Firebase} path="firebase" />
<Route component={Me} onEnter={requireAuth} path="me">
<Route component={Profile} path="profile" />
<Route component={Settings} path="settings" />
</Route>
<Route component={Todos} path="todos" />
<Route component={NotFound} path="*" />
</Route>
);
}
|
visualizations/mapWidgets/source/scripts/MapWidgetComponent.js | EITIorg/eiti | import React, { Component } from 'react';
import { renderToString } from 'react-dom/server';
import { Map, Marker, Popup, TileLayer, GeoJson } from 'react-leaflet';
import { countryGeoJson } from './data/countries.js';
//import { countryInfo } from './data/implementing_country.js';
import { helpers } from './helpers.js' ;
import { translations } from './data/translations.js' ;
import _ from 'underscore';
// Legend information
import { indicator_list } from './data/indicator_list.js';
import { status } from './data/status.js';
import { status2 } from './data/status2.js';
import { online_oil_registry } from './data/online_oil_registry.js';
import { online_mining_registry } from './data/online_mining_registry.js';
import { online_contracts } from './data/online_contracts.js';
import { oil_volume } from './data/oil_volume.js';
import { gas_volume } from './data/gas_volume.js';
import { coal_volume } from './data/coal_volume.js';
import { gold_volume} from './data/gold_volume.js';
import { copper_volume } from './data/copper_volume.js';
import { revenue } from './data/revenue.js';
import { share_revenues } from './data/share_revenues.js';
import geostats from 'geostats';
export default class MapWidgetComponent extends Component {
constructor() {
super();
this.state = {
initialized: false,
indicator_id: 'status',
valuetypes: 'fixed',
baseMap: undefined,
data: {},
latlng: {
lat: 18.897489183755892,
lng: 15.76171875
},
hasLocation: false,
};
}
componentWillMount() {
jQuery.get(helpers.getEndPoint() + '?fields=id', function(result) {
var calls = [];
var results = [];
for (var i = 0; i < result.count / helpers.getPageSize(); i++) {
calls.push(
jQuery.get(helpers.getEndPointPage(i + 1), function(result) {
results.push(result.data);
})
);
}
jQuery.when.apply(null, calls).done(function() {
var consolidated = [];
results.forEach(function(r) {
consolidated = consolidated.concat(r);
});
var baseMap = ::this.decorate(consolidated, this.state.indicator_id, this.state.valuetypes);
this.setState({
baseMap: baseMap,
data: consolidated
});
}.bind(this));
}.bind(this));
}
decorate(data, indicator_id, valuetypes) {
var countryGeoJsonProcessed = {
"type" : "FeatureCollection",
"metadata" : [],
"features" : []
};
// Get Legend information
var metadata = ::this.getValues(indicator_id);
countryGeoJson.features.forEach(function(country) {
var datapoint = _.find(data, function(v){ return v.iso3 === country.id;});
if(datapoint) {
var indicator_value = 0;
var indicator_unit = '';
switch(indicator_id) {
case "status":
indicator_value = datapoint.status ? datapoint.status.tid || 0: 0;
break;
case "online_oil_registry":
if(datapoint.licenses) {
var years = Object.keys(datapoint.licenses);
var last = _.last(years);
var yearData = datapoint.licenses[last];
indicator_value = yearData['Public registry of licences, oil'] !== undefined;
}
break;
case "online_mining_registry":
if(datapoint.licenses) {
var years = Object.keys(datapoint.licenses);
var last = _.last(years);
var yearData = datapoint.licenses[last];
indicator_value = yearData['Public registry of licences, mining'] !== undefined;
}
break;
case "online_contracts":
if(datapoint.contracts) {
var years = Object.keys(datapoint.contracts);
var last = _.last(years);
var yearData = datapoint.contracts[last];
indicator_value = yearData['Publicly available registry of contracts'] !== undefined;
}
break;
case "oil_volume":
if(datapoint.reports && Object.keys(datapoint.reports).length > 0) {
var years = Object.keys(datapoint.reports);
var last = _.last(years);
var yearData = datapoint.reports[last];
var indicator = yearData.find(function(v){ return (v.commodity === "Oil, volume" && v.unit && v.unit.toLowerCase() === 'sm3')});
indicator_value = indicator ? indicator.value : 0;
indicator_unit = indicator ? indicator.unit : 0;
}
break;
case "gas_volume":
if(datapoint.reports && Object.keys(datapoint.reports).length > 0) {
var years = Object.keys(datapoint.reports);
var last = _.last(years);
var yearData = datapoint.reports[last];
var indicator = yearData.find(function(v){ return (v.commodity === "Gas, volume" && v.unit && v.unit.toLowerCase() === 'sm3')});
indicator_value = indicator ? indicator.value : 0;
indicator_unit = indicator ? indicator.unit : 0;
}
break;
case "coal_volume":
if(datapoint.reports && Object.keys(datapoint.reports).length > 0) {
var years = Object.keys(datapoint.reports);
var last = _.last(years);
var yearData = datapoint.reports[last];
var indicator = yearData.find(function(v){return (v.commodity === "Coal, volume" && v.unit && (v.unit.toLowerCase() === 'tonne' || v.unit.toLowerCase() === 'tonnes' || v.unit.toLowerCase() === 'tons'))});
indicator_value = indicator ? indicator.value : 0;
indicator_unit = indicator ? indicator.unit : 0;
}
break;
case "gold_volume":
if(datapoint.reports && Object.keys(datapoint.reports).length > 0) {
var years = Object.keys(datapoint.reports);
var last = _.last(years);
var yearData = datapoint.reports[last];
var indicator = yearData.find(function(v){ return (v.commodity === "Gold, volume" && v.unit && (v.unit.toLowerCase() === 'tonne' || v.unit.toLowerCase() === 'tonnes' || v.unit.toLowerCase() === 'tons'))});
indicator_value = indicator ? indicator.value : 0;
indicator_unit = indicator ? indicator.unit : 0;
}
break;
case "copper_volume":
if(datapoint.reports && Object.keys(datapoint.reports).length > 0) {
var years = Object.keys(datapoint.reports);
var last = _.last(years);
var yearData = datapoint.reports[last];
var indicator = yearData.find(function(v){ return (v.commodity === "Copper, volume" && v.unit && (v.unit.toLowerCase() === 'tonne' || v.unit.toLowerCase() === 'tonnes' || v.unit.toLowerCase() === 'tons'))});
indicator_value = indicator ? indicator.value : 0;
indicator_unit = indicator ? indicator.unit : 0;
}
break;
case "revenue":
if(datapoint.revenues) {
var years = Object.keys(datapoint.revenues);
var last = _.last(years);
var yearData = datapoint.revenues[last];
var indicator = yearData.government;
indicator_value = indicator;
indicator_unit = 'USD';
}
break;
case "share_revenues":
if(datapoint.revenues && datapoint.reports) {
var years = Object.keys(datapoint.revenues);
var last = _.last(years);
var yearData = datapoint.revenues[last];
var generalYearData = datapoint.reports[last];
var indicator_government = yearData.government;
var indicator_allsectors = generalYearData ? generalYearData.find(function(v){ return (v.commodity === "Government revenue - all sectors")}) : undefined;
if(indicator_government && indicator_allsectors && indicator_allsectors.value !== 0 && indicator_government !== 0 && indicator_allsectors.unit === 'USD') {
indicator_value = indicator_government*100/indicator_allsectors.value;
}
else
{
indicator_value = 'n/a';
}
indicator_unit = '';
}
break;
}
var indicator_type = valuetypes;
country['indicator_type'] = valuetypes;
country['indicator_value'] = indicator_value;
country['indicator_unit'] = indicator_unit;
}
countryGeoJsonProcessed.features.push(country);
}.bind(this));
if(valuetypes === 'range') {
// Update metadata with ranges
metadata = this.updateMetadata(countryGeoJsonProcessed, metadata);
}
// Assign color with the new metadata
countryGeoJsonProcessed.features.forEach(function(feature) {
var indicator_color;
indicator_color = ::this.getColor(feature.indicator_type, feature.indicator_value, metadata, indicator_id);
feature['indicator_color'] = indicator_color;
}.bind(this));
return countryGeoJsonProcessed;
}
updateMetadata(data, metadata) {
//var values = _.map(_.pluck(data.features, 'indicator_value'),function(v){ return v?v*1:0;});
var part = _.pluck(data.features, 'indicator_unit');
var unit = _.find(part, function(v) { return v !== undefined && v !== "" && v !== 0;});
//var classifier = new geostats(values);
//var ranges = classifier.getEqInterval(metadata.length);
for(var i=0; i< metadata.length;i++) {
metadata[i].unit = unit;
//metadata[i].range.start = ranges[i];
//metadata[i].range.end = ranges[i+1];
//metadata[i].title = helpers.formatNumber(ranges[i]) + ' - ' + helpers.formatNumber(ranges[i+1]);
}
return metadata;
}
addLayer(e) {
//Deactivate anything selected
jQuery('.map-option-wrapper').find("LI").removeClass('active')
//Activate current selected
jQuery(e.target).parents("LI").addClass('active');
//Activate itself
jQuery(e.target).addClass('active')
if(this.removeLayer) this.removeLayer();
const map = this.refs['map'].leafletElement;
var indicator_id = e.target.dataset ? e.target.dataset.indicatorid : e.target.getAttribute("data-indicatorid");
var valuetypes = e.target.dataset ? e.target.dataset.valuetypes : e.target.getAttribute("data-valuetypes");
var countryDataProcessed = ::this.decorate(this.state.data, indicator_id, valuetypes);
const hoverDecider = this.props.infobox ? function(feature, layer){this.onEachFeaturePage(feature, layer)}.bind(this) : function(feature, layer){this.onEachFeatureStatus(feature, layer)}.bind(this);
::this.updateLegend(e, indicator_id);
if (this.props.buttons) {
::this.updateCountriesList(e, countryDataProcessed);
}
this.refs['geoJsonLayer'].leafletElement = L.geoJson(countryDataProcessed, {style:helpers.style, onEachFeature:hoverDecider}).addTo(map);
}
getValues(indicator_id) {
var values;
switch(indicator_id) {
case "status":
values = status;
if(this.props.selector) {
values = status2;
}
break;
case "online_oil_registry":
values = online_oil_registry;
break;
case "online_mining_registry":
values = online_mining_registry;
break;
case "online_contracts":
values = online_contracts;
break;
case "oil_volume":
values = oil_volume;
break;
case "gas_volume":
values = gas_volume;
break;
case "coal_volume":
values = coal_volume;
break;
case "gold_volume":
values = gold_volume;
break;
case "copper_volume":
values = copper_volume;
break;
case "revenue":
values = revenue;
break;
case "share_revenues":
values = share_revenues;
break;
}
return values;
}
removeLayer() {
const map = this.refs['map'].leafletElement;
const geoJsonLayer = this.refs['geoJsonLayer'].leafletElement;
map.removeLayer(geoJsonLayer);
}
legend(indicator_id) {
// For simple status/overview map.
if (indicator_id == 'status' && !this.props.buttons) {
var legend = document.createElement("DIV");
var h2El_2 = document.createElement("H2");
h2El_2.innerText = helpers.t('EITI members');
var indicatorHeader = '<a href="/countries">Click here to view the full interactive map</a>';
var mergedHTML = "";
var headerText = '<div class="legend_header" >' + helpers.t(indicatorHeader) + "</div>";
mergedHTML += headerText;
var divLegendBody = document.createElement("DIV");
divLegendBody.className = "inner";
divLegendBody.innerHTML = mergedHTML;
legend.appendChild(h2El_2);
legend.appendChild(divLegendBody);
return legend;
}
var legend = document.createElement("DIV");
var indicatorMetadata;
indicatorMetadata = ::this.getValues(indicator_id || this.state.indicator_id);
var indicatorData = ::this.getIndicatorData(indicator_id || this.state.indicator_id)
var indicatorDescription = indicatorData["description"];
var indicatorHeader = indicatorData["header"];
var indicatorFooter = indicatorData["footer"];
var unit = _.find(_.pluck(indicatorMetadata, 'unit'), function(v) {return v !== undefined});
var h2El_2 = document.createElement("H2");
h2El_2.innerText = helpers.t(indicatorDescription) + " " + (unit ? "("+unit+ ")" : "");
var mergedHTML = "";
var headerText = '<div class="legend_header" >' + helpers.t(indicatorHeader) + "</div>";
mergedHTML += headerText;
var noDataIncluded = false;
indicatorMetadata.forEach(function(v) {
noDataIncluded = (v.color === "#dddddd" && noDataIncluded === false) ? noDataIncluded = true : false;
if(v.use_style) {
mergedHTML += '<i class="' + v.title.toLowerCase().replace(/<[^>]*>/g, "").replace(/\/| /g,"_") + '"></i> <div class="legend_title">'+helpers.t(v.title)+ '<br/></div>';
}
else {
mergedHTML += '<i style="background:' + v.color + '"></i> <div class="legend_title">'+helpers.t(v.title)+ '<br/></div>';
}
if(v.subtitle != "") {
mergedHTML += (helpers.t(v.subtitle) || '') + '<br>';
}
});
var footerText = '<div class="legend_footer" >' + helpers.t(indicatorFooter) + "</div>";
mergedHTML += footerText;
var sourceText = '<a class="legend_source" href="/data">' + helpers.t('Source: EITI summary data') + "</a>";
var divLegendBody = document.createElement("DIV");
divLegendBody.className = "inner";
divLegendBody.innerHTML = mergedHTML + sourceText;
legend.appendChild(h2El_2);
legend.appendChild(divLegendBody);
return legend;
}
updateLegend(e, indicator_id) {
var legend = this.legend(indicator_id);
var legend_wrapper = jQuery(e.target).closest('.eiti-map-wrapper').find('.top.legend');
legend_wrapper.html(legend.innerHTML);
}
getIndicatorData(indicator_id){
var current_indicator = _.find(indicator_list, function(v){ return (v.name == indicator_id)});
return current_indicator;
}
onEachFeaturePage(feature, layer) {
layer.on({
mouseover: function(e){ helpers.showHint(e) },
mouseout: helpers.resetTooltip,
click: function(e){ helpers.showInfobox(e, this.state.data) }.bind(this)
});
}
onEachFeatureStatus(feature, layer) {
var data = this.state.data;
layer.on({
mouseover: function(e){ helpers.showTooltipStatus(e, data) },
mouseout: helpers.resetTooltip,
click: function(e){ helpers.zoomToFeature(e, data) }
});
}
getColor(indicator_type, indicator_value, metadata, indicator_id) {
if(indicator_type == 'fixed') {
var i_val = indicator_value;
// Limit overview to 2 colors together with status.js changes.
if (indicator_id == 'status' && !this.props.buttons) {
i_val = 0;
if (this.isNumeric(indicator_value) && jQuery.inArray(indicator_value, ['5329', '75', '74', '5327', '8212', '8213']) > -1) {
i_val = 1;
}
}
var completeType = _.find(metadata, function(v){ return (v.id == i_val)});
return completeType ? completeType.color: '#dddddd';
}
else
{
if (metadata === undefined) return;
if(this.isNumeric(indicator_value)) {
var value = Number(indicator_value);
var completeType = _.find(metadata, function(v){ return value > v.range.start && (!v.range.end || value <= v.range.end);});
return completeType !== undefined ? completeType.color : '#dddddd';
}
else
{
return '#dddddd';
}
}
}
isNumeric( obj ) {
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
}
getCountriesList(countryDataProcessed) {
var selector;
if(this.props.selector) {
var listed_countries = [];
if (countryDataProcessed) {
for (var i = 0; i < countryDataProcessed.features.length; i++) {
if (countryDataProcessed.features[i].indicator_value) {
if (countryDataProcessed.features[i].indicator_value != 0 && countryDataProcessed.features[i].indicator_value != 'n/a') {
listed_countries[countryDataProcessed.features[i].id] = [];
listed_countries[countryDataProcessed.features[i].id]['value'] = countryDataProcessed.features[i].indicator_value;
listed_countries[countryDataProcessed.features[i].id]['color'] = countryDataProcessed.features[i].indicator_color;
}
}
}
}
var items = [];
var cols = [];
var countries = _.sortBy(this.state.data, 'label');
var sortedCountries = countries.filter(function(k,v){ return (k.status.name !== "Other")});
if (countryDataProcessed) {
sortedCountries = countries.filter(function(k,v){ return (listed_countries[k.iso3] !== undefined)});
}
var cutout = Math.ceil(sortedCountries.length/4);
for (var i = 0; i < sortedCountries.length;i++) {
var itemStyle = sortedCountries[i].status ? "member-status " + sortedCountries[i].status.name.toLowerCase().replace(/\/| /g,"_") : "member-status other";
var inlineStyles = {};
if (countryDataProcessed) {
inlineStyles = {
background: listed_countries[sortedCountries[i].iso3]['color']
}
}
else if (sortedCountries[i].status.name === "Other") {
continue;
}
var countryPageURL = "/implementing_country/" + sortedCountries[i].id;
var years = Object.keys(sortedCountries[i].metadata);
var last = _.last(years);
var yearData = sortedCountries[i].metadata[last];
// If there's an attached report to the implementing country, use that one. If not, look for it in the metadata
var reportURL = sortedCountries[i].annual_report_file;
var reportClass = "";
if(reportURL === undefined || reportURL === null) {
var reportObj = yearData && yearData.web_report_links && yearData.web_report_links.length > 0 ? _.first(yearData.web_report_links) : undefined;
reportURL = reportObj ? reportObj.url : "";
reportClass = reportObj ? "" : "empty";
}
var country_name = helpers.t(sortedCountries[i].label);
items.push(
<li>
<span style={inlineStyles} className={itemStyle}></span>
<a href={countryPageURL}>{country_name}</a>
</li>
);
if((i+1)%cutout === 0 || i+1 === sortedCountries.length) {
cols.push(
<div className="country-col">
<ul className="country-list">
{items}
</ul>
</div>
);
items = [];
}
}
//Divide in columns by 4
selector = (
<div className="country-list-wrapper clearfix">
{cols}
</div>
);
return selector;
}
}
updateCountriesList(e, countryDataProcessed) {
if (jQuery(e.target).data('indicatorid') == 'status') {
var selector = this.getCountriesList();
}
else {
var selector = this.getCountriesList(countryDataProcessed);
}
var list_wrapper = jQuery(e.target).closest('.eiti-map-wrapper').find('.country-list-wrapper');
list_wrapper.replaceWith(renderToString(selector));
}
filterToggleOpen(e) {
jQuery(e.target).closest('li').toggleClass('open');
}
render() {
//if(!this.state || !this.state.baseMap) return;
const hoverDecider = this.props.infobox ? function(feature, layer){this.onEachFeaturePage(feature, layer)}.bind(this) : function(feature, layer){this.onEachFeatureStatus(feature, layer)}.bind(this);
var geoJsonLayer;
if(this.state.baseMap === undefined) {
geoJsonLayer == null;
}
else {
geoJsonLayer = <GeoJson data={this.state.baseMap} ref='geoJsonLayer' onEachFeature={hoverDecider} style={helpers.style}></GeoJson>;
}
var buttons;
if(this.props.buttons) {
buttons = (<div className="map-option-wrapper">
<h2>{helpers.t('Apply filter')}</h2>
<ul className="map-option-widget">
<li data-indicatorid="status" data-valuetypes="fixed" onClick={::this.addLayer} className="simple active">
{helpers.t('Implementation status')}
</li>
<li className="open">
<span onClick={::this.filterToggleOpen}>{helpers.t('Tax & Legal Framework')}</span>
<ul className="map-option-items">
<li data-indicatorid="online_oil_registry" data-valuetypes="fixed" onClick={::this.addLayer}>{helpers.t('Online oil registry')}</li>
<li data-indicatorid="online_mining_registry" data-valuetypes="fixed" onClick={::this.addLayer}>{helpers.t('Online mining registry')}</li>
<li data-indicatorid="online_contracts" data-valuetypes="fixed" onClick={::this.addLayer}>{helpers.t('Online registry of contracts')}</li>
</ul>
</li>
<li className="open">
<span onClick={::this.filterToggleOpen}>{helpers.t('Production')}</span>
<ul className="map-option-items">
<li data-indicatorid="oil_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Oil, volume')}</li>
<li data-indicatorid="gas_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Gas, volume')}</li>
<li data-indicatorid="coal_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Coal, tons')}</li>
<li data-indicatorid="gold_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Gold, tons')}</li>
<li data-indicatorid="copper_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Copper, tons')}</li>
</ul>
</li>
<li className="open">
<span onClick={::this.filterToggleOpen}>{helpers.t('Revenues')}</span>
<ul className="map-option-items">
<li data-indicatorid="revenue" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Government extractives revenue')}</li>
<li data-indicatorid="share_revenues" data-valuetypes="percentage" onClick={::this.addLayer}>{helpers.t('Share of revenues')}</li>
</ul>
</li>
</ul>
</div>);
}
/* var reportLink = (<svg id="country-report-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160">
<rect x="4.8" y="4" className="st0" width="115" height="151.6"/>
<rect x="4.8" y="4" className="st0" width="20.9" height="151.6"/>
<rect x="44" y="30.1" className="st0" width="57.5" height="31.4"/>
<line className="st0" x1="54.5" y1="40.6" x2="91.1" y2="40.6"/>
<line className="st0" x1="54.5" y1="51" x2="91.1" y2="51"/>
</svg>);*/
var selector = this.getCountriesList();
var screenWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var zoom = 3;
if(this.props.buttons) {
zoom = 2;
}
var min_zoom = 2;
if(screenWidth <= 400) {
zoom = 1;
min_zoom = 1;
}
// If there's a selector, add the responsive classes.
var containerClass = 'map-container';
var elementClass = 'map';
if(selector) {
containerClass = 'map-container media-resizable-element';
elementClass = 'resizable-map';
}
var legend = this.legend(this.state.indicator_id);
var map_output = (
<Map className={elementClass}
center={this.state.latlng}
length={4}
ref='map'
zoom={zoom}
maxZoom={8}
minZoom={min_zoom}
height={500}
scrollWheelZoom={false}
maxBounds={[[-84, -180], [90, 180]]}
maxBoundsViscosity={0.8}
>
<TileLayer
url=''
onLeafletLoad={function(e) {
if(!this.state.initialized) {
this.setState({initialized:true});
}
}.bind(this)}
/>
{geoJsonLayer}
</Map>
);
if (buttons) {
return (
<div className={containerClass}>
<div className="map-data">
<div className="legend top" dangerouslySetInnerHTML={{__html: legend.innerHTML}}></div>
<div className="map-wrap">
{map_output}
</div>
</div>
{buttons}
{selector}
</div>
);
}
else {
return (
<div className={containerClass}>
<div className="legend top" dangerouslySetInnerHTML={{__html: legend.innerHTML}}></div>
<div className="map-wrap">
{map_output}
</div>
{selector}
</div>
);
}
}
}
|
frontend/app/components/Phrasebook/edit.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
import Immutable from 'immutable'
import ProviderHelpers from 'common/ProviderHelpers'
import StateLoading from 'components/Loading'
import StateErrorBoundary from 'components/ErrorBoundary'
import StateSuccessEdit from './states/successEdit'
import StateSuccessDelete from './states/successDelete'
import StateEdit from './states/create'
import AuthenticationFilter from 'components/AuthenticationFilter'
import PromiseWrapper from 'components/PromiseWrapper'
// REDUX
import { connect } from 'react-redux'
// REDUX: actions/dispatch/func
import { createCategory, deleteCategory, fetchCategory, fetchCategories, updateCategory } from 'reducers/fvCategory'
import { fetchDialect, fetchDialect2 } from 'reducers/fvDialect'
import { pushWindowPath } from 'reducers/windowPath'
import selectn from 'selectn'
import { getFormData, handleSubmit } from 'common/FormHelpers'
// Models
import { Document } from 'nuxeo'
import {
STATE_LOADING,
STATE_DEFAULT,
STATE_ERROR,
STATE_SUCCESS,
STATE_SUCCESS_DELETE,
STATE_ERROR_BOUNDARY,
DEFAULT_PAGE,
DEFAULT_PAGE_SIZE,
DEFAULT_LANGUAGE,
DEFAULT_SORT_COL,
DEFAULT_SORT_TYPE,
} from 'common/Constants'
import './Phrasebook.css'
const { array, element, func, number, object, string } = PropTypes
export class PhrasebookEdit extends React.Component {
static propTypes = {
className: string,
copy: object,
groupName: string,
breadcrumb: element,
DEFAULT_PAGE: number,
DEFAULT_PAGE_SIZE: number,
DEFAULT_LANGUAGE: string,
DEFAULT_SORT_COL: string,
DEFAULT_SORT_TYPE: string,
onDocumentCreated: func,
validator: object,
createUrl: string,
// REDUX: reducers/state
computeCategory: object.isRequired,
computeCategories: object.isRequired,
computeCreateCategory: object,
computeDialect: object.isRequired,
computeDialect2: object.isRequired,
routeParams: object.isRequired,
splitWindowPath: array.isRequired,
// REDUX: actions/dispatch/func
createCategory: func.isRequired,
deleteCategory: func.isRequired,
fetchCategory: func.isRequired,
fetchCategories: func.isRequired,
fetchDialect: func.isRequired,
fetchDialect2: func.isRequired,
pushWindowPath: func.isRequired,
updateCategory: func.isRequired,
}
static defaultProps = {
className: 'FormPhrasebook',
groupName: '',
breadcrumb: null,
DEFAULT_PAGE,
DEFAULT_PAGE_SIZE,
DEFAULT_LANGUAGE,
DEFAULT_SORT_COL,
DEFAULT_SORT_TYPE,
}
_commonInitialState = {
errors: [],
formData: {},
isBusy: false,
is403: false,
}
state = {
componentState: STATE_LOADING,
...this._commonInitialState,
}
// NOTE: Using callback refs since on old React
// https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
form = null
setFormRef = (_element) => {
this.form = _element
}
async componentDidMount() {
const copy = this.props.copy
? this.props.copy
: await import(/* webpackChunkName: "PhrasebookCopy" */ './copy').then((_copy) => {
return _copy.default
})
const validator = this.props.validator
? this.props.validator
: await import(/* webpackChunkName: "PhrasebookValidator" */ './validator').then((_validator) => {
return _validator.default
})
await this._getData({ copy, validator })
}
render() {
let content = null
switch (this.state.componentState) {
case STATE_DEFAULT: {
content = this._stateGetEdit()
break
}
case STATE_ERROR: {
content = this._stateGetError()
break
}
case STATE_SUCCESS: {
content = this._stateGetSuccess()
break
}
case STATE_SUCCESS_DELETE: {
content = this._stateGetSuccessDelete()
break
}
case STATE_ERROR_BOUNDARY: {
// STATE_ERROR_BOUNDARY === server or authentication issue
content = this._stateGetErrorBoundary()
break
}
default:
// STATE_LOADING === loading
content = this._stateGetLoading()
}
return content
}
_getData = async (addToState = {}) => {
// Do any loading here...
const { routeParams } = this.props
const { itemId } = routeParams
await this.props.fetchDialect(`/${this.props.routeParams.dialect_path}`)
await this.props.fetchCategory(itemId)
const item = await this._getItem()
if (item.isError) {
this.setState({
componentState: STATE_DEFAULT,
// Note: Intentional == comparison
is403: item.message == '403',
errorMessage: item.message,
...addToState,
})
} else {
this.setState({
errorMessage: undefined,
componentState: STATE_DEFAULT,
valueName: item.name,
valueDescription: item.description,
isTrashed: item.isTrashed,
item: item.data,
...this._commonInitialState,
...addToState,
})
}
}
_stateGetLoading = () => {
const { className } = this.props
return <StateLoading className={className} isEdit copy={this.state.copy} />
}
_stateGetErrorBoundary = () => {
// Make `errorBoundary.explanation` === `errorBoundary.explanationEdit`
const _copy = Object.assign({}, this.state.copy)
_copy.errorBoundary.explanation = this.state.copy.errorBoundary.explanationEdit
return <StateErrorBoundary errorMessage={this.state.errorMessage} copy={this.state.copy} />
}
_stateGetEdit = () => {
const { className, breadcrumb, groupName } = this.props
const { errors, isBusy, isTrashed, valueDescription, valueName } = this.state
return (
<AuthenticationFilter.Container
is403={this.state.is403}
notAuthenticatedComponent={<StateErrorBoundary copy={this.state.copy} errorMessage={this.state.errorMessage} />}
>
<PromiseWrapper
computeEntities={Immutable.fromJS([
{
id: `/${this.props.routeParams.dialect_path}`,
entity: this.props.fetchDialect,
},
])}
>
<StateEdit
copy={this.state.copy}
className={className}
groupName={groupName}
breadcrumb={breadcrumb}
errors={errors}
isBusy={isBusy}
isTrashed={isTrashed}
isEdit
deleteItem={() => {
this.props.deleteCategory(this.state.item.id)
this.setState({
componentState: STATE_SUCCESS_DELETE,
})
}}
onRequestSaveForm={() => {
this._onRequestSaveForm()
}}
setFormRef={this.setFormRef}
valueName={valueName}
valueDescription={valueDescription}
/>
</PromiseWrapper>
</AuthenticationFilter.Container>
)
}
_stateGetError = () => {
// default state handles errors, just call it...
return this._stateGetEdit()
}
_stateGetSuccess = () => {
const { className } = this.props
const { formData, itemUid } = this.state
return (
<StateSuccessEdit
className={className}
copy={this.state.copy}
itemUid={itemUid}
formData={formData}
handleClick={() => {
this._getData()
}}
/>
)
}
_stateGetSuccessDelete = () => {
const { createUrl, className, routeParams } = this.props
const { formData } = this.state
const { siteTheme, dialect_path } = routeParams
const _createUrl = createUrl || `/${siteTheme}${dialect_path}/create/phrasebook`
return (
<StateSuccessDelete createUrl={_createUrl} className={className} copy={this.state.copy} formData={formData} />
)
}
async _handleCreateItemSubmit(formData) {
const { item } = this.state
const newDocument = new Document(item.response, {
repository: item.response._repository,
nuxeo: item.response._nuxeo,
})
// Set new value property on document
newDocument.set({
'dc:description': formData['dc:description'],
'dc:title': formData['dc:title'],
})
// Save document
const _updateCategory = await this.props.updateCategory(newDocument, null, null)
if (_updateCategory.success) {
this.setState({
errors: [],
formData,
itemUid: _updateCategory.pathOrId,
componentState: STATE_SUCCESS,
})
} else {
this.setState({
componentState: STATE_ERROR_BOUNDARY,
errorMessage: _updateCategory.message,
})
}
}
_onRequestSaveForm = async () => {
const formData = getFormData({
formReference: this.form,
})
const valid = () => {
this.setState(
{
isBusy: true,
},
() => {
this._handleCreateItemSubmit(formData)
}
)
}
const invalid = (response) => {
this.setState({
errors: response.errors,
componentState: STATE_ERROR,
})
}
handleSubmit({
validator: this.state.validator,
formData,
valid,
invalid,
})
}
_getItem = async () => {
const { computeCategory, routeParams } = this.props
const { itemId } = routeParams
// Extract data from immutable:
const _computeCategory = await ProviderHelpers.getEntry(computeCategory, itemId)
if (_computeCategory.success) {
// Extract data from object:
const name = selectn(['response', 'properties', 'dc:title'], _computeCategory)
const description = selectn(['response', 'properties', 'dc:description'], _computeCategory)
const isTrashed = selectn(['response', 'isTrashed'], _computeCategory)
// Respond...
return {
isError: _computeCategory.isError,
name,
description,
isTrashed,
data: _computeCategory,
}
}
return { isError: _computeCategory.isError, message: _computeCategory.message }
}
}
// REDUX: reducers/state
const mapStateToProps = (state /*, ownProps*/) => {
const { fvCategory, fvDialect, navigation, windowPath } = state
const { computeCategory, computeCategories, computeCreateCategory } = fvCategory
const { computeDialect, computeDialect2 } = fvDialect
const { splitWindowPath } = windowPath
const { route } = navigation
return {
computeCategory,
computeCategories,
computeCreateCategory,
computeDialect,
computeDialect2,
routeParams: route.routeParams,
splitWindowPath,
}
}
// REDUX: actions/dispatch/func
const mapDispatchToProps = {
createCategory,
deleteCategory,
fetchCategory,
fetchCategories,
fetchDialect,
fetchDialect2,
pushWindowPath,
updateCategory,
}
export default connect(mapStateToProps, mapDispatchToProps)(PhrasebookEdit)
|
client/Pets.js | lizraeli/react-personal-boilerplate | import React from 'react'
import { Card, CardImage, Text, Heading, Section } from 'rebass'
import { Grid, Row, Col } from 'react-flexbox-grid';
const Pets = () => (
<Section>
<Row center="xs">
<Col xs={12} sm={3}>
<Card>
<CardImage width={256}
src={require('./photos/fred.jpeg')}
/>
<Heading level={3}>
Fred
</Heading>
<Text>
First puppy
</Text>
</Card>
</Col>
<Col xs={12} sm={3}>
<Card>
<CardImage width={256}
src={require('./photos/george.jpeg')}
/>
<Heading level={3}>
George
</Heading>
<Text>
Second puppy
</Text>
</Card>
</Col>
</Row>
</Section>
)
export default Pets |
src/components/topic/UpdateForStorySearchWarning.js | mitmedialab/MediaCloud-Web-Tools | import React from 'react';
import { FormattedMessage, FormattedHTMLMessage } from 'react-intl';
import { WarningNotice } from '../common/Notice';
const localMessages = {
title: { id: 'errors.storySwitchover.title', defaultMessage: 'Update for Story-Level Searches' },
intro: { id: 'errors.storySwitchover.intro', defaultMessage: '<b>Your topic query needs to be checked because we have switched to story-level searches.</b>' },
details: { id: 'errors.storySwitchover.details', defaultMessage: 'When you last ran your topic we searched at the sentence level. Since then we have switched over to do everything at the story level, because that is what most people tell us they want. This also helps us save space and make things faster (<a target="_new" href="https://mediacloud.org/news/2018/4/12/switching-to-story-based-searching-on-may-12th">learn more about this change</a>). If your seed query relied on finding multiple words in the same sentence you need to update it.' },
};
const UpdateForStorySearchWarning = () => (
<div className="story-switchover">
<WarningNotice>
<p className="title"><FormattedMessage {...localMessages.title} /></p>
<p><FormattedHTMLMessage {...localMessages.intro} /></p>
<p><FormattedHTMLMessage {...localMessages.details} /></p>
</WarningNotice>
</div>
);
export default UpdateForStorySearchWarning;
|
resources/js/react/search/SearchResultListItem.js | chekun/spore | import React from 'react';
var Avatar = require('../Avatar');
//<SearchResultListItem item=[] />
class SearchResultListItem extends React.Component {
render() {
var item = this.props.item;
if (item["title"]) {
item.type = 3;
} else if (item["intro"]) {
item.type = 2;
} else {
item.type = 1;
}
switch (item.type) {
case 1:
return (
<a href="javascript:void(0);" className="list-group-item">
<Avatar width="30" height="30" icon={item.icon} alt={item.name} />
<span>用户</span>: {item.name}
</a>
);
break;
case 2:
var link = "http://baoz.cn/" + item.id;
return (
<a href={link} target="_blank" className="list-group-item">
<Avatar width="30" height="30" icon={item.icon} alt={item.name} />
<span>群组</span>: {item.name}
</a>
);
break;
case 3:
var link = "http://baoz.cn/" + item.id;
return (
<a href={link} target="_blank" className="list-group-item">
<span>帖子</span>: {item.title}
</a>
);
}
}
}
export default SearchResultListItem
|
create-react-app/src/router.js | wumouren/react-demo | // import React, { Component } from 'react';
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import App from './components/app/App';
import Home from './components/home/Home';
// 两种写法都可以
// export default class Routers extends Component {
// render() {
// return (
// <Router>
// <Switch>
// <Route exact path='/' component={App}/>
// </Switch>
// </Router>
// );
// }
// }
const Routers = () => {
return (
<Router>
<Switch>
<Route exact path='/' component={App}/>
<Route exact path='/home' component={Home}/>
</Switch>
</Router>
);
}
export default Routers; |
src/componentOrElement.js | react-bootstrap/prop-types-extra | import React from 'react';
import createChainableTypeChecker from './utils/createChainableTypeChecker';
function validate(props, propName, componentName, location, propFullName) {
const propValue = props[propName];
const propType = typeof propValue;
if (React.isValidElement(propValue)) {
return new Error(
`Invalid ${location} \`${propFullName}\` of type ReactElement `
+ `supplied to \`${componentName}\`, expected a ReactComponent or a `
+ 'DOMElement. You can usually obtain a ReactComponent or DOMElement '
+ 'from a ReactElement by attaching a ref to it.',
);
}
if (
(propType !== 'object' || typeof propValue.render !== 'function')
&& propValue.nodeType !== 1
) {
return new Error(
`Invalid ${location} \`${propFullName}\` of value \`${propValue}\` `
+ `supplied to \`${componentName}\`, expected a ReactComponent or a `
+ 'DOMElement.',
);
}
return null;
}
export default createChainableTypeChecker(validate);
|
demo/containers/badges-icons.js | nbonamy/react-native-app-components |
import React, { Component } from 'react';
import { StyleSheet, ScrollView, View, Text } from 'react-native';
import { theme, Badge, Icon } from 'react-native-app-components';
export default class BadgesIcons extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ScrollView style={{paddingBottom: 32, paddingLeft: 16, paddingRight: 16}}>
<View style={{flexDirection: 'column'}}>
<Text style={styles.title}>BADGES</Text>
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<Badge primary style={styles.badge}>0</Badge>
<Badge info style={styles.badge}>1</Badge>
<Badge success style={styles.badge}>2</Badge>
<Badge warning style={styles.badge}>3</Badge>
<Badge danger style={styles.badge}>4</Badge>
</View>
</View>
<View style={{flexDirection: 'column'}}>
<Text style={styles.title}>ICONS</Text>
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<Icon name="add-circle" color={theme.colors.primary} size={32} style={styles.icon} />
<Icon name="md-alert" color={theme.colors.danger} size={32} style={styles.icon} />
<Icon font="entypo" name="archive" color={theme.colors.success} size={32} style={styles.icon} />
</View>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
title: {
fontSize: 18,
marginTop: 32,
marginBottom: 16,
color: theme.colors.dark,
},
badge: {
margin: 8,
},
icon: {
margin: 8,
},
});
|
app/javascript/mastodon/containers/admin_component.js | Kirishima21/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
export default class AdminComponent extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
};
render () {
const { locale, children } = this.props;
return (
<IntlProvider locale={locale} messages={messages}>
{children}
</IntlProvider>
);
}
}
|
4.2.0/src/routes.js | erikras/redux-form-docs | import React from 'react'
import { Router, Route, hashHistory } from 'react-router'
import markdownPage from 'components/markdownPage'
import App from 'pages/App'
import Home from 'pages/Home'
import Simple from 'pages/examples/Simple'
import ComplexValues from 'pages/examples/ComplexValues'
import File from 'pages/examples/File'
import Wizard from 'pages/examples/Wizard'
import Deep from 'pages/examples/Deep'
import SynchronousValidation from 'pages/examples/SynchronousValidation'
import SubmitFromParent from 'pages/examples/SubmitFromParent'
import SubmitValidation from 'pages/examples/SubmitValidation'
import AsynchronousBlurValidation from 'pages/examples/AsynchronousBlurValidation'
import AlternateMountPoint from 'pages/examples/AlternateMountPoint'
import Multirecord from 'pages/examples/Multirecord'
import Normalizing from 'pages/examples/Normalizing'
import Dynamic from 'pages/examples/Dynamic'
import InitializingFromState from 'pages/examples/InitializingFromState'
import Examples from 'pages/examples/Examples.md'
import Faq from 'pages/faq/Faq.md'
import FaqEnterToSubmit from 'pages/faq/EnterToSubmit.md'
import FaqSubmitFunction from 'pages/faq/SubmitFunction.md'
import FaqHandleVsOn from 'pages/faq/HandleVsOn.md'
import FaqHowToClear from 'pages/faq/HowToClear.md'
import FaqReactNative from 'pages/faq/ReactNative.md'
import FaqImmutableJs from 'pages/faq/ImmutableJs.md'
import FaqCustomComponent from 'pages/faq/CustomComponent.md'
import FaqWebsockets from 'pages/faq/WebsocketSubmit.md'
import GettingStarted from 'pages/GettingStarted.md'
import Api from 'pages/api/Api.md'
import ApiReduxForm from 'pages/api/ReduxForm.md'
import ApiReducer from 'pages/api/Reducer.md'
import ApiReducerNormalize from 'pages/api/ReducerNormalize.md'
import ApiReducerPlugin from 'pages/api/ReducerPlugin.md'
import ApiProps from 'pages/api/Props.md'
import ApiActionCreators from 'pages/api/ActionCreators.md'
import ApiGetValues from 'pages/api/GetValues.md'
const routes = (
<Router history={hashHistory}>
<Route component={App}>
<Route path="/" component={Home}/>
<Route path="/api" component={markdownPage(Api)}/>
<Route path="/api/action-creators" component={markdownPage(ApiActionCreators)}/>
<Route path="/api/get-values" component={markdownPage(ApiGetValues)}/>
<Route path="/api/props" component={markdownPage(ApiProps)}/>
<Route path="/api/reduxForm" component={markdownPage(ApiReduxForm)}/>
<Route path="/api/reducer" component={markdownPage(ApiReducer)}/>
<Route path="/api/reducer/normalize" component={markdownPage(ApiReducerNormalize)}/>
<Route path="/api/reducer/plugin" component={markdownPage(ApiReducerPlugin)}/>
<Route path="/getting-started" component={markdownPage(GettingStarted)}/>
<Route path="/examples" component={markdownPage(Examples)}/>
<Route path="/examples/asynchronous-blur-validation" component={AsynchronousBlurValidation}/>
<Route path="/examples/alternate-mount-point" component={AlternateMountPoint}/>
<Route path="/examples/deep" component={Deep}/>
<Route path="/examples/initializing-from-state" component={InitializingFromState}/>
<Route path="/examples/dynamic" component={Dynamic}/>
<Route path="/examples/multirecord" component={Multirecord}/>
<Route path="/examples/normalizing" component={Normalizing}/>
<Route path="/examples/simple" component={Simple}/>
<Route path="/examples/complex" component={ComplexValues}/>
<Route path="/examples/file" component={File}/>
<Route path="/examples/wizard" component={Wizard}/>
<Route path="/examples/submit-validation" component={SubmitValidation}/>
<Route path="/examples/synchronous-validation" component={SynchronousValidation}/>
<Route path="/examples/submit-from-parent" component={SubmitFromParent}/>
<Route path="/faq" component={markdownPage(Faq)}/>
<Route path="/faq/submit-function" component={markdownPage(FaqSubmitFunction)}/>
<Route path="/faq/handle-vs-on" component={markdownPage(FaqHandleVsOn)}/>
<Route path="/faq/how-to-clear" component={markdownPage(FaqHowToClear)}/>
<Route path="/faq/enter-to-submit" component={markdownPage(FaqEnterToSubmit)}/>
<Route path="/faq/immutable-js" component={markdownPage(FaqImmutableJs)}/>
<Route path="/faq/react-native" component={markdownPage(FaqReactNative)}/>
<Route path="/faq/custom-component" component={markdownPage(FaqCustomComponent)}/>
<Route path="/faq/websockets" component={markdownPage(FaqWebsockets)}/>
<Route path="*" component={Home}/>
</Route>
</Router>
)
export default routes
|
src/containers/ProductHotItem/ProductHotItem.js | kingpowerclick/kpc-web-backend | import React, { Component } from 'react';
import classNames from 'classnames';
import { FilterPage,
Breadcrumb } from 'components';
import { DropdownButton, MenuItem, Modal } from 'react-bootstrap';
export default class ProductHotItem extends Component {
state = {
displayCompleteModal: false,
displayLineProductModal: false
}
handleOpenAddProductExcModal = () => {
this.setState({
displayCompleteModal: true
});
}
handleCloseModal = () => {
this.setState({
displayCompleteModal: false
});
}
handleOpenLineProductModal = () => {
this.setState({
displayLineProductModal: true
});
}
handleCloseLineProductModal = () => {
this.setState({
displayLineProductModal: false
});
}
handleOpenModal = (styles) => {
const { displayCompleteModal } = this.state;
return (
<Modal show={ displayCompleteModal } dialogClassName={ styles['addproduct-modal'] } >
<Modal.Header>
<Modal.Title className={ styles['modal-title'] }><strong>Add product for Exclusive launch at King Power</strong>
<button
className={ classNames(styles['btn-ghost'], styles['close-modal'])}
onClick={ this.handleCloseModal }>
<i className="fa fa-times"></i>
</button>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className={ styles['addproduct-box'] }>
<div className={ styles['modal-body'] }>
<div className={ styles['select-file']}>
<span>Select file to Import</span>
</div>
<div className="input-group">
<input type="text" className="form-control" placeholder="Chose file"/>
<span className="input-group-btn">
<button className="btn btn-default" type="button">Browse</button>
</span>
</div>
<div className={ styles['download-file'] }>
<a href="Download Sample File">Download Sample File</a>
</div>
<button className={ classNames(styles['btn-blue'], 'btn', 'btn-default') }> Check Data & Upload Now</button>
</div>
</div>
</Modal.Body>
<Modal.Footer></Modal.Footer>
</Modal>
);
}
handleOpenModalLineProduct = (styles) => {
const { displayLineProductModal } = this.state;
return (
<Modal show={ displayLineProductModal } dialogClassName={ styles['addproduct-line-modal'] } >
<Modal.Header>
<Modal.Title className={ styles['modal-title'] }><strong>Add product for Exclusive launch at King Power</strong>
<button
className={ classNames(styles['btn-ghost'], styles['close-modal'])}
onClick={ this.handleCloseLineProductModal }>
<i className="fa fa-times"></i>
</button>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className={ styles['addproduct-line-box'] }>
<div className={ styles['modal-body'] }>
<div className="row">
<div className={ styles['modal-body-left'] }>
<div className={ styles['title-box']}>
<span>Product name or SKU</span>
</div>
<div className={ styles['search-product'] }>
<input type="text" className="form-control" placeholder="Search orders"/>
</div>
<div className={ styles['product-table']}>
<table className="table table-striped">
<thead>
<tr className={ styles['title-table']}>
<th className={ styles['product-checkbox'] }><input type="checkbox"/></th>
<th className={ styles['product-id'] }>Product</th>
<th className={ styles['product-thumbnail'] }>SKU</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"/></td>
<td>MONTBLANC Legend Special Edition EDT 100 มล.</td>
<td>74396</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>COACH New York EDP 50 มล.</td>
<td>74396</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>Barracuda กระเป๋าเดินทางอัจฉริยะ สี Pure Gold</td>
<td>74396</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>KIEHL'S 75ML Powerful-Strength Line-Reducing Concentrate</td>
<td>74396</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className={ styles['modal-body-center'] }>
<div className={ styles['title-box']}>
<i className="fa fa-chevron-right "></i>
</div>
</div>
<div className={ styles['modal-body-right'] }>
<div className={ styles['title-box']}>
<span>Selected product</span>
</div>
<div className={ styles['selected-product-box']}>
<div className={ styles['selected-product-inner']}>
<div className={ styles['selected-product']}>
<span className={ classNames(styles['label-product'], 'label')}>MONTBLANC Legend Special
<button
className={ classNames(styles['btn-ghost'], styles['delete-selected-product'])}>
<i className="fa fa-times"></i>
</button>
</span>
</div>
<div className={ styles['selected-product']}>
<span className={ classNames(styles['label-product'], 'label')}>KIEHL'S 75ML Powerful-Stresssss…
<button
className={ classNames(styles['btn-ghost'], styles['delete-selected-product'])}>
<i className="fa fa-times"></i>
</button>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</Modal.Body>
<Modal.Footer>
<div className={ styles['btn-group']}>
<button type="button" className={classNames( styles['btn-white'], 'btn', 'btn-default') }>Cancel</button>
<button type="button" className={classNames( styles['btn-blue'], 'btn', 'btn-default') }>Add to order now</button>
</div>
</Modal.Footer>
</Modal>
);
}
render() {
const styles = require('./productHotItem.scss');
return (
<div className="container-fluid">
{ this.handleOpenModal(styles) }
{ this.handleOpenModalLineProduct(styles) }
<div className="row">
<div className={ classNames(styles['product-hotitem-view']) }>
<header className={ styles['page-header']}>
<div className={ styles['page-title']}>
<h1 className={ styles.header }><strong>Hot Item</strong></h1>
</div>
<div className={ styles['page-filter']}>
<ul className={ styles['list-filter']}>
<li className={ classNames( styles.filter, styles['add-product'])}>
<div className="dropdown">
<DropdownButton title="Add Exclusive Products" className={ classNames(styles['btn-blue'], 'btn', 'btn-default', 'dropdown-toggle')}>
<MenuItem eventKey="1" onClick={ this.handleOpenLineProductModal }>Add by Line Product</MenuItem>
<MenuItem eventKey="2" onClick={ this.handleOpenAddProductExcModal }>Add by Excel</MenuItem>
<MenuItem eventKey="3">Add by Line Parent Product</MenuItem>
<MenuItem eventKey="4">Add GWP by Excel</MenuItem>
</DropdownButton>
</div>
</li>
</ul>
</div>
<Breadcrumb breadcrumb={ "Product > Hot Item" }/>
</header>
<section className={ styles['wrapper-content']}>
<div className={ styles.content}>
<div className={ classNames(styles['filter-product'])}>
<div className={ classNames(styles['wrapper-filter'])}>
<div className={ styles['filter-left']}>
<div className={ styles['filter-action']}>
<div className="btn-group">
<button type="button" className={ classNames(styles['btn-action'], 'btn', 'btn-default')}>Action</button>
<button type="button" className={ classNames(styles['btn-action-select'], 'btn', 'btn-default', 'dropdown-toggle')} aria-expanded="false">
<span className="caret"></span>
</button>
</div>
</div>
<div className={ styles['filter-id']}>
<div className="input-group">
<div className="input-group-btn">
<button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action <span className="caret"></span></button>
<ul className="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" className="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<input type="text" className={ classNames(styles['input-productid'], 'form-control') } aria-label="..."/>
</div>
</div>
</div>
<div className={ classNames(styles['filter-right']) }>
<FilterPage/>
</div>
</div>
</div>
<div className={ styles['table-detail'] }>
<div className={ styles['tab-content'] }>
<table className="table table-striped">
<thead>
<tr className={ styles['title-table']}>
<th className={ styles['product-checkbox'] }><input type="checkbox"/></th>
<th className={ styles['product-id'] }>ID</th>
<th className={ styles['product-thumbnail'] }>Thumbnail</th>
<th className={ styles['product-name'] }>Name</th>
<th className={ styles['product-type'] }>Type</th>
<th className={ styles['product-attribute'] }>Arttribute Set</th>
<th className={ styles['product-sku'] }>SKU</th>
<th className={ styles['product-price'] }>Price</th>
<th className={ styles['product-qty'] }>Qty</th>
<th className={ styles['product-status'] }>Status</th>
<th className={ styles['product-batch'] }>Batch</th>
<th className={ styles['product-action'] }>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"/></td>
<td>503576</td>
<td><img src="http://via.placeholder.com/50x50"/></td>
<td>EMPORIO ARMANI CLASSIC WATCH</td>
<td>-</td>
<td>default</td>
<td>8169513</td>
<td>11,800.00 THB</td>
<td>172</td>
<td>Enable</td>
<td>batch 110</td>
<td>
<div className="btn-group">
<button type="button" className={ classNames(styles['btn-action'], 'btn', 'btn-default')}>Action</button>
<button type="button" className={ classNames(styles['btn-action-select'], 'btn', 'btn-default', 'dropdown-toggle')} aria-expanded="false">
<span className="caret"></span>
</button>
</div>
</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>503576</td>
<td><img src="http://via.placeholder.com/50x50"/></td>
<td>EMPORIO ARMANI CLASSIC WATCH</td>
<td>Child Product </td>
<td>default</td>
<td>8169513</td>
<td>11,800.00 THB</td>
<td>172</td>
<td>Enable</td>
<td>batch 110</td>
<td>
<div className="btn-group">
<button type="button" className={ classNames(styles['btn-action'], 'btn', 'btn-default')}>Action</button>
<button type="button" className={ classNames(styles['btn-action-select'], 'btn', 'btn-default', 'dropdown-toggle')} aria-expanded="false">
<span className="caret"></span>
</button>
</div>
</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>503576</td>
<td><img src="http://via.placeholder.com/50x50"/></td>
<td>EMPORIO ARMANI CLASSIC WATCH</td>
<td>-</td>
<td>default</td>
<td>8169513</td>
<td>11,800.00 THB</td>
<td>172</td>
<td>Enable</td>
<td>batch 110</td>
<td>
<div className="btn-group">
<button type="button" className={ classNames(styles['btn-action'], 'btn', 'btn-default')}>Action</button>
<button type="button" className={ classNames(styles['btn-action-select'], 'btn', 'btn-default', 'dropdown-toggle')} aria-expanded="false">
<span className="caret"></span>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div className="row">
<div className={ classNames(styles['filter-bottom'])}>
<FilterPage/>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
);
}
}
|
packages/docs/pages/plugin/emoji/index.js | nikgraf/draft-js-plugin-editor | /* eslint-disable no-template-curly-in-string */
import React, { Component } from 'react';
// eslint-disable-next-line import/no-unresolved
import gettingStarted from '!!raw-loader!../../../components/Examples/emoji/gettingStarted';
// eslint-disable-next-line import/no-unresolved
// eslint-disable-next-line import/no-duplicates
import simpleExampleCode from '!!raw-loader!../../../components/Examples/emoji/SimpleEmojiEditor';
// eslint-disable-next-line import/no-unresolved
import simpleEditorStylesCode from '!!raw-loader!../../../components/Examples/emoji/SimpleEmojiEditor/editorStyles.module.css';
// eslint-disable-next-line import/no-unresolved
import webpackConfig from '!!raw-loader!../../../components/Examples/emoji/webpackConfig';
// eslint-disable-next-line import/no-unresolved
// eslint-disable-next-line import/no-duplicates
import customExampleCode from '!!raw-loader!../../../components/Examples/emoji/CustomEmojiEditor';
import styles from './styles.module.css';
import Container from '../../../components/Container/Container';
import Heading from '../../../components/Heading/Heading';
import Code from '../../../components/Code/Code';
// eslint-disable-next-line import/no-duplicates
import SimpleEmojiEditor from '../../../components/Examples/emoji/SimpleEmojiEditor';
// eslint-disable-next-line import/no-duplicates
import CustomEmojiEditor from '../../../components/Examples/emoji/CustomEmojiEditor';
import AlternateContainer from '../../../components/AlternateContainer/AlternateContainer';
import ExternalLink from '../../../components/Link/Link';
import InlineCode from '../../../components/InlineCode/InlineCode';
import PluginPageFrame from '../../../components/PluginPageFrame/PluginPageFrame';
const toneSelectStyles = `.emojiSelectPopoverToneSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 2;
}`;
const priorityListCode = `priorityList: {
':see_no_evil:': ["1f648"],
':raised_hands:': ["1f64c"],
':100:': ["1f4af"],
}`;
const selectGroupsCode = `selectGroups: [{
title: 'Society',
icon: '👥',
categories: ['people', 'food', 'travel'],
}, {
title: 'Objects & symbols',
icon: '❤️',
categories: ['objects', 'symbols'],
}]`;
export default class App extends Component {
render() {
return (
<PluginPageFrame>
<Container>
<Heading level={2}>Emoji</Heading>
<p>
Consistent Emoji display across all platforms, independent of the
host system.
</p>
<Heading level={3}>Attribution to EmojiOne</Heading>
<p>
The beautiful Emoji art used in this plugin is provided by the{' '}
<ExternalLink href="http://emojione.com/">Emoji One</ExternalLink>{' '}
project. Personal or non-commercial use of the emojis do not require
attribution. For the rights to use our emojis still for free in
commercial projects proper attribution in form of a link is
required. More here:{' '}
<ExternalLink href="http://emojione.com/licensing">
http://emojione.com/licensing
</ExternalLink>
.
</p>
<Heading level={3}>Implementation</Heading>
<p>
Emoji unicode characters are wrapped in a span, hidden, and
displayed instead through a background image. This creates
consistency across all platforms while maintaining natural
copy/pasting functionality.
</p>
<p>
If useNativeArt parameter is used, emoji unicode characters are
displayed. This enables displaying platform specific art for emojis.
</p>
<Heading level={3}>Usage</Heading>
<p>
To use simply type <code>:</code> which will show an autocomplete
with matching emojis.
</p>
<Heading level={3}>Supported Environment</Heading>
<ul className={styles.list}>
<li className={styles.listEntry}>Desktop: Yes</li>
<li className={styles.listEntry}>Mobile: Yes</li>
<li className={styles.listEntry}>Screen-reader: Yes</li>
</ul>
</Container>
<AlternateContainer>
<Heading level={2}>Getting Started</Heading>
<Code code="npm install @draft-js-plugins/editor" />
<Code code="npm install @draft-js-plugins/emoji" />
<Code code={gettingStarted} name="gettingStarted.js" />
<Heading level={3}>Importing the default styles</Heading>
<p>
The plugin ships with a default styling available at this location
in the installed package:
<InlineCode
code={'node_modules/@draft-js-plugins/emoji/lib/plugin.css'}
/>
</p>
<Heading level={4}>Webpack Usage</Heading>
<ul className={styles.list}>
<li className={styles.listEntry}>
1. Install Webpack loaders:
<InlineCode code={'npm i style-loader css-loader --save-dev'} />
</li>
<li className={styles.listEntry}>
2. Add the below section to Webpack config (if your config already
has a loaders array, simply add the below loader object to your
existing list.
<Code code={webpackConfig} className={styles.guideCodeBlock} />
</li>
<li className={styles.listEntry}>
3. Add the below import line to your component to tell Webpack to
inject the style to your component.
<Code
code={"import '@draft-js-plugins/emoji/lib/plugin.css';"}
className={styles.guideCodeBlock}
/>
</li>
<li className={styles.listEntry}>4. Restart Webpack.</li>
</ul>
<Heading level={4}>Browserify Usage</Heading>
<p>
Please help, by submiting a Pull Request to the{' '}
<ExternalLink href="https://github.com/draft-js-plugins/draft-js-plugins/blob/master/docs/client/components/pages/Emoji/index.js">
documentation
</ExternalLink>
.
</p>
</AlternateContainer>
<Container>
<Heading level={2}>Configuration Parameters</Heading>
<div className={styles.param}>
<span className={styles.paramName}>theme</span>
<span>Object of CSS classes with the following keys.</span>
<div className={styles.subParams}>
<div className={styles.subParam}>
<span className={styles.subParamName}>emoji:</span>
CSS class for the emoji wrapper.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>emojiSuggestions:</span>
CSS class for suggestions component.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSuggestionsEntry:
</span>
CSS class for an entry in the suggestions component.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSuggestionsEntryFocused:
</span>
CSS class for the focused entry in the suggestions component.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSuggestionsEntryText:
</span>
CSS class for an entry’s text in the suggestions component.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSuggestionsEntryIcon:
</span>
CSS class for an entry’s emoji image in the suggestions
component.
</div>
{/* EmojiSelect styles */}
<div className={styles.subParam}>
<span className={styles.subParamName}>emojiSelect:</span>
CSS class for emoji select component.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>emojiSelectButton:</span>
CSS class for button to open emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectButtonPressed:
</span>
CSS class for pressed state of button to open emoji select
popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>emojiSelectPopover:</span>
CSS class for emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverClosed:
</span>
CSS class for closed state of the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverTitle:
</span>
CSS class for a title of active group in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverGroups:
</span>
CSS class for the emoji groups wrapper in the emoji select
popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverGroup:
</span>
CSS class for a group of emojis in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverGroupTitle:
</span>
CSS class for a title of emoji group in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverGroupList:
</span>
CSS class for a group emoji list in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverGroupItem:
</span>
CSS class for a group emoji list item in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverToneSelect:
</span>
CSS class for tone select in the emoji select popup.
<div>
<em>
Important. The tone select must overlap the emoji select
popup so that disable controls of the popup. By default
</em>
<Code code={toneSelectStyles} />
</div>
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverToneSelectList:
</span>
CSS class for a tone select emoji list in the emoji select
popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverToneSelectItem:
</span>
CSS class for a tone select emoji list item in the emoji select
popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverEntry:
</span>
CSS class for an emoji entry in the emoji select popup
(including tone select).
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverEntryFocused:
</span>
CSS class for the focused emoji entry in the emoji select popup
(including tone select).
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverEntryIcon:
</span>
CSS class for an emoji entry’s image in the emoji select popup
(including tone select).
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverNav:
</span>
CSS class for a group navigation in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverNavItem:
</span>
CSS class for a group navigation item in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverNavEntry:
</span>
CSS class for an entry of the group navigation in the emoji
select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverNavEntryActive:
</span>
CSS class for active state of the group navigation entry in the
emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverScrollbarOuter:
</span>
CSS class for the outer scrollbar box in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverScrollbar:
</span>
CSS class for scrollbar in the emoji select popup.
</div>
<div className={styles.subParam}>
<span className={styles.subParamName}>
emojiSelectPopoverScrollbarThumb:
</span>
CSS class for scrollbar thumb in the emoji select popup.
</div>
</div>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>positionSuggestions</span>
<span>
The function can be used to manipulate the position of the popover
containing the suggestions. It receives one object as arguments
containing the visible rectangle surrounding the decorated search
string including the colon. In addition the object contains
prevProps, prevState, state & props. An object should be returned
which can contain all sorts of styles. The defined properties will
be applied as inline-styles.
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>priorityList</span>
<div>
These entries will be show first in the EmojiSuggestions dropdown
after typing `:`. Must be an object which must contain Emoji
entries used by EmojiOne e.g.
<Code code={priorityListCode} />
</div>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>selectGroups</span>
<div>
Emoji select groups specification. Must be an array of objects,
which declare each group: title, icon (can be a string or React
element), array of emoji categories from EmojiOne e.g.
<Code code={selectGroupsCode} />
</div>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>selectButtonContent</span>
<span>
Content of button which opens emoji select popup. (Default content
is ☺)
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>toneSelectOpenDelay</span>
<span>
Time delay before opening tone select. (Default value is
500 ms)
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>useNativeArt</span>
<span>
If set to <InlineCode code={'true'} />, uses host system art for
emojis instead of EmojiOne art. Default value is{' '}
<InlineCode code={'false'} />.
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>emojiImage</span>
<span>
If provided the passed component is used to render the preview
image for the suggestions. If this parameter is set the{' '}
<InlineCode code={'useNativeArt'} /> is ignored. You can use this
component to implement your own emoji library. It receives the
following props: emoji, unicode and theme
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>emojiInlineText</span>
<span>
If provided the passed component is used to render the emojis in
the text. If this parameter is set the{' '}
<InlineCode code={'useNativeArt'} /> is ignored. You can use this
component to implement your own emoji library. It receives the
following props: decoratedText, className, children and theme
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>disableInlineEmojis</span>
<span>
Disables the suggestion popover for emojis in the editor.
</span>
</div>
<Heading level={3}>EmojiSuggestions</Heading>
<div>
The EmojiSuggestions component is part of the plugin and should
placed somewhere in the JSX after the Editor. It takes the following
props:
<div className={styles.paramBig}>
<span className={styles.paramName}>onSearchChange</span>
<span>
A callback which is triggered whenever the search term changes.
The first argument is an object which constains the search term
in the property value.
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>onOpen</span>
<span>
A callback which is triggered whenever the suggestions popover
opens.
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>onClose</span>
<span>
A callback which is triggered whenever the suggestions popover
closes.
</span>
</div>
</div>
<Heading level={3}>EmojiSelect</Heading>
<div>
The EmojiSelect is another component of the plugin. It takes the
following props:
<div className={styles.paramBig}>
<span className={styles.paramName}>onOpen</span>
<span>
A callback which is triggered whenever the emoji popover opens.
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>onClose</span>
<span>
A callback which is triggered whenever the emoji popover closes.
</span>
</div>
<div className={styles.paramBig}>
<span className={styles.paramName}>closeOnEmojiSelect</span>
<span>
If set to true the popup is closed after an emoji is selected,
otherwise it will stay open.
</span>
</div>
</div>
</Container>
<Container>
<Heading level={2}>Simple Emoji Example</Heading>
<SimpleEmojiEditor />
<Code code={simpleExampleCode} name="SimpleEmojiEditor.js" />
<Code code={simpleEditorStylesCode} name="editorStyles.js" />
</Container>
<Container>
<Heading level={2}>Custom Emoji Example with native emojis</Heading>
<CustomEmojiEditor />
<Code code={customExampleCode} name="SimpleEmojiEditor.js" />
</Container>
</PluginPageFrame>
);
}
}
|
src/index.js | justinkahrs/portfolio | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import '../node_modules/bootstrap/dist/css/bootstrap.css';
import '../node_modules/bootstrap/dist/css/bootstrap-theme.css';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root'),
);
|
client/src/components/calculateButton.js | BukhariH/finimizeChallenge | import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import '../App.css';
import PropTypes from 'prop-types';
class CalculateButton extends Component {
render() {
return (
<button id="calc-btn" name="calc-btn" className="btn btn-success" onClick={this.props.calcFunc}>Figure this all out! 🤓</button>
);
}
}
CalculateButton.propTypes = {
calcFunc: PropTypes.func
};
export default CalculateButton; |
src/components/WebResults/TotalResults.js | nicolas-adamini/littleblue | import React from 'react';
export default function TotalResults(props) {
const number = props.number;
function format(num) {
let n = num.toString(), p = n.indexOf('.');
return n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g, function ($0, i) {
return p < 0 || i < p ? ($0 + ',') : $0;
});
}
return (
<p className="number-of-results">
<small>About {format(number)} results.</small>
</p>
);
} |
springboot/GReact/src/main/resources/static/app/components/forms/wizards/Wizard.js | ezsimple/java | import React from 'react'
export default class Wizard extends React.Component {
componentDidMount() {
let self = this;
let element = $(this.refs.wizard);
var stepsCount = $('[data-smart-wizard-tab]').length;
var currentStep = 1;
var validSteps = [];
var $form = element.closest('form');
var $prev = $('[data-smart-wizard-prev]', element);
var $next = $('[data-smart-wizard-next]', element);
function setStep(step) {
currentStep = step;
$('[data-smart-wizard-pane=' + step + ']', element).addClass('active').siblings('[data-smart-wizard-pane]').removeClass('active');
$('[data-smart-wizard-tab=' + step + ']', element).addClass('active').siblings('[data-smart-wizard-tab]').removeClass('active');
$prev.toggleClass('disabled', step == 1)
}
element.on('click', '[data-smart-wizard-tab]', function (e) {
setStep(parseInt($(this).data('smartWizardTab')));
e.preventDefault();
});
$next.on('click', function (e) {
if ($form.data('validator')) {
if (!$form.valid()) {
validSteps = _.without(validSteps, currentStep);
$form.data('validator').focusInvalid();
return false;
} else {
validSteps = _.without(validSteps, currentStep);
validSteps.push(currentStep);
element.find('[data-smart-wizard-tab=' + currentStep + ']')
.addClass('complete')
.find('.step')
.html('<i class="fa fa-check"></i>');
}
}
if (currentStep < stepsCount) {
setStep(currentStep + 1);
} else {
if (validSteps.length < stepsCount) {
var steps = _.range(1, stepsCount + 1)
_(steps).forEach(function (num) {
if (validSteps.indexOf(num) == -1) {
setStep(num);
return false;
}
})
} else {
var data = {};
_.each($form.serializeArray(), function (field) {
data[field.name] = field.value
});
if (_.isFunction(self.props.onComplete)) {
self.props.onComplete(data)
}
}
}
e.preventDefault();
});
$prev.on('click', function (e) {
if (!$prev.hasClass('disabled') && currentStep > 0) {
setStep(currentStep - 1);
}
e.preventDefault();
});
setStep(currentStep);
}
render() {
let {children, onComplete, ...props} = this.props;
return (
<div {...props} ref="wizard">
{children}
</div>
)
}
} |
src/client/app/boot.js | jsilvestre/tasky | import Application from './components/application';
import logger from 'debug';
import React from 'react';
import { Provider } from 'react-redux';
import startRouter from './router';
import { configureStore } from './store.js';
import en from './locales/en';
import fr from './locales/fr';
const debug = logger('app:boot');
export default function boot(data) {
debug('Prepare application to boot.');
debug('Get localization strings based on given locale.');
const locale = data.locale;
const localesLoader = {en, fr};
let phrases = localesLoader[locale];
if (!phrases) {
debug(`Localized strings could not be found for locale ${locale},` +
`using EN locale instead.`);
phrases = localesLoader.en;
}
// Initialize polyglot object with phrases.
const Polyglot = require('node-polyglot');
const polyglot = new Polyglot({
allowMissing: process.env.NODE_ENV === 'production',
locale: locale,
});
polyglot.extend(phrases);
const store = configureStore(data);
const history = startRouter(store);
const application = (
<Provider store={store}>
<Application router={history} t={polyglot.t.bind(polyglot)}/>
</Provider>
);
debug('Application configured.');
return application;
}
|
src/components/ChallengeList.js | quintel/etmobile | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Challenge from './Challenge';
const sortChallenges = (left, right) => (
left.name.toLowerCase() < right.name.toLowerCase() ? 0 : 1
);
class ChallengeList extends React.Component {
constructor() {
super();
this.state = { challenges: null };
}
componentWillMount() {
const queries = { orderByChild: 'expires' };
if (this.props.active) {
queries.startAt = new Date().getTime();
} else {
queries.endAt = new Date().getTime();
}
this.props.base.fetch('challenges', {
context: this,
asArray: true,
queries
}).then(data =>
this.setState({ challenges: data.sort(sortChallenges) })
);
}
render() {
if (!this.state.challenges) {
return (
<div className="challenge loading">
<FormattedMessage id="challenges.loadingChallenges" />…
</div>
);
}
return (
<div>
{this.state.challenges.map(({ key, name, expires, mode }) => (
<Challenge
key={key}
base={this.props.base}
expires={new Date(expires)}
id={key}
modeName={mode}
name={name}
/>
))}
</div>
);
}
}
ChallengeList.contextTypes = {
router: PropTypes.shape({})
};
ChallengeList.propTypes = {
active: PropTypes.bool,
base: PropTypes.shape({
fetch: PropTypes.func.isRequired
}).isRequired
};
ChallengeList.defaultProps = {
active: false
};
export default ChallengeList;
|
app/javascript/mastodon/components/attachment_list.js | pixiv/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
const filename = url => url.split('/').pop().split('#')[0].split('?')[0];
export default class AttachmentList extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.list.isRequired,
compact: PropTypes.bool,
};
render () {
const { media, compact } = this.props;
if (compact) {
return (
<div className='attachment-list compact'>
<ul className='attachment-list__list'>
{media.map(attachment => {
const displayUrl = attachment.get('remote_url') || attachment.get('url');
return (
<li key={attachment.get('id')}>
<a href={displayUrl} target='_blank' rel='noopener'><i className='fa fa-link' /> {filename(displayUrl)}</a>
</li>
);
})}
</ul>
</div>
);
}
return (
<div className='attachment-list'>
<div className='attachment-list__icon'>
<i className='fa fa-link' />
</div>
<ul className='attachment-list__list'>
{media.map(attachment => {
const displayUrl = attachment.get('remote_url') || attachment.get('url');
return (
<li key={attachment.get('id')}>
<a href={displayUrl} target='_blank' rel='noopener'>{filename(displayUrl)}</a>
</li>
);
})}
</ul>
</div>
);
}
}
|
src/components/Header/Header.js | langpavel/react-starter-kit | /**
* 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 { defineMessages, FormattedMessage } from 'react-intl';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Header.css';
import Link from '../Link';
import Navigation from '../Navigation';
import LanguageSwitcher from '../LanguageSwitcher';
import logoUrl from './logo-small.png';
import logoUrl2x from './[email protected]';
const messages = defineMessages({
brand: {
id: 'header.brand',
defaultMessage: 'Your Company Brand',
description: 'Brand name displayed in header',
},
bannerTitle: {
id: 'header.banner.title',
defaultMessage: 'React',
description: 'Title in page header',
},
bannerDesc: {
id: 'header.banner.desc',
defaultMessage: 'Complex web apps made easy',
description: 'Description in header',
},
});
class Header extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<Navigation />
<Link className={s.brand} to="/">
<img
src={logoUrl}
srcSet={`${logoUrl2x} 2x`}
width="38"
height="38"
alt="React"
/>
<span className={s.brandTxt}>
<FormattedMessage {...messages.brand} />
</span>
</Link>
<LanguageSwitcher />
<div className={s.banner}>
<h1 className={s.bannerTitle}>
<FormattedMessage {...messages.bannerTitle} />
</h1>
<FormattedMessage tagName="p" {...messages.bannerDesc} />
</div>
</div>
</div>
);
}
}
export default withStyles(s)(Header);
|
source/PhoneInputBrowser.js | halt-hammerzeit/react-phone-number-input | import React from 'react'
import PropTypes from 'prop-types'
import PhoneInput_ from './PhoneInput'
import InputSmart from './InputSmart'
import InputBasic from './InputBasic'
export function createInput(defaultMetadata) {
function PhoneInput({
smartCaret,
...rest
}, ref) {
return (
<PhoneInput_
{...rest}
ref={ref}
Component={smartCaret ? InputSmart : InputBasic} />
)
}
PhoneInput = React.forwardRef(PhoneInput)
PhoneInput.propTypes = {
/**
* HTML `<input/>` `type` attribute.
*/
type: PropTypes.string,
/**
* HTML `<input/>` `autocomplete` attribute.
*/
autoComplete: PropTypes.string,
/**
* By default, the caret position is being "intelligently" managed
* while a user inputs a phone number.
* This "smart" caret behavior can be turned off
* by passing `smartCaret={false}` property.
* This is just an "escape hatch" for any possible caret position issues.
*/
// Is `true` by default.
smartCaret: PropTypes.bool.isRequired,
/**
* `libphonenumber-js` metadata.
*/
metadata: PropTypes.object.isRequired
}
PhoneInput.defaultProps = {
/**
* HTML `<input/>` `type="tel"`.
*/
type: 'tel',
/**
* Remember (and autofill) the value as a phone number.
*/
autoComplete: 'tel',
/**
* Set to `false` to use "basic" caret instead of the "smart" one.
*/
smartCaret: true,
/**
* `libphonenumber-js` metadata.
*/
metadata: defaultMetadata
}
return PhoneInput
}
export default createInput() |
src/js/components/widget/Overview.js | kukua/dashboard | import _ from 'underscore'
import React from 'react'
import ControlsWidget from './Controls'
import DevicePickerWidget from './DevicePicker'
import AlertOverviewWidget from './AlertOverview'
import FilterGraphWidget from './FilterGraph'
import DownloadWidget from './Download'
import NotFoundWidget from './NotFound'
const availableWidgets = {
'controls': ControlsWidget,
'device-picker': DevicePickerWidget,
'alert-overview': AlertOverviewWidget,
'filter-graph': FilterGraphWidget,
'download': DownloadWidget,
}
class WidgetOverview extends React.Component {
constructor () {
super()
this.state = {
shared: {},
}
}
onSetShared (key, value) {
var shared = this.state.shared
shared[key] = value
this.setState({ shared })
}
render () {
var rows = [[]]
var columnCount = (row) => _.chain(row)
.map((column) => column[0])
.reduce((memo, num) => memo + num, 0)
.value()
this.props.widgets.forEach((widget, i) => {
var row = rows[rows.length - 1]
widget.columns = Math.min(4, widget.columns || 4)
if (columnCount(row) + widget.columns > 4) {
// New row
rows.push([])
row = rows[rows.length - 1]
}
var Widget = availableWidgets[widget.type] || NotFoundWidget
var widthClass = 'col-md-' + Math.max(1, Math.min(12, widget.columns * 3))
var Container = (
<div key={i} class={widthClass}>
<Widget {...widget} shared={this.state.shared} onSetShared={(key, value) => this.onSetShared(key, value)} />
</div>
)
row.push([widget.columns, Container])
})
return (
<div>
{rows.map((columns, i) => <div key={i} class="row">{columns.map((column) => column[1])}</div>)}
</div>
)
}
}
WidgetOverview.propTypes = {
widgets: React.PropTypes.array.isRequired,
}
export default WidgetOverview
|
client/src/javascript/components/icons/FeedIcon.js | stephdewit/flood | import React from 'react';
import BaseIcon from './BaseIcon';
export default class FeedIcon extends BaseIcon {
render() {
return (
<svg className={`icon icon--feed ${this.props.className}`} viewBox={this.getViewBox()}>
<path d="M18.47,47.88A6.49,6.49,0,1,0,12,54.38,6.5,6.5,0,0,0,18.47,47.88Zm18,3.51a30.41,30.41,0,0,0-8.85-19.12A30.33,30.33,0,0,0,8.48,23.41H8.31A2.07,2.07,0,0,0,6.85,24a2.06,2.06,0,0,0-.71,1.59v4.57a2.14,2.14,0,0,0,2,2.13A21.64,21.64,0,0,1,27.57,51.77a2.14,2.14,0,0,0,2.13,2h4.56A2.06,2.06,0,0,0,35.85,53,2.19,2.19,0,0,0,36.42,51.4Zm17.3,0.07a47.68,47.68,0,0,0-14-31.37,47.55,47.55,0,0,0-31.33-14H8.31a2.1,2.1,0,0,0-1.49.61,2.07,2.07,0,0,0-.68,1.56v4.84a2.15,2.15,0,0,0,2,2.13A38.72,38.72,0,0,1,44.57,51.7a2.15,2.15,0,0,0,2.16,2h4.83A2.19,2.19,0,0,0,53.73,51.46Z" />
</svg>
);
}
}
|
client/pages/examples/threejs/sph/sph.js | fdesjardins/webgl | import React from 'react'
import * as THREE from 'three'
import { MarchingCubes } from 'three/examples/jsm/objects/MarchingCubes'
import tinygradient from 'tinygradient'
import {
createAxes,
addControls,
createParticle,
addAxesLabels,
} from '../graphing/utils'
// import { buildCells, buildCellNeighbors, assignToCell } from './2d-cell-list'
import { buildCells, buildCellNeighbors, assignToCell } from './3d-cell-list'
const WHITE = 0xffffff
const BLACK = 0x000000
const setupOrthoCamera = ({ domain, margin }) => {
const width = domain[1] - domain[0]
const camera = new THREE.OrthographicCamera(
-width / 2 - margin[0],
width / 2 + margin[1],
width / 2 + margin[2],
-width / 2 - margin[3],
0.01,
1000
)
camera.updateProjectionMatrix()
camera.position.z = 50
return camera
}
const setupPerspectiveCamera = ({ width, height }) => {
const camera = new THREE.PerspectiveCamera(35, width / height, 0.1, 1000)
camera.position.x = 0
camera.position.y = 0
camera.position.z = 50
return camera
}
const templatePoint = null
const createParticles = ({ n, size, center }) => {
const point =
templatePoint ||
createParticle({
size,
color: 0x0000ff,
transparent: true,
opacity: 0.65,
})
const particles = []
for (let i = 0; i < n; i += 1) {
const p = point.clone()
p.position.set(
center + (Math.random() - 0.5) * 0.1,
center + (Math.random() - 0.5) * 0.1,
center + (Math.random() - 0.5) * 0.1
)
p.lastPosition = p.position.clone()
particles.push(p)
}
return {
particles,
}
}
// const lines = connections.map(([m, n]) =>
// createConnectingLine(points[m], points[n])
// )
// const lines = []
// lines.map(l => scene.add(l))
const createBoundingCube = () => {
const cubeGeom = new THREE.BoxBufferGeometry(10, 10, 10)
const cubeMat = new THREE.MeshLambertMaterial({
color: 0xeeeeee,
opacity: 0.25,
transparent: true,
side: THREE.BackSide,
})
const cube = new THREE.Mesh(cubeGeom, cubeMat)
return cube
}
const mousePos = (event) => {
const bounds = event.target.getBoundingClientRect()
const xy = {
x: event.clientX - bounds.left,
y: event.clientY - bounds.top,
}
const x = (xy.x / event.target.clientWidth) * 2 - 1
const y = -((xy.y / event.target.clientHeight) * 2 - 1)
return [x, y]
}
const calcF_spring = (particle, obj2, k, restLength) => {
const d = particle.position.clone().sub(obj2.position)
const l = d.length()
const F_spring = d.normalize().multiplyScalar(-1 * k * (l - restLength))
particle.f.add(F_spring)
}
const F_gravity = new THREE.Vector3(0, -9.81, 0)
const F_pressure = new THREE.Vector3(0, 0, 0)
const F_viscosity = new THREE.Vector3(0, 0, 0)
const F = new THREE.Vector3(0, 0, 0)
const tempPressure = new THREE.Vector3(0, 0, 0)
const tempV = new THREE.Vector3(0, 0, 0)
const visc = (r, h) => 45 / (Math.PI * h ** 6)
const poly6f = (r, h) => {
if (r > 0 && r < h) {
return (315 / (64 * h ** 9 * Math.PI)) * (h ** 2 - r ** 2) ** 3
}
return 0
}
const spikyf = (r, h) => 15 / (h ** 6 * Math.PI) / (h - r) ** 3
const poly6fg = (r, h) =>
-1 * r * (945 / (32 * h ** 9 * Math.PI)) * (h ** 2 - r ** 2) ** 2
const sqNorm = (v) => {
return v.x ** 2 + v.y ** 2 + v.z ** 2
}
const norm = (v) => {
return Math.sqrt(sqNorm(v))
}
const calcDensityPressure = (
particles,
neighbors,
{ h, gasConstant, restDensity, mass }
) => {
particles.map((pi, i) => {
pi.density = 0
neighbors[i].map((j) => {
const pj = particles[j]
const dist = pj.position.distanceTo(pi.position)
if (dist < h) {
pi.density += mass * poly6f(dist, h)
}
})
pi.pressure = gasConstant * (pi.density - restDensity)
})
}
const calcForces = (particles, neighbors, { h, viscosity, mass }) => {
particles.map((pi, i) => {
F_pressure.set(0, 0, 0)
F_viscosity.set(0, 0, 0)
F.set(0, 0, 0)
if (!neighbors || neighbors.length === 0) {
return
}
neighbors[i].map((j) => {
const pj = particles[j]
const r = pj.position.distanceTo(pi.position)
if (r < h) {
tempPressure
.copy(pj.position)
.sub(pi.position)
.normalize()
.multiplyScalar((-1 * (pi.pressure + pj.pressure)) / 2)
F_pressure.add(tempPressure)
tempV
.copy(pj.v)
.sub(pi.v)
.multiplyScalar(
((viscosity * mass) / pj.density) * visc(r, h) * (h - r)
)
F_viscosity.add(tempV)
}
})
F.add(F_gravity)
F.add(F_pressure)
F.add(F_viscosity)
pi.f.add(F)
})
}
// gravity (m/s)
const G = -9.81
const config = {
scene: {
domain: [-20, 20],
gridSize: 1,
// l,r,t,b
margin: [4, 4, 4, 4],
surfaceResolution: 26,
},
sim: {
numParticles: 700,
numToAdd: 8,
particleSize: 1,
},
sph: {
h: 4,
gasConstant: 100,
mass: 5,
restDensity: 1,
viscosity: 30,
},
}
const width = config.scene.domain[1] - config.scene.domain[0]
const center = (config.scene.domain[1] + config.scene.domain[0]) / 2
const init = ({ state }) => {
const canvas = document.getElementById('sph')
let scene = new THREE.Scene()
scene.background = new THREE.Color(WHITE)
let renderer = new THREE.WebGLRenderer({ canvas, antialias: true })
renderer.setSize(canvas.clientWidth, canvas.clientWidth)
const ambientLight = new THREE.AmbientLight(0x707070)
scene.add(ambientLight)
const pointLight = new THREE.PointLight(WHITE)
pointLight.position.set(20, 20, -20)
scene.add(pointLight)
const { domain, gridSize, margin } = config.scene
const camera = setupOrthoCamera({ domain, margin })
// const camera = setupPerspectiveCamera({
// width: canvas.width,
// height: canvas.height
// })
const controls = addControls({ camera, renderer })
controls.target.set(center, center, 0)
controls.update()
const grid = new THREE.GridHelper(
domain[1] - domain[0],
(domain[1] - domain[0]) / gridSize,
0x000000,
0xf2f2f2
)
grid.rotation.x = Math.PI / 2
grid.position.set(center, center, 0)
const axes = createAxes({ size: (domain[1] - domain[0]) / 2, fontSize: 0 })
axes.position.set(center, center, 0)
scene.add(axes)
addAxesLabels({ scene, domain, gridSize })
// let lastMousePos = { x: 0.5, y: 0.5 }
// let label
// canvas.onmousemove = event => {
// const [x, y] = mousePos(event)
// lastMousePos = {
// x,
// y
// }
// }
// canvas.onmouseleave = () => {
// lastMousePos = { x: 0.5, y: 0.5 }
// if (label) {
// scene.remove(label)
// label = null
// }
// }
// const raycaster = new THREE.Raycaster()
const arrowHelper = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0).normalize(),
new THREE.Vector3(0, 0, 0),
width / 4,
BLACK
)
scene.add(arrowHelper)
const { numParticles, numToAdd, particleSize } = config.sim
const particles = []
const connectionsMap = []
let n = 0
const particlesSceneNode = new THREE.Group()
const particleEmitters = [
new THREE.Vector3(15, 18, 15),
new THREE.Vector3(-15, 18, 15),
new THREE.Vector3(15, 18, -15),
new THREE.Vector3(-15, 18, -15),
]
const interval = setInterval(() => {
const { particles: newParticles } = createParticles({
n: numToAdd,
size: particleSize,
center,
})
newParticles.map((p, i) => {
p.position.add(particleEmitters[i % 4])
p.lastPosition = p.position.clone()
p.v = new THREE.Vector3(0, 0, 0)
p.f = new THREE.Vector3(0, 0, 0)
p.lastf = new THREE.Vector3(0, 0, 0)
const len = particles.length
connectionsMap[len] = []
connectionsMap.map((_, j) => {
connectionsMap[j].push(len)
connectionsMap[len].push(j)
})
particles.push(p)
particlesSceneNode.add(p)
})
n += numToAdd
if (n >= numParticles) {
clearInterval(interval)
}
}, 100)
const tempPos = new THREE.Vector3()
const F_g = new THREE.Vector3(0, G, 0)
const xAxis = new THREE.Vector3(1, 0, 0)
const zAxis = new THREE.Vector3(0, 0, 1)
let thenSecs = 0
const cellmin = domain[0]
const cellmax = domain[1]
const cellw = 2.5
const stride = (domain[1] - domain[0]) / cellw
const cells = buildCells({ cellmin, cellmax, cellw })
const cellNeighbors = buildCellNeighbors(cells, {
cellmin,
cellmax,
cellw,
stride,
})
const cubesMaterial = new THREE.MeshPhongMaterial({
color: 0xcccccc,
opacity: 0.85,
transparent: true,
refractionRatio: 0.5,
vertexColors: THREE.VertexColors,
shininess: 60,
})
let cubesInstance = new MarchingCubes(24, cubesMaterial, true, true)
cubesInstance.position.set(0, 0, 0)
cubesInstance.scale.set(40, 40, 40)
const carribean = [
'#cbdcf2',
'#91e1e9',
'#00c0e3',
'#0096cc',
'#006fb6',
'#044185',
]
const lava = ['#fff1a1', '#d9a848', '#c93200', '#841800', '#3d0a03']
const acid = ['#b0bf1a', '#3b8e22', '#1e4d2b', '#0d2b0f']
const gradient = tinygradient(lava)
const lookUpTable = {}
const gradientMax = config.sph.restDensity * 2
const gradientMin = config.sph.restDensity / 2
for (let i = gradientMin; i <= gradientMax; i += 0.1) {
lookUpTable[i.toFixed(1).toString()] = new THREE.Color(
gradient.rgbAt(i / gradientMax).toHexString()
)
}
const maxColor = new THREE.Color(
lookUpTable[Object.keys(lookUpTable).length - 1]
)
const animate = (now) => {
if (!renderer) {
return
}
controls.update()
requestAnimationFrame(animate)
const nowSecs = now * 0.001
let deltaSecs = nowSecs - thenSecs
thenSecs = nowSecs
if (!deltaSecs) {
deltaSecs = 0
}
const dt = state.get('timestep')
F_gravity.copy(F_g)
.applyAxisAngle(zAxis, 0.5 * Math.sin(nowSecs / 2))
.applyAxisAngle(xAxis, 0.5 * Math.cos(nowSecs / 3))
arrowHelper.setDirection(F_gravity.clone().normalize())
// Rebuild neighbors list
const particleCellIndices = particles.map((p) => {
return assignToCell(cells, cellw, p.position)
})
const neighbors = particleCellIndices.map((cellIndex) => {
const neighboringCells = cellNeighbors[cellIndex]
const nb = []
particleCellIndices.map((b, j) => {
if (neighboringCells.includes(b) || cellIndex === b) {
nb.push(j)
}
})
return nb
})
particles.map((p, i) => {
p.lookAt(camera.position)
// Velocity Verlet Method
// tempV.copy(p.v).multiplyScalar(dt)
// tempPos.copy(p.position).add(tempV)
// tempV
// .copy(p.f)
// .divideScalar(2)
// .multiplyScalar(dt ** 2)
// tempPos.add(tempV)
// p.position.copy(tempPos)
// p.lastf.copy(p.f)
p.f.set(0, 0, 0)
})
// Calculate forces
calcDensityPressure(particles, neighbors, config.sph)
//
// const mousePosVec = new THREE.Vector2(lastMousePos.x, lastMousePos.y)
// raycaster.setFromCamera(mousePosVec, camera)
// const intersects = raycaster.intersectObjects(particles)
// if (intersects.length > 0) {
// intersects[0].object.pressure += 500
// }
calcForces(particles, neighbors, config.sph)
const particleRadius = particleSize / 2
particles.map((p, i) => {
// Euler Method
// const newPos = p.position.clone().add(p.v.clone().multiplyScalar(dt))
// const newVel = p.v.clone().add(p.f.clone().multiplyScalar(dt))
// p.lastPosition.copy(p.position)
// p.position.copy(newPos)
// p.v.copy(newVel)
// Verlet Method
tempPos
.copy(p.position)
.multiplyScalar(2)
.sub(p.lastPosition)
.add(p.f.clone().multiplyScalar(dt ** 2))
p.lastPosition.copy(p.position)
p.position.copy(tempPos)
p.v
.copy(tempPos)
.sub(p.lastPosition)
.divideScalar(2 * dt)
// Velocity Verlet
// tempV
// .copy(p.f)
// .add(p.lastf)
// .divideScalar(2)
// .multiplyScalar(dt)
// p.v.add(tempV)
// Handle Boundary Conditions
const damping = -0.8
if (p.position.x + particleRadius > domain[1]) {
p.v.x = damping * p.v.x
p.position.x = domain[1] - particleRadius
} else if (p.position.x - particleRadius < -1 * domain[1]) {
p.v.x = damping * p.v.x
p.position.x = domain[0] + particleRadius
}
if (p.position.y + particleRadius > domain[1]) {
p.v.y = damping * p.v.y
p.position.y = domain[1] - particleRadius
} else if (p.position.y - particleRadius < -1 * domain[1]) {
p.v.y = damping * p.v.y
p.position.y = domain[0] + particleRadius
}
if (p.position.z + particleRadius > domain[1]) {
p.v.z = damping * p.v.z
p.position.z = domain[1] - particleRadius
} else if (p.position.z - particleRadius < -1 * domain[1]) {
p.v.z = damping * p.v.z
p.position.z = domain[0] + particleRadius
}
})
cubesInstance.reset()
// Update color of particles and fluid
particles.map((p) => {
const color = lookUpTable[p.density.toFixed(1)] || maxColor
p.material.color.set(color)
cubesInstance.addBall(
(p.position.x + 40) / 80,
(p.position.y + 40) / 80,
(p.position.z + 40) / 80,
0.025,
7,
new THREE.Color(color)
)
})
// if (label) {
// label.lookAt(camera.position)
// }
// if (intersects.length === 0 && label) {
// scene.remove(label)
// label = null
// } else if (intersects.length > 0) {
// const target = intersects[0]
// const { position, v, density, pressure } = target.object
// if (label) {
// scene.remove(label)
// label = null
// }
// label = createLabel({
// text: `Pos: (${position.x.toFixed(2)}, ${position.y.toFixed(
// 2
// )})\nVel: (${v.x.toFixed(2)})\nDen: (${density.toFixed(
// 2
// )})\nPrs: (${pressure.toFixed(2)})`,
// color: BLACK,
// size: gridSize / 2
// })
// label.position.set(
// target.object.position.x,
// target.object.position.y,
// target.object.position.z
// )
// const labelToCam = label.position.clone().sub(camera.position)
// labelToCam.normalize()
// label.position.sub(labelToCam.multiplyScalar(10))
// scene.add(label)
// label.lookAt(camera.position)
// }
if (state.get('showGrid')) {
scene.add(grid)
} else {
scene.remove(grid)
}
if (state.get('showSurface')) {
scene.add(cubesInstance)
} else {
scene.remove(cubesInstance)
}
if (state.get('showParticles')) {
scene.add(particlesSceneNode)
} else {
scene.remove(particlesSceneNode)
}
config.sph.viscosity = state.get('viscosity')
const surfaceResolution = state.get('surfaceResolution')
if (config.scene.surfaceResolution !== surfaceResolution) {
scene.remove(cubesInstance)
cubesInstance = new MarchingCubes(
surfaceResolution,
cubesMaterial,
true,
true
)
cubesInstance.position.set(0, 0, 0)
cubesInstance.scale.set(40, 40, 40)
config.scene.surfaceResolution = surfaceResolution
}
renderer.render(scene, camera)
}
animate()
return () => {
renderer.dispose()
scene = null
renderer = null
}
}
const SPH = ({ state, labels }) => {
React.useEffect(() => {
if (document.getElementById('sph')) {
return init({ state })
}
})
return <canvas id="sph" />
}
export { init }
export default SPH
|
packages/react-jsx-highcharts/src/components/FunnelSeries/FunnelSeries.js | AlexMayants/react-jsx-highcharts | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Series from '../Series';
class FunnelSeries extends Component {
static propTypes = {
id: PropTypes.string.isRequired
};
render () {
return (
<Series {...this.props} type="funnel" />
);
}
}
export default FunnelSeries;
|
packages/material-ui-icons/src/SettingsInputAntenna.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let SettingsInputAntenna = props =>
<SvgIcon {...props}>
<path d="M12 5c-3.87 0-7 3.13-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.87-3.13-7-7-7zm1 9.29c.88-.39 1.5-1.26 1.5-2.29 0-1.38-1.12-2.5-2.5-2.5S9.5 10.62 9.5 12c0 1.02.62 1.9 1.5 2.29v3.3L7.59 21 9 22.41l3-3 3 3L16.41 21 13 17.59v-3.3zM12 1C5.93 1 1 5.93 1 12h2c0-4.97 4.03-9 9-9s9 4.03 9 9h2c0-6.07-4.93-11-11-11z" />
</SvgIcon>;
SettingsInputAntenna = pure(SettingsInputAntenna);
SettingsInputAntenna.muiName = 'SvgIcon';
export default SettingsInputAntenna;
|
src/app/User.js | halhenke/life-letters | import React from 'react';
import classnames from 'classnames';
import styles from './User.css';
import {GeneSequence, SequenceKey} from './Genetics.js';
import {Card, CardHeader, Avatar, CardMedia, CardTitle} from 'material-ui';
import {Paper} from 'material-ui';
import Colors from 'material-ui/src/styles/colors';
import {RaisedButton} from 'material-ui';
import fb from 'flexboxgrid/dist/flexboxgrid.css';
export const UserList = React.createClass({
propTypes: {
user: React.PropTypes.object.required,
click: React.PropTypes.func.required,
order: React.PropTypes.number.required,
},
choose(e) {
e.preventDefault();
this.props.click(this.props.order);
},
render() {
const bgStyle = {
backgroundImage: `url(${this.props.user.avatar})`,
};
const initialAvatar = (
<Avatar
backgroundColor={(this.props.user.gender === 'female') ? Colors.red400 : Colors.blue400} >
{this.props.user.firstName[0]}{this.props.user.lastName[0]}
</Avatar>
);
return (
<section className={styles.user} onClick={this.choose}>
<Card>
<CardHeader
avatar={initialAvatar}
title={`${this.props.user.firstName} ${this.props.user.lastName}`} />
<CardMedia>
<div className={styles.imgCont}>
<div className={styles.imgBG} style={bgStyle}>
{
// <img src={this.props.avatar}/>
}
</div>
</div>
</CardMedia>
</Card>
</section>
);
},
});
export const UserDetail = React.createClass({
propTypes: {
user: React.PropTypes.object.required,
reference: React.PropTypes.array.required,
geneRegions: React.PropTypes.array.required,
clicked: React.PropTypes.func.required,
},
back(e) {
e.preventDefault();
this.props.clicked();
},
render() {
const fullName = `${this.props.user.firstName} ${this.props.user.lastName}`;
const avatarClasses = classnames([
fb[`col-xs-6`],
]);
return (
<div>
<RaisedButton label="Back to Users" secondary={true} onClick={this.back} />
<Paper>
<Card>
<div className={fb[`row`]}>
<div className={fb[`col-xs-6`]}>
<SequenceKey />
</div>
<div className={avatarClasses}>
<CardMedia
overlay={<CardTitle title={fullName} />} >
<img src={this.props.user.avatar}/>
</CardMedia>
</div>
</div>
</Card>
<div>
<GeneSequence
refSequence={this.props.reference}
userSequence={this.props.user.sequence}
geneRegions={this.props.geneRegions} />
</div>
</Paper>
</div>
);
},
});
|
node_modules/babel-preset-react-hmre/test/Test.js | ajames72/MovieDBReact | import React from 'react'
export default
class Test extends React.Component {
render() {
return (
<div>Winning?</div>
)
}
}
|
docs/examples/Checkbox/Example1.js | romagny13/react-form-validation | import React from 'react';
import { Checkbox } from 'romagny13-react-form-validation';
const Example1 = () => {
let values = ['a','c'];
return (
<div>
<h4>Direct check</h4>
<Checkbox checked name="g1" />
<h4>Grouped by name (all checked are checked)</h4>
<Checkbox checked name="g2" />
<Checkbox checked name="g2" />
<h4>Checked by value (if values contains control value)</h4>
<Checkbox name="g3" value="a" checked={values.indexOf("a") !== -1}/>
<Checkbox name="g3" value="b" checked={values.indexOf("b") !== -1}/>
<Checkbox name="g3" value="c" checked={values.indexOf("c") !== -1}/>
</div>
);
};
export default Example1;
|
server/sonar-web/src/main/js/apps/system/section.js | joansmith/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import ItemValue from './item-value';
export default React.createClass({
render() {
let items = this.props.items.map(item => {
return <tr key={item.name}>
<td className="thin">
<div style={{ width: '25vw', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.name}</div>
</td>
<td style={{ wordBreak: 'break-all' }}><ItemValue name={item.name} value={item.value}/></td>
</tr>;
});
return <div className="big-spacer-bottom">
<h3 className="spacer-bottom">{this.props.section}</h3>
<table className="data zebra" id={this.props.section}>
<tbody>{items}</tbody>
</table>
</div>;
}
});
|
src/container/navigator/header.js | PangPangPangPangPang/react-blog | /**
* Created by wangyefeng on 2017-03-31 11:26
*/
import React from 'react'
import { hashHistory } from 'react-router'
import './header.css'
import NormalButton from '../../compontent/normal_button'
import Logo from '../../resource/svg/diamond.svg'
class Header extends React.Component {
constructor(props) {
super(props)
this.state = {
backgroundColor: '',
iconColor: '',
}
}
componentDidMount() {
document.addEventListener('scroll', this.scrollEvent, false)
}
scrollEvent = () => {
if (document.body.scrollTop > 90) {
this.setState({
backgroundColor: 'header-animation',
iconColor: 'header-default-icon-animation',
})
} else if (document.body.scrollTop < 70) {
this.setState({
backgroundColor: 'header-animation-back',
iconColor: 'header-default-icon-animation-back',
})
}
}
clickHome = () => {
hashHistory.push('home')
}
clickArticle = () => {
hashHistory.push('list')
}
clickTags = () => {
hashHistory.push('tag')
}
clickAbout = () => {
hashHistory.push('about')
}
render() {
return (
<div className="header-base">
<div className={`header-default ${this.state.backgroundColor}`} >
<NormalButton title="Home Page" img={'home'} handleClick={this.clickHome} />
<NormalButton title="Article" img={'article'} handleClick={this.clickArticle} />
<NormalButton title="Contact Me" img={'tag'} handleClick={this.clickTags} />
<NormalButton title="About Me" img={'about'} handleClick={this.clickAbout} />
</div>
<Logo className={`header-default-icon ${this.state.iconColor}`} />
</div>
)
}
}
export default Header
|
blueocean-material-icons/src/js/components/svg-icons/image/hdr-strong.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageHdrStrong = (props) => (
<SvgIcon {...props}>
<path d="M17 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zM5 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
ImageHdrStrong.displayName = 'ImageHdrStrong';
ImageHdrStrong.muiName = 'SvgIcon';
export default ImageHdrStrong;
|
src/containers/Home.js | pjkarlik/Radial | import React from 'react';
import { withRouter } from 'react-router';
import { resolve } from '../styles';
import SiteStyles from '../styles/Site.less';
import RadialNav from '../components/RadialNav';
import RadialStyles from '../components/RadialNav.less';
class Home extends React.Component {
static displayName = 'Home';
static propTypes = {
classes: React.PropTypes.object,
router: React.PropTypes.shape({
push: React.PropTypes.func.isRequired,
}).isRequired,
items: React.PropTypes.array,
history: React.PropTypes.object,
};
static defaultProps = {
classes: SiteStyles,
items: [
{ name: 'dance', link: 'dance' },
{ name: 'ismtk', link: 'ismtk' },
{ name: 'home', link: '' },
],
};
constructor(props) {
super(props);
this.background = ~~(Math.random() * 4);
}
onClick = (path) => {
const { router } = this.props;
router.push(path);
}
render() {
const { items } = this.props;
return (
<div {...resolve(this.props, 'container', `home${this.background}`)}>
<div {...resolve(this.props, 'widget')}>
<RadialNav items = {items} mod = {this.background} classes = {RadialStyles} clickHandler = {this.onClick} />
</div>
</div>
);
}
}
export default withRouter(Home);
|
src/App.js | SpencerCornish/gong-web | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
example/src/screens/types/LightBox.js | inalist/react-native-navigation | import React from 'react';
import {StyleSheet, View, Text, Dimensions, Button} from 'react-native';
class Lightbox extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={{flex: 8}}>
<Text style={styles.title}>{this.props.title}</Text>
<Text style={styles.content}>{this.props.content}</Text>
</View>
<View style={{flex: 2}}>
<Button
title={'Close'}
onPress={() => this.props.onClose()}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
width: Dimensions.get('window').width * 0.7,
height: Dimensions.get('window').height * 0.3,
backgroundColor: '#ffffff',
borderRadius: 5,
padding: 16,
},
title: {
fontSize: 17,
fontWeight: '700',
},
content: {
marginTop: 8,
},
});
export default Lightbox;
|
app/components/Toggle/index.js | Dmitry-N-Medvedev/motor-collection | /**
*
* LocaleToggle
*
*/
import React from 'react';
import Select from './Select';
import ToggleOption from '../ToggleOption';
function Toggle(props) {
let content = (<option>--</option>);
// If we have items, render them
if (props.values) {
content = props.values.map((value) => (
<ToggleOption key={value} value={value} message={props.messages[value]} />
));
}
return (
<Select value={props.value} onChange={props.onToggle}>
{content}
</Select>
);
}
Toggle.propTypes = {
onToggle: React.PropTypes.func,
values: React.PropTypes.array,
value: React.PropTypes.string,
messages: React.PropTypes.object,
};
export default Toggle;
|
imports/api/interests/interests.js | howlround/worldtheatremap | // Meteor
import { TAPi18n } from 'meteor/tap:i18n';
// Utilities
import React from 'react';
import ReactSelect from 'react-select';
import { FormattedMessage } from 'react-intl';
import t from 'tcomb-form';
import Checkboxes from '../../ui/components/Checkboxes.jsx';
class InterestsCollection extends TAPi18n.Collection {
// insert(profile, callback) {
// }
// remove(selector, callback) {
// }
}
export const Interests = new InterestsCollection('Interests');
// Deny all client-side updates since we will be using methods to manage this collection
Interests.deny({
insert() { return true; },
update() { return true; },
remove() { return true; },
});
Interests.publicFields = {
value: 1,
label: 1,
};
export const interestsSelectFactory = (locale, multiValue = false) => {
// interestsSelectFactory options
const sortKey = (!locale || locale === 'en') ? 'label' : `i18n.${locale}.label`;
const sort = {};
sort[sortKey] = 1;
const allInterests = Interests.find({}, { sort }).fetch();
// interestsSelectFactory template
const allInterestsTags = t.form.Form.templates.select.clone({
renderSelect: (locals) => {
function onChange(options) {
if (multiValue === true) {
const values = (options || []).map(({ value }) => value);
locals.onChange(values);
} else {
if (options) {
locals.onChange(options.value);
} else {
locals.onChange(null);
}
}
}
const placeholder = (<FormattedMessage
id="forms.selectPlaceholder"
description="Select widget placeholder"
defaultMessage="Select..."
/>);
return (
<ReactSelect
multi
autoBlur
options={allInterests}
value={locals.value}
onChange={onChange}
className="interests-edit"
placeholder={placeholder}
/>
);
},
});
// interestsSelectFactory factory function
class ReactSelectInterestsFactory extends t.form.Component {
getTemplate() {
return allInterestsTags;
}
}
ReactSelectInterestsFactory.transformer = t.form.List.transformer;
return ReactSelectInterestsFactory;
};
export const interestsCheckboxFactory = (locale) => {
// interestsCheckboxFactory options
const sortKey = (!locale || locale === 'en') ? 'label' : `i18n.${locale}.label`;
const sort = {};
sort[sortKey] = 1;
const allInterests = Interests.find({}, { sort }).fetch();
// interestsCheckboxFactory template
const interestsCheckboxes = t.form.Form.templates.select.clone({
renderSelect: (locals) => (
<Checkboxes
options={allInterests}
values={locals.value}
name="interests"
onChange={locals.onChange}
/>
),
});
// interestsCheckboxFactory factory function
class CheckboxesInterestsFactory extends t.form.Component {
getTemplate() {
return interestsCheckboxes;
}
}
CheckboxesInterestsFactory.transformer = t.form.List.transformer;
return CheckboxesInterestsFactory;
};
|
demo-docs-website/src/theme/DocItemFooter/index.js | dimsemenov/PhotoSwipe | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import clsx from 'clsx';
import LastUpdated from '@theme/LastUpdated';
import EditThisPage from '@theme/EditThisPage';
import TagsListInline from '@theme/TagsListInline';
import styles from './styles.module.css';
import {ThemeClassNames} from '@docusaurus/theme-common';
function TagsRow(props) {
return (
<div
className={clsx(
ThemeClassNames.docs.docFooterTagsRow,
'row margin-bottom--sm',
)}>
<div className="col">
<TagsListInline {...props} />
</div>
</div>
);
}
function EditMetaRow({
editUrl,
lastUpdatedAt,
lastUpdatedBy,
formattedLastUpdatedAt,
}) {
return (
<div className={clsx(ThemeClassNames.docs.docFooterEditMetaRow, 'row')}>
<div className="col">
{editUrl && <EditThisPage editUrl={editUrl} />}
<br/>
Updates on <a href="https://twitter.com/photoswipe">Twitter</a>
<br/>
Code on <a href="https://github.com/dimsemenov/photoswipe">GitHub</a>
<br/>
Sponsor on <a href="https://opencollective.com/photoswipe">Open Collective</a>
</div>
<div className={clsx('col', styles.lastUpdated)}>
{(lastUpdatedAt || lastUpdatedBy) && (
<LastUpdated
lastUpdatedAt={lastUpdatedAt}
formattedLastUpdatedAt={formattedLastUpdatedAt}
lastUpdatedBy={lastUpdatedBy}
/>
)}
</div>
</div>
);
}
export default function DocItemFooter(props) {
const {content: DocContent} = props;
const {metadata} = DocContent;
const {editUrl, lastUpdatedAt, formattedLastUpdatedAt, lastUpdatedBy, tags} =
metadata;
const canDisplayTagsRow = tags.length > 0;
const canDisplayEditMetaRow = !!(editUrl || lastUpdatedAt || lastUpdatedBy);
const canDisplayFooter = canDisplayTagsRow || canDisplayEditMetaRow;
if (!canDisplayFooter) {
return null;
}
return (
<footer
className={clsx(ThemeClassNames.docs.docFooter, 'docusaurus-mt-lg')}>
{canDisplayTagsRow && <TagsRow tags={tags} />}
{canDisplayEditMetaRow && (
<EditMetaRow
editUrl={editUrl}
lastUpdatedAt={lastUpdatedAt}
lastUpdatedBy={lastUpdatedBy}
formattedLastUpdatedAt={formattedLastUpdatedAt}
/>
)}
</footer>
);
}
|
src/svg-icons/notification/airline-seat-legroom-extra.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatLegroomExtra = (props) => (
<SvgIcon {...props}>
<path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z"/>
</SvgIcon>
);
NotificationAirlineSeatLegroomExtra = pure(NotificationAirlineSeatLegroomExtra);
NotificationAirlineSeatLegroomExtra.displayName = 'NotificationAirlineSeatLegroomExtra';
NotificationAirlineSeatLegroomExtra.muiName = 'SvgIcon';
export default NotificationAirlineSeatLegroomExtra;
|
server/sonar-web/src/main/js/apps/web-api/components/Params.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// @flow
import React from 'react';
import InternalBadge from './InternalBadge';
import DeprecatedBadge from './DeprecatedBadge';
import type { Param } from '../../../api/web-api';
export default class Params extends React.PureComponent {
props: {
showDeprecated: boolean,
showInternal: boolean,
params: Array<Param>
};
render() {
const { showDeprecated, showInternal, params } = this.props;
const displayedParameters = params
.filter(p => showDeprecated || !p.deprecatedSince)
.filter(p => showInternal || !p.internal);
return (
<div className="web-api-params">
<table>
<tbody>
{displayedParameters.map(param => (
<tr key={param.key}>
<td className="markdown" style={{ width: 180 }}>
<code>{param.key}</code>
{param.internal &&
<div className="little-spacer-top">
<InternalBadge />
</div>}
{param.deprecatedSince &&
<div className="little-spacer-top">
<DeprecatedBadge since={param.deprecatedSince} />
</div>}
{showDeprecated &&
param.deprecatedKey &&
<div className="little-spacer-top">
<code>{param.deprecatedKey}</code>
</div>}
{showDeprecated &&
param.deprecatedKey &&
param.deprecatedKeySince &&
<div className="little-spacer-top">
<DeprecatedBadge since={param.deprecatedKeySince} />
</div>}
<div className="note little-spacer-top">
{param.required ? 'required' : 'optional'}
</div>
{param.since &&
<div className="note little-spacer-top">
since {param.since}
</div>}
</td>
<td>
<div
className="markdown"
dangerouslySetInnerHTML={{ __html: param.description }}
/>
</td>
<td style={{ width: 250 }}>
{param.possibleValues &&
<div>
<h4>Possible values</h4>
<ul className="list-styled">
{param.possibleValues.map(value => (
<li key={value} className="little-spacer-top">
<code>{value}</code>
</li>
))}
</ul>
</div>}
{param.defaultValue &&
<div className="little-spacer-top">
<h4>Default value</h4>
<code>{param.defaultValue}</code>
</div>}
{param.exampleValue &&
<div className="little-spacer-top">
<h4>Example value</h4>
<code>{param.exampleValue}</code>
</div>}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
|
entry_types/scrolled/package/src/frontend/inlineEditing/TextPlaceholder.js | codevise/pageflow | import React from 'react';
import styles from './TextPlaceholder.module.css';
export function TextPlaceholder({text, visible}) {
if (!text || !visible) {
return null;
}
return (
<div className={styles.placeholder}>
<div>{text}</div>
</div>
);
}
|
editor/components/ButtonGroups.js | VishalRohra/chroma-tone | import React from 'react'
import Toolbar from './Toolbar'
export default class ButtonGroups extends React.Component {
render() {
return (
<Toolbar className={this.props.className}>
{['left', 'middle', 'right'].map( position =>
<div key={position} className='toolbar-group'>
{ this.props.children[position] }
</div>
)}
</Toolbar>
);
}
}
|
src/server/frontend/Html.js | VigneshRavichandran02/3io | /* @flow */
/* eslint-disable react/no-danger */
import React from 'react';
const GoogleAnalytics = ({ id }) => (
<script
dangerouslySetInnerHTML={{ __html: `
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '${id}', 'auto'); ga('send', 'pageview');`,
}}
/>
);
GoogleAnalytics.propTypes = {
id: React.PropTypes.string.isRequired,
};
type Props = {
appCssFilename: string,
bodyHtml: string,
googleAnalyticsId: string,
helmet: Object,
isProduction: boolean,
};
const Html = ({
appCssFilename,
bodyHtml,
googleAnalyticsId,
helmet,
isProduction,
}: Props) => (
<html {...helmet.htmlAttributes.toComponent()}>
<head>
{helmet.title.toComponent()}
{helmet.base.toComponent()}
{helmet.meta.toComponent()}
{helmet.link.toComponent()}
{helmet.script.toComponent()}
{appCssFilename &&
<link href={appCssFilename} rel="stylesheet" />
}
{isProduction && googleAnalyticsId !== 'UA-XXXXXXX-X' &&
<GoogleAnalytics id={googleAnalyticsId} />
}
</head>
<body
dangerouslySetInnerHTML={{ __html: bodyHtml }}
/>
</html>
);
// TODO: Use babel-plugin-flow-react-proptypes one day.
Html.propTypes = {
appCssFilename: React.PropTypes.string,
bodyHtml: React.PropTypes.string.isRequired,
googleAnalyticsId: React.PropTypes.string.isRequired,
helmet: React.PropTypes.object.isRequired,
isProduction: React.PropTypes.bool.isRequired,
};
export default Html;
|
src/common/containers/Profile.js | strekmann/samklang | import React from 'react';
import { Grid, Row, Col } from 'react-bootstrap';
import { connect } from 'react-redux';
import Immutable from 'immutable';
class Profile extends React.Component {
render() {
const user = this.props.users.get(this.props.user.get('id'));
return (
<Grid>
<Row>
<Col xs={12}>
<h2>{user.get('name')}</h2>
<p>{user.get('email')}</p>
<p>{user.get('created')}</p>
</Col>
</Row>
</Grid>
);
}
}
Profile.propTypes = {
user: React.PropTypes.object,
users: React.PropTypes.instanceOf(Immutable.Map),
};
function select(state) {
return {
user: state.get('user'),
users: state.get('users'),
};
}
export default connect(select)(Profile);
|
src/routes/index.js | corydolphin/kanban-github | import React from 'react'
import { Route, IndexRoute, Redirect } from 'react-router'
// NOTE: here we're making use of the `resolve.root` configuration
// option in webpack, which allows us to specify import paths as if
// they were from the root of the ~/src directory. This makes it
// very easy to navigate to files regardless of how deeply nested
// your current file is.
import CoreLayout from 'layouts/CoreLayout/CoreLayout'
import HomeView from 'views/HomeView/HomeView'
import NotFoundView from 'views/NotFoundView/NotFoundView'
export default (
<Route path='/' component={CoreLayout}>
<IndexRoute component={HomeView} />
<Route path='/404' component={NotFoundView} />
<Redirect from='*' to='/404' />
</Route>
)
|
src/Parser/Core/Modules/Items/Legion/Legendaries/SephuzsSecret.js | enragednuke/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import { formatPercentage } from 'common/format';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
const PASSIVE_HASTE = 0.02;
const ACTIVE_HASTE = 0.25;
/*
* Sephuz's Secret -
* Equip: Gain 10% increased movement speed and 2% Haste. Successfully applying a loss of control effect to an enemy, interrupting an enemy, or dispelling any target increases this effect to 70% increased movement speed and 25% Haste for 10 sec. This increase may occur once every 30 sec.
*/
class SephuzsSecret extends Analyzer {
static dependencies = {
combatants: Combatants,
};
on_initialized() {
this.active = this.combatants.selected.hasFinger(ITEMS.SEPHUZS_SECRET.id);
}
item() {
const uptimePercent = this.combatants.selected.getBuffUptime(SPELLS.SEPHUZS_SECRET_BUFF.id) / this.owner.fightDuration;
const avgHaste = (uptimePercent * ACTIVE_HASTE) + ((1 - uptimePercent) * PASSIVE_HASTE);
return {
item: ITEMS.SEPHUZS_SECRET,
result: (
<span>
<dfn
data-tip={`This is the average haste percentage gained, factoring in both the passive and active bonuses. The active's uptime was <b>${formatPercentage(uptimePercent)}%</b>`}
>
{formatPercentage(avgHaste)} % average haste
</dfn>
</span>
),
};
}
}
export default SephuzsSecret;
|
Skins/VetoccitanT3/ReactSrc/node_modules/react-awesome-slider/src/core/bullets.js | MAN-IN-WAN/Kob-Eye | import React from 'react';
import PropTypes from 'prop-types';
import { getClassName } from '../helpers/components';
export default class Bullets extends React.Component {
static propTypes = {
cssModule: PropTypes.object,
rootElement: PropTypes.string.isRequired,
media: PropTypes.array,
onClick: PropTypes.func,
selected: PropTypes.number,
};
static defaultProps = {
cssModule: null,
selected: 0,
media: [],
onClick: () => {},
};
constructor(props) {
super(props);
this.rootElement = props.rootElement;
}
bulletClick = event => {
const button = event.currentTarget;
button.classList.add(
getClassName(
`${this.rootElement}__bullets--loading`,
this.props.cssModule
)
);
const index = parseInt(button.getAttribute('data-index'), 10);
const direction = !(this.props.selected > index);
this.props.onClick({ index, direction });
};
renderBullets() {
const { cssModule, selected, media = [] } = this.props;
return media.map((item, index) => {
const className =
index === selected
? getClassName(`${this.rootElement}__bullets--active`, cssModule)
: null;
return (
<button
key={`bullet-${index}`}
data-index={index}
onClick={this.bulletClick}
className={className}
>
{index}
</button>
);
});
}
render() {
const { cssModule, rootElement } = this.props;
return (
<nav className={getClassName(`${rootElement}__bullets`, cssModule)}>
{this.renderBullets()}
</nav>
);
}
}
|
src/components/Footer.js | elamperti/OpenWebScrobbler | import React from 'react';
import { Trans } from 'react-i18next';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTwitter, faFacebook, faGithub } from '@fortawesome/free-brands-svg-icons';
import './Footer.css';
function Footer() {
return (
<footer>
<div className="container mt-3 mb-2">
<div className="social text-center my-2">
<a title="Facebook" className="mx-2" href="https://facebook.com/OpenScrobbler">
<FontAwesomeIcon icon={faFacebook} size="2x" />
</a>
<a title="Twitter" className="mx-2" href="https://twitter.com/OpenScrobbler">
<FontAwesomeIcon icon={faTwitter} size="2x" />
</a>
<a title="GitHub" className="mx-2" href="https://github.com/elamperti/openwebscrobbler">
<FontAwesomeIcon icon={faGithub} size="2x" />
</a>
</div>
<p className="text-center">
<Trans i18nKey="footer.joinCommunity">
You are welcome to join our community <a href="https://discord.gg/vcbprTz">on Discord</a>!
</Trans>
<Trans i18nKey="footer.supportThisProject">
Please <a href="https://www.patreon.com/OpenScrobbler">support this project</a> on Patreon :)
</Trans>
<br />
<Trans i18nKey="footer.specialThanks">
{'Special thanks to all our supporters, translators and '}
<a href="https://github.com/elamperti/OpenWebScrobbler/graphs/contributors">contributors</a>
</Trans>
{' ❤ '}
<span className="app-version">v{process.env.REACT_APP_VERSION}</span>
</p>
</div>
</footer>
);
}
export default Footer;
|
src/with-feature-toggles.js | paralleldrive/react-feature-toggles | import React from 'react';
import { FeatureToggles } from './feature-toggles';
export const withFeatureToggles = ({ features } = {}) => Component => props => (
<FeatureToggles features={features}>
<Component {...props} />
</FeatureToggles>
);
|
src/propTypes/PointPropType.js | dingbat/react-native-mock | /**
* https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/PointPropType.js
*/
import React from 'react';
const { PropTypes } = React;
const PointPropType = PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number,
});
module.exports = PointPropType;
|
src/shared/components/HistoricTime/index.js | CharlesMangwa/Chloe | /* @flow */
import React from 'react'
import { Text, View } from 'react-native'
import { getPeriodColor, getPeriodName } from '@helpers/periods'
import Icon from '@components/Icon'
import styles from './styles'
type Props = {
value: 'preHistory' | 'antiquity' | 'middleAge' | 'modernTimes' | 'contemporaryTimes',
pages?: number,
}
const HistoricTime = (props: Props): React$Element<any> => {
const { value, pages } = props
return (
<View style={styles.container}>
<Icon
name={pages ? 'bookmarkIcon' : value}
defaultColor={getPeriodColor(value)}
size={16}
/>
{pages && <Text style={styles.text}><Text style={styles.textBold}>{pages}</Text> pages</Text>}
{!pages && <Text style={styles.text}>{getPeriodName(value)}</Text>}
</View>
)
}
export default HistoricTime
|
src/js/components/App.js | nathanbrennan/redux-todo | import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodolist from '../containers/VisibleTodoList'
const App = () => (
<div>
<AddTodo />
<VisibleTodolist />
<Footer />
</div>
)
export default App
|
packages/material-ui-icons/src/PermDataSetting.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PermDataSetting = props =>
<SvgIcon {...props}>
<path d="M18.99 11.5c.34 0 .67.03 1 .07L20 0 0 20h11.56c-.04-.33-.07-.66-.07-1 0-4.14 3.36-7.5 7.5-7.5zm3.71 7.99c.02-.16.04-.32.04-.49 0-.17-.01-.33-.04-.49l1.06-.83c.09-.08.12-.21.06-.32l-1-1.73c-.06-.11-.19-.15-.31-.11l-1.24.5c-.26-.2-.54-.37-.85-.49l-.19-1.32c-.01-.12-.12-.21-.24-.21h-2c-.12 0-.23.09-.25.21l-.19 1.32c-.3.13-.59.29-.85.49l-1.24-.5c-.11-.04-.24 0-.31.11l-1 1.73c-.06.11-.04.24.06.32l1.06.83c-.02.16-.03.32-.03.49 0 .17.01.33.03.49l-1.06.83c-.09.08-.12.21-.06.32l1 1.73c.06.11.19.15.31.11l1.24-.5c.26.2.54.37.85.49l.19 1.32c.02.12.12.21.25.21h2c.12 0 .23-.09.25-.21l.19-1.32c.3-.13.59-.29.84-.49l1.25.5c.11.04.24 0 .31-.11l1-1.73c.06-.11.03-.24-.06-.32l-1.07-.83zm-3.71 1.01c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" />
</SvgIcon>;
PermDataSetting = pure(PermDataSetting);
PermDataSetting.muiName = 'SvgIcon';
export default PermDataSetting;
|
src/server/createSSR.js | jcoreio/crater | import React from 'react'
import makeStore from '../universal/redux/makeStore'
import {match as _match} from 'react-router'
import Html from './Html'
import {push} from 'react-router-redux'
import {renderToStaticMarkup} from 'react-dom-stream/server'
import fs from 'fs'
import path from 'path'
import {join} from 'path'
import promisify from 'es6-promisify'
import {Map as iMap} from 'immutable'
import {Meteor} from 'meteor/meteor'
import url from 'url'
import type {IncomingMessage, ServerResponse} from 'http'
import type {Store} from '../universal/flowtypes/redux'
const __meteor_runtime_config__ = {
PUBLIC_SETTINGS: Meteor.settings.public || {},
ROOT_URL: process.env.ROOT_URL,
// Not everything is in place to support basename right now (e.g. react-router history config, webpack config)
// but might as well go ahead and use the correct value here anyway
ROOT_URL_PATH_PREFIX: url.parse(process.env.ROOT_URL).pathname.substring(1),
meteorEnv: {
NODE_ENV: process.env.NODE_ENV,
},
meteorRelease: Meteor.release,
}
function handleError(res: ServerResponse, error: Error) {
console.error(error.stack) // eslint-disable-line no-console
res.write(`
<div style="padding: 15px; position: fixed; top: 0; left: 0; right: 0; bottom: 0;">
<h3>An internal server error occurred:</h3>
<p>${error.message}</p>
</div>
`)
res.addTrailers({
'X-Streaming-Error': error.message,
})
res.end()
}
function renderApp(res: ServerResponse, store: Store, assets?: Object, renderProps?: Object) {
res.setHeader('Trailer', 'X-Streaming-Error')
const onError = handleError.bind(null, res)
const location = renderProps && renderProps.location && renderProps.location.pathname || '/'
// Needed so some components can render based on location
store.dispatch(push(location))
const htmlStream = renderToStaticMarkup(
<Html
title="Crater"
store={store}
assets={assets}
__meteor_runtime_config__={__meteor_runtime_config__}
renderProps={renderProps}
onError={onError}
/>
)
res.write('<!DOCTYPE html>')
htmlStream.pipe(res, {end: false})
htmlStream.on('end', (): void => res.end())
htmlStream.on('error', onError)
}
type MatchResult = {
redirectLocation: {pathname: string, search: string},
renderProps: ?Object,
}
function match({routes, location}: {routes: Object, location: string}): Promise<MatchResult> {
return new Promise((resolve: (result: MatchResult) => void, reject: (error: Error) => void) => {
_match({routes, location}, (error: ?Error, redirectLocation: {pathname: string, search: string}, renderProps: ?Object) => {
if (error) {
reject(error)
return
}
resolve({redirectLocation, renderProps})
})
})
}
const createSSR = Meteor.bindEnvironment(async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
try {
const store = makeStore(iMap())
if (process.env.NODE_ENV === 'production') {
const readFile = promisify(fs.readFile)
const assets = JSON.parse(await readFile(path.resolve(__dirname, 'assets.json'), 'utf8'))
assets.manifest.text = await readFile(join(__dirname, assets.manifest.js), 'utf-8')
if (process.env.DISABLE_FULL_SSR) {
return await renderApp(res, store, assets)
}
const makeRoutes = require('../universal/routes').default
const routes = makeRoutes(store)
const {redirectLocation, renderProps} = await match({
routes,
location: req.url
})
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
renderApp(res, store, assets, renderProps)
} else {
res.status(404).send('Not found')
}
} else {
// just send a cheap html doc + stringified store
renderApp(res, store)
}
} catch (error) {
handleError(res, error)
}
})
export default createSSR
|
app/components/Player/PlayerControls.js | Nurasael/WeWatch | import React from 'react'
import styles from './PlayerControls.css'
const PlayerControls = (props) => {
const {seekValue, handleSeekChange, prepareTestVideo, togglePause, duration, showTimer} = props
return (
<div className={styles.component}>
<input type="range" min="0" max={duration} value={seekValue} onChange={event => handleSeekChange(event.target.value)} step="0.1" />
<div className={styles.controls}>
<button className={styles.playerPlay} onClick={togglePause} type="button"><i className="fa fa-play" aria-hidden="true"></i></button>
<button className={styles.playerFordward} type="button"><i className="fa fa-forward" aria-hidden="true"></i></button>
<span className={styles.timer}>{showTimer()}</span>
<button className={styles.playerVolume} type="button"><i className="fa fa-volume-up" aria-hidden="true"></i></button>
<button type="button" onClick={prepareTestVideo}>PrepareTestVideo</button>
</div>
</div>
)
}
export default PlayerControls
|
client/vehicle-finder-spa/src/containers/messages/all-message-threads.js | Del7a/vehicle-finder | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { requestAllMessageThreads, changeCurrentMessageThread } from '../../actions/messages/';
import { getUserProfile } from '../../actions/user/';
import MessageThreadListComponent from '../../components/messages/list-item-view';
class AllMessageThreads extends Component {
constructor(props) {
super(props)
this.onMessageThreadClick = this.onMessageThreadClick.bind(this)
}
componentDidMount() {
if (!this.props.messages.messageThreads.length) {
this.props.requestAllMessageThreads()
}
if (!this.props.user.currentUserId) {
this.props.getUserProfile()
}
}
onMessageThreadClick(messageThread) {
if (!messageThread.messages) {
messageThread.messages = [];
messageThread.loadingMessages = true;
}
this.props.changeCurrentMessageThread(messageThread)
}
render() {
return (
<div className="modal-body row">
<MessageThreadListComponent
messageThreads={this.props.messages.messageThreads}
onMessageThreadClick={this.onMessageThreadClick}
currentUserId={this.props.user.userId}
/>
</div>
)
}
}
function mapStateToProps({messages, user}) {
return {messages, user};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({requestAllMessageThreads, changeCurrentMessageThread,
getUserProfile}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(AllMessageThreads) |
modules/dreamview/frontend/src/components/common/PortalModal.js | ApolloAuto/apollo | import 'styles/Modal.scss';
import React from 'react';
import ReactDOM from 'react-dom';
class Modal extends React.Component {
constructor(props) {
super(props);
this.setOkButtonRef = (element) => {
this.okButton = element;
};
}
componentDidMount() {
// .focus() has browser restrictions in some cases, where
// the element is not visible when trying to focus().
// The workaround is setting a setTimeout as below.
setTimeout(() => {
if (this.okButton) {
this.okButton.focus();
}
}, 0);
}
componentDidUpdate() {
if (this.okButton) {
this.okButton.focus();
}
}
render() {
const { open, header } = this.props;
if (!open) {
return null;
}
return (
<div>
<div className="modal-background" />
<div className="modal-content">
<div role="dialog" className="modal-dialog">
{header && (
<header>
<span>{this.props.header}</span>
</header>
)}
{this.props.children}
</div>
<button
ref={this.setOkButtonRef}
className="ok-button"
onClick={() => this.props.onClose()}
>
OK
</button>
</div>
</div>
);
}
}
export default class PortalModal extends React.Component {
constructor(props) {
super(props);
this.rootSelector = document.getElementById('root');
this.container = document.createElement('div');
}
componentDidMount() {
this.rootSelector.appendChild(this.container);
}
componentWillUnmount() {
this.rootSelector.removeChild(this.container);
}
render() {
return ReactDOM.createPortal(<Modal {...this.props} />, this.container);
}
}
|
src/components/Header.js | jamescchu/jameschu-v5 | import React from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
import { rhythm } from '../utils/typography'
import { media } from '../utils/media'
const Header = styled.header`
width: ${rhythm(2)};
margin: ${rhythm(1 / 2)} ${rhythm(1)};
position: initial;
${media.desktop`
position: fixed;
`};
`
const LogoLink = styled(Link)`
display: block;
`
const Logo = () =>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M5.2 18.7c.2-.3.4-.6.6-.8.9-1.2 1.7-2.5 2.4-3.9.2-.6.5-1.1.8-1.6.4-.9.9-1.9 1.2-2.8.4-1.1.8-2.1 1.2-3.2.4-1 .8-2 1.1-3 .2-.7.4-1.5.5-2.3 0-.2 0-.4.1-.6-.7-.2-1.3-.3-2-.4-.2.2-.4.5-.6.7-.6.4-.8.8-1.1 1.3-.4.7-.9 1.4-1.3 2.1-.2.4-.4.8-.6 1.3-.3.8-.8 1.6-1.1 2.5-.3.9-.7 1.8-.9 2.7-.3 1-.5 1.7-.7 2.6-.1.4-.1.8-.1.9 0 .4.1.4 0 .6 0 .2-.4-.1-.4-.5 0-.8 0-1.5.2-2.3.2-.9.5-1.6.7-2.5.2-.9.6-1.7 1-2.6.3-.5.5-1.1.8-1.6.2-.4.3-.8.5-1.2.4-.8.9-1.5 1.4-2.3.3-.6.7-1.2 1.2-1.8H10C4.5 0 0 4.5 0 10c0 3.7 2.1 7 5.2 8.7z" />
<path d="M13.5.6c-.1.8-.3 1.6-.5 2.4-.2.9-.6 1.8-.9 2.7-.3.9-.6 1.8-.9 2.6-.2.6-.5 1.2-.7 1.8-.6 1.3-1.1 2.5-1.7 3.8v.1c.4-.4.7-.9 1.1-1.3l.9-.9c.3-.3.7-.7 1.1-.9.2-.1.6-.2.8-.1.2.1.3.4.3.6 0 .6 0 1.2-.1 1.8 0 .3.1.3.4.2.5-.2.9-.6 1.3-1 .2-.2.4-.4.6-.5.3-.2.7-.2 1-.1.3.2.6.3 1 .5v.2h-.1c-.4 0-.8 0-1.2-.2-.2-.1-.2 0-.4.1-.4.3-.7.7-1.1 1-.4.3-.8.6-1.4.6-.4 0-.6-.2-.6-.6v-2.2c-.2.1-.5.2-.7.4-.8.8-1.6 1.7-2.3 2.6-.5.7-1.1 1.3-1.6 2-.4.6-.7 1.2-1 1.8-.2.4-.4.7-.6 1.1 1.1.6 2.4.9 3.8.9 5.5 0 10-4.5 10-10 0-4.3-2.7-8-6.5-9.4z" />
</svg>
const SiteHeader = () =>
<Header>
<LogoLink to="/">
<Logo />
</LogoLink>
</Header>
export default SiteHeader
|
packages/react-scripts/template/src/App.js | dpoineau/create-react-app | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
src/client/js/Layout.js | JMJustas/todolist | /**
* Layout for the whole page
*/
import React from 'react';
import EntryService from './services/EntryService';
import Header from './Header';
import TodosApp from './components/TodosApp';
export default class Layout extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="full-height">
<Header heading="A simple TODO app"/>
<div className="container full-height">
<div className="row">
<TodosApp entryService={new EntryService()}/>
</div>
</div>
</div>
);
}
}
|
src/components/CategoryCard/CategoryCard.js | hologram-io/docs | import React from 'react'
import {Link} from '../'
class CategoryCard extends React.Component {
constructor(props) {
super(props);
}
render() {
const {
header = "",
title = "",
image = "",
blurb = "",
cta = "",
ctaLink = ""
} = this.props;
return (
<div className="row">
<h2 className="col-md-3">
{header}
</h2>
<div className="col-md-9">
<div className="row card-category">
<div className="col-xs">
<img className="cat-image" src={image} />
</div>
<div className="col-xs">
<h1>{title}</h1>
<p>{blurb}</p>
<div className="cta">
<Link href={ctaLink}>{cta}</Link>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CategoryCard;
|
client/modules/Post/__tests__/components/PostList.spec.js | BingeTrackr/BingeTrackr | import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import PostList from '../../components/PostList';
const posts = [
{ name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" },
{ name: 'Mayank', title: 'Hi Mern', slug: 'hi-mern', cuid: 'f34gb2bh24b24b3', content: "All dogs bark 'mern!'" },
];
test('renders the list', t => {
const wrapper = shallow(
<PostList posts={posts} handleShowPost={() => {}} handleDeletePost={() => {}} />
);
t.is(wrapper.find('PostListItem').length, 2);
});
|
src/component/Dashboard.js | hustlrb/yjbAdmin | /**
* Created by yangyang on 2017/9/11.
*/
import React from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'
import { Button } from 'antd'
import {configAction, configSelector} from '../util/config'
class Dashboard extends React.Component {
constructor(props) {
super(props)
}
fetchDomain = () => {
this.props.requestDomain({times: 2})
}
render() {
return (
<div>
Dashboard
<div style={{marginTop: 10}}>
<Button type="primary" onClick={this.fetchDomain}>获取域名</Button>
</div>
<div style={{marginTop: 10}}>
{this.props.domain}
</div>
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
let domain = configSelector.selectDomain(state)
return {
domain,
}
}
const mapDispatchToProps = {
...configAction,
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Dashboard))
|
packages/react/src/components/atoms/buttons/Button/index.js | massgov/mayflower | /**
* Button module.
* @module @massds/mayflower-react/Button
*/
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
const Button = (button) => {
const buttonClasses = classNames({
ma__button: true,
[`ma__button--${button.usage}`]: button.usage,
[`ma__button--${button.size}`]: button.size,
[`ma__button--${button.theme}`]: button.theme,
'ma__button--disabled': button.disabled,
[button.classes.join(' ')]: button.classes
});
const Element = button.href ? 'a' : 'button';
const onClickCallback = (e) => {
if (typeof button.onClick === 'function') {
e.preventDefault();
button.onClick(e);
}
};
return(
<Element
className={buttonClasses}
type={button.type}
href={button.href}
title={button.info}
aria-label={button.label}
onClick={(e) => onClickCallback(e)}
disabled={button.disabled}
>
{button.children ? button.children : button.text}
</Element>
);
};
Button.propTypes = {
/** Custom click handler function. */
onClick: PropTypes.func,
/** When populated with a url, this component renders an `<a>` vs a `<button>` */
href: PropTypes.string,
/** The text which renders in the standard browser tooltip on hover */
info: PropTypes.string,
/** Aria-label of the button */
label: PropTypes.string,
/** Button or link text */
text: PropTypes.string,
/** HTML button 'type' attribute */
type: PropTypes.oneOf(['submit', 'reset', 'button', '']),
/** Create a smaller button */
size: PropTypes.oneOf(['', 'small', 'large']),
/** Themes correspond to site color scheme i.e. sass variables */
theme: PropTypes.oneOf(['', 'c-primary-alt', 'c-highlight', 'c-gray-dark']),
/** Button usage */
usage: PropTypes.oneOf(['', 'secondary', 'tertiary', 'quaternary']),
/** Set `<button>` to disabled */
disabled: PropTypes.bool,
/** Custom classnames appending to the button */
classes: PropTypes.arrayOf(PropTypes.string)
};
// Only set defaults for the configuration variables which need to be opted in to activate.
Button.defaultProps = {
href: '',
type: '',
size: '',
theme: '',
usage: '',
disabled: false,
classes: ['']
};
export default Button;
|
src/svg-icons/notification/no-encryption.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationNoEncryption = (props) => (
<SvgIcon {...props}>
<path d="M21 21.78L4.22 5 3 6.22l2.04 2.04C4.42 8.6 4 9.25 4 10v10c0 1.1.9 2 2 2h12c.23 0 .45-.05.66-.12L19.78 23 21 21.78zM8.9 6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2H9.66L20 18.34V10c0-1.1-.9-2-2-2h-1V6c0-2.76-2.24-5-5-5-2.56 0-4.64 1.93-4.94 4.4L8.9 7.24V6z"/>
</SvgIcon>
);
NotificationNoEncryption = pure(NotificationNoEncryption);
NotificationNoEncryption.displayName = 'NotificationNoEncryption';
NotificationNoEncryption.muiName = 'SvgIcon';
export default NotificationNoEncryption;
|
client/util/react-intl-test-helper.js | eantler/simmeme-client | /**
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import { mount, shallow } from 'enzyme';
// You can pass your messages to the IntlProvider. Optional: remove if unneeded.
const messages = require('../../Intl/localizationData/en');
// Create the IntlProvider to retrieve context for wrapping around.
const intlProvider = new IntlProvider({ locale: 'en', messages }, {});
export const { intl } = intlProvider.getChildContext();
/**
* When using React-Intl `injectIntl` on components, props.intl is required.
*/
const nodeWithIntlProp = node => {
return React.cloneElement(node, { intl });
};
export const shallowWithIntl = node => {
return shallow(nodeWithIntlProp(node), { context: { intl } });
};
export const mountWithIntl = node => {
return mount(nodeWithIntlProp(node), {
context: { intl },
childContextTypes: { intl: intlShape },
});
};
|
src/layouts/CoreLayout/CoreLayout.js | TriPSs/react-esc-example | import React from 'react'
import { Route, Switch } from 'react-router'
import 'styles/core.scss'
import Header from 'components/Header'
import Home from 'routes/Home'
import Counter from 'routes/Counter'
import Async from 'routes/Async'
import classes from './CoreLayout.scss'
export const CoreLayout = () => (
<div className="container text-center">
<Header />
<div className={classes.mainContainer}>
<Switch>
<Route {...Home} />
<Route {...Counter} />
<Route {...Async} />
</Switch>
</div>
</div>
)
export default CoreLayout
|
renderer/components/Channels/ChannelsViewButtons.js | LN-Zap/zap-desktop | import React from 'react'
import PropTypes from 'prop-types'
import { useIntl } from 'react-intl'
import { SwitchButton } from 'components/UI'
import LayoutCards from 'components/Icon/LayoutCards'
import LayoutList from 'components/Icon/LayoutList'
import { CHANNEL_LIST_VIEW_MODE_SUMMARY, CHANNEL_LIST_VIEW_MODE_CARD } from './constants'
import messages from './messages'
const ChannelsViewButtons = ({ channelViewMode, setChannelViewMode, ...rest }) => {
const intl = useIntl()
const isCardView = channelViewMode === CHANNEL_LIST_VIEW_MODE_CARD
return (
<SwitchButton
{...rest}
data-hint={intl.formatMessage({
...(isCardView ? messages.view_mode_list : messages.view_mode_card),
})}
Icon1={LayoutList}
Icon2={LayoutCards}
isSwitched={isCardView}
onClick={() =>
setChannelViewMode(
isCardView ? CHANNEL_LIST_VIEW_MODE_SUMMARY : CHANNEL_LIST_VIEW_MODE_CARD
)
}
/>
)
}
ChannelsViewButtons.propTypes = {
channelViewMode: PropTypes.string.isRequired,
setChannelViewMode: PropTypes.func.isRequired,
}
export default ChannelsViewButtons
|
docs/app/Examples/elements/Image/States/index.js | ben174/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ImageStatesExamples = () => (
<ExampleSection title='States'>
<ComponentExample
title='Hidden'
description='An image can be hidden.'
examplePath='elements/Image/States/ImageExampleHidden'
/>
<ComponentExample
title='Disabled'
description='An image can show that it is disabled and cannot be selected.'
examplePath='elements/Image/States/ImageExampleDisabled'
/>
</ExampleSection>
)
export default ImageStatesExamples
|
browser/components/relationships/relationships-single-bubble.component.js | smanwaring/relationship-visualizer | import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import Popover, { PopoverAnimationVertical } from 'material-ui/Popover';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import AddActivityForm from '../forms/add-activity/add-activity.component';
import EditRelationship from '../forms/edit-relationship/edit-relationship.component';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
class SingleRelationship extends Component {
constructor(props){
super(props);
this.state = {
modalOpen: false,
open: false,
modalContent: ""
};
this.handleTouchTap = this.handleTouchTap.bind(this);
this.handleRequestClose = this.handleRequestClose.bind(this);
this.handleAddActivityOpen = this.handleAddActivityOpen.bind(this);
this.handleAddActivityClose = this.handleAddActivityClose.bind(this);
this.handleEditActivityOpen = this.handleEditActivityOpen.bind(this);
}
handleAddActivityOpen() {
this.setState({open: false});
this.setState({ modalOpen: true, modalContent: "add" });
}
handleEditActivityOpen() {
this.setState({open: false});
this.setState({ modalOpen: true, modalContent: "edit" });
}
handleAddActivityClose() {
this.setState({ modalOpen: false });
}
handleTouchTap(event){
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
}
handleRequestClose() {
this.setState({ open: false });
}
renderModalContent() {
if(this.state.modalContent === "add") {
return (
<AddActivityForm
handleAddActivityClose={this.handleAddActivityClose}
relationshipId={this.props.relationship.id} autoFocus="true" />
)
} else if(this.state.modalContent === "edit") {
return (
<EditRelationship
autoFocus="true"
handleClose={this.handleAddActivityClose}
relationship={this.props.relationship}
/>
)
}
}
render(){
const { loggedInUser, relationship, relationshipStyle, name, addActivityStatus } = this.props;
const addActivityActions = [
<FlatButton
label="Cancel"
primary={true}
keyboardFocused={true}
onTouchTap={this.handleAddActivityClose}
/>
]
return (
<div className="bubble-container">
<div className="bubble-container-center vam" onTouchTap={this.handleTouchTap}>
<p>{name}</p>
<div className="flex-bubble" onTouchTap={this.handleTouchTap} style={relationshipStyle} />
</div>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'middle', vertical: 'center'}}
targetOrigin={{horizontal: 'middle', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
animation={PopoverAnimationVertical}
>
<Menu>
<MenuItem primaryText="Add Activity" onClick={this.handleAddActivityOpen} />
<Link to={`/relationships/user/${loggedInUser.id}/rel/${relationship.id}`}><MenuItem primaryText="View Activity History" /></Link>
<MenuItem primaryText="Edit Relationship" onClick={this.handleEditActivityOpen} />
</Menu>
</Popover>
<Dialog
title={`Add an activity for ${relationship.name}`}
actions={addActivityActions}
modal={false}
open={this.state.modalOpen}
onRequestClose={this.handleAddActivityClose}
>
{this.renderModalContent()}
</Dialog>
</div>
);
}
}
/* ----------------- CONTAINER ------------------ */
const mapStateToProps = (state) => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SingleRelationship);
|
fixtures/attribute-behavior/src/index.js | nhunzaker/react | import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
|
client/src/pages/Routes/Routes.js | patferguson/solitaire-react | import React, { Component } from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import App from '../App'
import NotFound from '../NotFound'
import Home from '../Home'
import About from '../About'
import Testing from '../Testing'
class Routes extends Component {
render() {
return (
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="about" component={About}/>
<Route path="testing" component={Testing}/>
<Route path="*" component={NotFound}/>
</Route>
</Router>
);
}
}
export default Routes;
|
app/jsx/external_apps/components/AppDetails.js | venturehive/canvas-lms | /*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import I18n from 'i18n!external_tools'
import React from 'react'
import PropTypes from 'prop-types'
import page from 'page'
import Header from 'jsx/external_apps/components/Header'
import AddApp from 'jsx/external_apps/components/AddApp'
import 'compiled/jquery.rails_flash_notifications'
export default React.createClass({
displayName: 'AppDetails',
propTypes: {
store: PropTypes.object.isRequired,
baseUrl: PropTypes.string.isRequired,
shortName: PropTypes.string.isRequired
},
getInitialState() {
return {
app: null
}
},
componentDidMount() {
var app = this.props.store.findAppByShortName(this.props.shortName);
if (app) {
this.setState({ app: app });
} else {
page('/');
}
},
handleToolInstalled() {
var app = this.state.app;
app.is_installed = true;
this.setState({ app: app });
this.props.store.flagAppAsInstalled(app.short_name);
this.props.store.setState({filter: 'installed', filterText: ''});
$.flashMessage(I18n.t('The app was added successfully'));
page('/');
},
alreadyInstalled() {
if (this.state.app.is_installed) {
return <div className="gray-box-centered">{I18n.t('Installed')}</div>;
}
},
render() {
if (!this.state.app) {
return <img src="/images/ajax-loader-linear.gif" />;
}
return (
<div className="AppDetails">
<Header>
<a href={`${this.props.baseUrl}/configurations`} className="btn view_tools_link lm pull-right">{I18n.t('View App Configurations')}</a>
<a href={this.props.baseUrl} className="btn view_tools_link lm pull-right">{I18n.t('View App Center')}</a>
</Header>
<div className="app_full">
<table className="individual-app">
<tbody>
<tr>
<td className="individual-app-left" valign="top">
<div className="app">
<img className="img-polaroid" src={this.state.app.banner_image_url} />
{this.alreadyInstalled()}
</div>
<AddApp ref="addAppButton" app={this.state.app} handleToolInstalled={this.handleToolInstalled} />
<a href={this.props.baseUrl} className="app_cancel">« {I18n.t('Back to App Center')}</a>
</td>
<td className="individual-app-right" valign="top">
<h2 ref="appName">{this.state.app.name}</h2>
<p ref="appDescription" dangerouslySetInnerHTML={{__html: this.state.app.description}} />
</td>
</tr>
</tbody>
</table>
</div>
</div>
)
}
});
|
js/Search.js | aramay/complete-intro-to-react-v2 | import React from 'react'
import ShowCard from './ShowCard'
import Header from './Header'
import { connect } from 'react-redux'
const { arrayOf, shape, string } = React.PropTypes
// import preload from '../public/data.json'
const Search = React.createClass({
propTypes: {
shows: arrayOf(shape({
title: string,
description: string
})),
searchTerm: string
},
// getInitialState () {
// return {
// searchTerm: ''
// }
// },
// handleSearchTermChange (event) {
// this.setState({
// searchTerm: event.target.value
// })
// },
render () {
return (
<div className='search'>
<Header showSearch />
<div>
{this.props.shows
.filter( (show) => {
return `${show.title} ${show.description}`.toUpperCase().indexOf(this.props.searchTerm.toUpperCase()) >= 0
})
.map((show) => {
return (
// <ShowCard key={show.imdbID} show={show} />
<ShowCard key={show.imdbID} {...show} />
)
})}
</div>
</div>
)
}
})
const mapStateToProps = (state) => {
return {
searchTerm: state.searchTerm
}
}
export default connect(mapStateToProps)(Search)
|
app/index.js | fullPistol/React-demo | import React from 'react';
import {render} from 'react-dom';
import App from './js/containers/App';
import './css/reset.css'
import './css/index.less';
render(
<App />,
document.getElementById('root')
); |
src/svg-icons/image/photo-size-select-small.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoSizeSelectSmall = (props) => (
<SvgIcon {...props}>
<path d="M23 15h-2v2h2v-2zm0-4h-2v2h2v-2zm0 8h-2v2c1 0 2-1 2-2zM15 3h-2v2h2V3zm8 4h-2v2h2V7zm-2-4v2h2c0-1-1-2-2-2zM3 21h8v-6H1v4c0 1.1.9 2 2 2zM3 7H1v2h2V7zm12 12h-2v2h2v-2zm4-16h-2v2h2V3zm0 16h-2v2h2v-2zM3 3C2 3 1 4 1 5h2V3zm0 8H1v2h2v-2zm8-8H9v2h2V3zM7 3H5v2h2V3z"/>
</SvgIcon>
);
ImagePhotoSizeSelectSmall = pure(ImagePhotoSizeSelectSmall);
ImagePhotoSizeSelectSmall.displayName = 'ImagePhotoSizeSelectSmall';
ImagePhotoSizeSelectSmall.muiName = 'SvgIcon';
export default ImagePhotoSizeSelectSmall;
|
packages/ui-toolkit/src/styleguide/tabs.js | geek/joyent-portal | import React from 'react';
import PropTypes from 'prop-types';
import Styled from 'react-styleguidist/lib/rsg-components/Styled';
import cx from 'classnames';
export const styles = ({
space,
color,
fontFamily,
fontSize,
buttonTextTransform
}) => ({
button: {
padding: [[space[1], 0]],
fontFamily: fontFamily.base,
fontSize: fontSize.base,
color: color.light,
background: 'transparent',
textTransform: buttonTextTransform,
transition: 'color 750ms ease-out',
border: 'none',
cursor: 'pointer',
'&:hover, &:focus': {
isolate: false,
outline: 0,
color: color.linkHover,
transition: 'color 150ms ease-in'
},
'&:focus:not($isActive)': {
isolate: false,
outline: [[1, 'dotted', color.linkHover]]
},
'& + &': {
isolate: false,
marginLeft: space[1]
}
},
isActive: {
borderBottom: [[2, color.linkHover, 'solid']]
}
});
export function TabButtonRenderer({
classes,
name,
className,
onClick,
active,
children
}) {
const classNames = cx(classes.button, className, {
[classes.isActive]: active
});
return (
<button type="button" name={name} className={classNames} onClick={onClick}>
{children}
</button>
);
}
TabButtonRenderer.propTypes = {
classes: PropTypes.object.isRequired,
name: PropTypes.string,
className: PropTypes.string,
onClick: PropTypes.func,
active: PropTypes.bool,
children: PropTypes.node
};
export default Styled(styles)(TabButtonRenderer);
|
test/test_helper.js | quebez/react_todolist | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/components/error-screen.js | gitpoint/git-point | import React, { Component } from 'react';
import { colors, fonts, normalize } from 'config';
import { t } from 'utils';
import styled from 'styled-components';
const ViewWrapper = styled.View`
align-items: center;
align-content: center;
height: 100%;
justify-content: center;
`;
const TextStyled = styled.Text`
color: ${colors.white};
${fonts.fontPrimaryBold};
font-size: ${normalize(20)};
text-align: center;
width: 80%;
`;
type Props = {
locale: string,
};
export class ErrorScreen extends Component {
props: Props;
render() {
return (
<ViewWrapper>
<TextStyled>
{t(
'Oops! it seems that you are not connected to the internet!',
this.props.locale
)}
</TextStyled>
</ViewWrapper>
);
}
}
|
src/component/Template.js | NHAAHNA/hms | import React, { Component } from 'react';
import '../containers/App.css';
export default class Template extends Component{
render(){
return(
<div className="container">
<div className="row">
<div className="col-md-12 twelveDiv">
<h2>12 </h2>
</div>
</div>
<div className="row"><hr/></div>
<div className="row">
<div className="col-md-8 eightDiv">
<h2>8</h2>
</div>
<div className="col-md-4 fourDiv">
<h2>4</h2>
</div>
</div>
</div>
)
}
} |
src/components/Bottom/Bottom.js | Zoomdata/nhtsa-dashboard-2.2 | import styles from './Bottom.css';
import React from 'react';
import image from '../../images/slot-bottom.png'
const Bottom = () => {
return (
<img
className={styles.root}
width="120" height="3.5"
src={image}
/>
)
};
export default Bottom; |
src/index.js | yfruan/react-simple | import React from 'react';
import ReactDom from 'react-dom';
import App from 'app';
ReactDom.render(
<App />,
document.getElementById('content')
);
|
examples/redirect-using-index/app.js | okcoker/react-router | import React from 'react';
import { Router, Route, IndexRoute, Link } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
{this.props.children}
</div>
);
}
});
var Index = React.createClass({
render () {
return (
<div>
<h1>You should not see this.</h1>
{this.props.children}
</div>
)
}
});
var Child = React.createClass({
render () {
return (
<div>
<h2>Redirected to "/child"</h2>
<Link to="/">Try going to "/"</Link>
</div>
)
}
});
function redirectToChild(location, replaceWith) {
replaceWith(null, '/child');
}
React.render((
<Router>
<Route path="/" component={App}>
<IndexRoute component={Index} onEnter={redirectToChild}/>
<Route path="/child" component={Child}/>
</Route>
</Router>
), document.getElementById('example'));
|
src/svg-icons/action/perm-phone-msg.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermPhoneMsg = (props) => (
<SvgIcon {...props}>
<path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z"/>
</SvgIcon>
);
ActionPermPhoneMsg = pure(ActionPermPhoneMsg);
ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg';
ActionPermPhoneMsg.muiName = 'SvgIcon';
export default ActionPermPhoneMsg;
|
client/src/javascript/components/icons/Ratio.js | jfurrow/flood | import React from 'react';
import BaseIcon from './BaseIcon';
export default class Ratio extends BaseIcon {
render() {
return (
<svg className={`icon icon--ratio ${this.props.className}`} viewBox={this.getViewBox()}>
<path d="M54.57,15.76a28.56,28.56,0,1,0-10.45,39A28.56,28.56,0,0,0,54.57,15.76ZM9.68,41.86a23.36,23.36,0,1,1,40.39-23.5C40.72,29.74,24.32,39.36,9.68,41.86Z" />
</svg>
);
}
}
|
src/svg-icons/editor/format-paint.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatPaint = (props) => (
<SvgIcon {...props}>
<path d="M18 4V3c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6h1v4H9v11c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-9h8V4h-3z"/>
</SvgIcon>
);
EditorFormatPaint = pure(EditorFormatPaint);
EditorFormatPaint.displayName = 'EditorFormatPaint';
export default EditorFormatPaint;
|
public/jspm_packages/npm/[email protected]/modules/Redirect.js | nayashooter/ES6_React-Bootstrap | /* */
"format cjs";
import React from 'react'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { formatPattern } from './PatternUtils'
import { falsy } from './PropTypes'
const { string, object } = React.PropTypes
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
const Redirect = React.createClass({
statics: {
createRouteFromReactElement(element) {
const route = createRouteFromReactElement(element)
if (route.from)
route.path = route.from
route.onEnter = function (nextState, replace) {
const { location, params } = nextState
let pathname
if (route.to.charAt(0) === '/') {
pathname = formatPattern(route.to, params)
} else if (!route.to) {
pathname = location.pathname
} else {
let routeIndex = nextState.routes.indexOf(route)
let parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1)
let pattern = parentPattern.replace(/\/*$/, '/') + route.to
pathname = formatPattern(pattern, params)
}
replace({
pathname,
query: route.query || location.query,
state: route.state || location.state
})
}
return route
},
getRoutePattern(routes, routeIndex) {
let parentPattern = ''
for (let i = routeIndex; i >= 0; i--) {
const route = routes[i]
const pattern = route.path || ''
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern
if (pattern.indexOf('/') === 0)
break
}
return '/' + parentPattern
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render() {
invariant(
false,
'<Redirect> elements are for router configuration only and should not be rendered'
)
}
})
export default Redirect
|
src/svg-icons/file/cloud-off.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileCloudOff = (props) => (
<SvgIcon {...props}>
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4c-1.48 0-2.85.43-4.01 1.17l1.46 1.46C10.21 6.23 11.08 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3 0 1.13-.64 2.11-1.56 2.62l1.45 1.45C23.16 18.16 24 16.68 24 15c0-2.64-2.05-4.78-4.65-4.96zM3 5.27l2.75 2.74C2.56 8.15 0 10.77 0 14c0 3.31 2.69 6 6 6h11.73l2 2L21 20.73 4.27 4 3 5.27zM7.73 10l8 8H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h1.73z"/>
</SvgIcon>
);
FileCloudOff = pure(FileCloudOff);
FileCloudOff.displayName = 'FileCloudOff';
FileCloudOff.muiName = 'SvgIcon';
export default FileCloudOff;
|
packages/react-dom/src/server/ReactPartialRenderer.js | anushreesubramani/react | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {ReactElement} from 'shared/ReactElementType';
import React from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import emptyObject from 'fbjs/lib/emptyObject';
import hyphenateStyleName from 'fbjs/lib/hyphenateStyleName';
import invariant from 'fbjs/lib/invariant';
import memoizeStringOnly from 'fbjs/lib/memoizeStringOnly';
import warning from 'fbjs/lib/warning';
import checkPropTypes from 'prop-types/checkPropTypes';
import describeComponentFrame from 'shared/describeComponentFrame';
import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState';
import {
REACT_FRAGMENT_TYPE,
REACT_CALL_TYPE,
REACT_RETURN_TYPE,
REACT_PORTAL_TYPE,
} from 'shared/ReactSymbols';
import {
createMarkupForCustomAttribute,
createMarkupForProperty,
createMarkupForRoot,
} from './DOMMarkupOperations';
import escapeTextForBrowser from './escapeTextForBrowser';
import {
Namespaces,
getIntrinsicNamespace,
getChildNamespace,
} from '../shared/DOMNamespaces';
import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
import assertValidProps from '../shared/assertValidProps';
import dangerousStyleValue from '../shared/dangerousStyleValue';
import isCustomComponent from '../shared/isCustomComponent';
import omittedCloseTags from '../shared/omittedCloseTags';
import warnValidStyle from '../shared/warnValidStyle';
import {validateProperties as validateARIAProperties} from '../shared/ReactDOMInvalidARIAHook';
import {validateProperties as validateInputProperties} from '../shared/ReactDOMNullInputValuePropHook';
import {validateProperties as validateUnknownProperties} from '../shared/ReactDOMUnknownPropertyHook';
// Based on reading the React.Children implementation. TODO: type this somewhere?
type ReactNode = string | number | ReactElement;
type FlatReactChildren = Array<null | ReactNode>;
type toArrayType = (children: mixed) => FlatReactChildren;
var toArray = ((React.Children.toArray: any): toArrayType);
var getStackAddendum = emptyFunction.thatReturns('');
if (__DEV__) {
var validatePropertiesInDevelopment = function(type, props) {
validateARIAProperties(type, props);
validateInputProperties(type, props);
validateUnknownProperties(type, props, /* canUseEventSystem */ false);
};
var describeStackFrame = function(element): string {
var source = element._source;
var type = element.type;
var name = getComponentName(type);
var ownerName = null;
return describeComponentFrame(name, source, ownerName);
};
var currentDebugStack = null;
var currentDebugElementStack = null;
var setCurrentDebugStack = function(stack: Array<Frame>) {
var frame: Frame = stack[stack.length - 1];
currentDebugElementStack = ((frame: any): FrameDev).debugElementStack;
// We are about to enter a new composite stack, reset the array.
currentDebugElementStack.length = 0;
currentDebugStack = stack;
ReactDebugCurrentFrame.getCurrentStack = getStackAddendum;
};
var pushElementToDebugStack = function(element: ReactElement) {
if (currentDebugElementStack !== null) {
currentDebugElementStack.push(element);
}
};
var resetCurrentDebugStack = function() {
currentDebugElementStack = null;
currentDebugStack = null;
ReactDebugCurrentFrame.getCurrentStack = null;
};
getStackAddendum = function(): null | string {
if (currentDebugStack === null) {
return '';
}
let stack = '';
let debugStack = currentDebugStack;
for (let i = debugStack.length - 1; i >= 0; i--) {
const frame: Frame = debugStack[i];
let debugElementStack = ((frame: any): FrameDev).debugElementStack;
for (let ii = debugElementStack.length - 1; ii >= 0; ii--) {
stack += describeStackFrame(debugElementStack[ii]);
}
}
return stack;
};
}
var didWarnDefaultInputValue = false;
var didWarnDefaultChecked = false;
var didWarnDefaultSelectValue = false;
var didWarnDefaultTextareaValue = false;
var didWarnInvalidOptionChildren = false;
var didWarnAboutNoopUpdateForComponent = {};
var valuePropNames = ['value', 'defaultValue'];
var newlineEatingTags = {
listing: true,
pre: true,
textarea: true,
};
function getComponentName(type) {
return typeof type === 'string'
? type
: typeof type === 'function' ? type.displayName || type.name : null;
}
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
function validateDangerousTag(tag) {
if (!validatedTagCache.hasOwnProperty(tag)) {
invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag);
validatedTagCache[tag] = true;
}
}
var processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
});
function createMarkupForStyles(styles): string | null {
var serialized = '';
var delimiter = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var isCustomProperty = styleName.indexOf('--') === 0;
var styleValue = styles[styleName];
if (__DEV__) {
if (!isCustomProperty) {
warnValidStyle(styleName, styleValue, getStackAddendum);
}
}
if (styleValue != null) {
serialized += delimiter + processStyleName(styleName) + ':';
serialized += dangerousStyleValue(
styleName,
styleValue,
isCustomProperty,
);
delimiter = ';';
}
}
return serialized || null;
}
function warnNoop(
publicInstance: React$Component<any, any>,
callerName: string,
) {
if (__DEV__) {
var constructor = publicInstance.constructor;
const componentName =
(constructor && getComponentName(constructor)) || 'ReactClass';
const warningKey = `${componentName}.${callerName}`;
if (didWarnAboutNoopUpdateForComponent[warningKey]) {
return;
}
warning(
false,
'%s(...): Can only update a mounting component. ' +
'This usually means you called %s() outside componentWillMount() on the server. ' +
'This is a no-op.\n\nPlease check the code for the %s component.',
callerName,
callerName,
componentName,
);
didWarnAboutNoopUpdateForComponent[warningKey] = true;
}
}
function shouldConstruct(Component) {
return Component.prototype && Component.prototype.isReactComponent;
}
function getNonChildrenInnerMarkup(props) {
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
var content = props.children;
if (typeof content === 'string' || typeof content === 'number') {
return escapeTextForBrowser(content);
}
}
return null;
}
function flattenTopLevelChildren(children: mixed): FlatReactChildren {
if (!React.isValidElement(children)) {
return toArray(children);
}
const element = ((children: any): ReactElement);
if (element.type !== REACT_FRAGMENT_TYPE) {
return [element];
}
const fragmentChildren = element.props.children;
if (!React.isValidElement(fragmentChildren)) {
return toArray(fragmentChildren);
}
const fragmentChildElement = ((fragmentChildren: any): ReactElement);
return [fragmentChildElement];
}
function flattenOptionChildren(children: mixed): string {
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
React.Children.forEach(children, function(child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else {
if (__DEV__) {
if (!didWarnInvalidOptionChildren) {
didWarnInvalidOptionChildren = true;
warning(
false,
'Only strings and numbers are supported as <option> children.',
);
}
}
}
});
return content;
}
function maskContext(type, context) {
var contextTypes = type.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
}
function checkContextTypes(typeSpecs, values, location: string) {
if (__DEV__) {
checkPropTypes(typeSpecs, values, location, 'Component', getStackAddendum);
}
}
function processContext(type, context) {
var maskedContext = maskContext(type, context);
if (__DEV__) {
if (type.contextTypes) {
checkContextTypes(type.contextTypes, maskedContext, 'context');
}
}
return maskedContext;
}
var STYLE = 'style';
var RESERVED_PROPS = {
children: null,
dangerouslySetInnerHTML: null,
suppressContentEditableWarning: null,
suppressHydrationWarning: null,
};
function createOpenTagMarkup(
tagVerbatim: string,
tagLowercase: string,
props: Object,
namespace: string,
makeStaticMarkup: boolean,
isRootElement: boolean,
): string {
var ret = '<' + tagVerbatim;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (propKey === STYLE) {
propValue = createMarkupForStyles(propValue);
}
var markup = null;
if (isCustomComponent(tagLowercase, props)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
markup = createMarkupForCustomAttribute(propKey, propValue);
}
} else {
markup = createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (makeStaticMarkup) {
return ret;
}
if (isRootElement) {
ret += ' ' + createMarkupForRoot();
}
return ret;
}
function validateRenderResult(child, type) {
if (child === undefined) {
invariant(
false,
'%s(...): Nothing was returned from render. This usually means a ' +
'return statement is missing. Or, to render nothing, ' +
'return null.',
getComponentName(type) || 'Component',
);
}
}
function resolve(
child: mixed,
context: Object,
): {|
child: mixed,
context: Object,
|} {
while (React.isValidElement(child)) {
// Safe because we just checked it's an element.
var element: ReactElement = ((child: any): ReactElement);
if (__DEV__) {
pushElementToDebugStack(element);
}
var Component = element.type;
if (typeof Component !== 'function') {
break;
}
var publicContext = processContext(Component, context);
var inst;
var queue = [];
var replace = false;
var updater = {
isMounted: function(publicInstance) {
return false;
},
enqueueForceUpdate: function(publicInstance) {
if (queue === null) {
warnNoop(publicInstance, 'forceUpdate');
return null;
}
},
enqueueReplaceState: function(publicInstance, completeState) {
replace = true;
queue = [completeState];
},
enqueueSetState: function(publicInstance, partialState) {
if (queue === null) {
warnNoop(publicInstance, 'setState');
return null;
}
queue.push(partialState);
},
};
if (shouldConstruct(Component)) {
inst = new Component(element.props, publicContext, updater);
} else {
inst = Component(element.props, publicContext, updater);
if (inst == null || inst.render == null) {
child = inst;
validateRenderResult(child, Component);
continue;
}
}
inst.props = element.props;
inst.context = publicContext;
inst.updater = updater;
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
if (inst.componentWillMount) {
inst.componentWillMount();
if (queue.length) {
var oldQueue = queue;
var oldReplace = replace;
queue = null;
replace = false;
if (oldReplace && oldQueue.length === 1) {
inst.state = oldQueue[0];
} else {
var nextState = oldReplace ? oldQueue[0] : inst.state;
var dontMutate = true;
for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
var partial = oldQueue[i];
var partialState =
typeof partial === 'function'
? partial.call(inst, nextState, element.props, publicContext)
: partial;
if (partialState) {
if (dontMutate) {
dontMutate = false;
nextState = Object.assign({}, nextState, partialState);
} else {
Object.assign(nextState, partialState);
}
}
}
inst.state = nextState;
}
} else {
queue = null;
}
}
child = inst.render();
if (__DEV__) {
if (child === undefined && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
child = null;
}
}
validateRenderResult(child, Component);
var childContext;
if (typeof inst.getChildContext === 'function') {
var childContextTypes = Component.childContextTypes;
if (typeof childContextTypes === 'object') {
childContext = inst.getChildContext();
for (let contextKey in childContext) {
invariant(
contextKey in childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
getComponentName(Component) || 'Unknown',
contextKey,
);
}
} else {
warning(
false,
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
getComponentName(Component) || 'Unknown',
);
}
}
if (childContext) {
context = Object.assign({}, context, childContext);
}
}
return {child, context};
}
type Frame = {
domNamespace: string,
children: FlatReactChildren,
childIndex: number,
context: Object,
footer: string,
};
type FrameDev = Frame & {
debugElementStack: Array<ReactElement>,
};
class ReactDOMServerRenderer {
stack: Array<Frame>;
exhausted: boolean;
// TODO: type this more strictly:
currentSelectValue: any;
previousWasTextNode: boolean;
makeStaticMarkup: boolean;
constructor(children: mixed, makeStaticMarkup: boolean) {
const flatChildren = flattenTopLevelChildren(children);
var topFrame: Frame = {
// Assume all trees start in the HTML namespace (not totally true, but
// this is what we did historically)
domNamespace: Namespaces.html,
children: flatChildren,
childIndex: 0,
context: emptyObject,
footer: '',
};
if (__DEV__) {
((topFrame: any): FrameDev).debugElementStack = [];
}
this.stack = [topFrame];
this.exhausted = false;
this.currentSelectValue = null;
this.previousWasTextNode = false;
this.makeStaticMarkup = makeStaticMarkup;
}
read(bytes: number): string | null {
if (this.exhausted) {
return null;
}
var out = '';
while (out.length < bytes) {
if (this.stack.length === 0) {
this.exhausted = true;
break;
}
var frame: Frame = this.stack[this.stack.length - 1];
if (frame.childIndex >= frame.children.length) {
var footer = frame.footer;
out += footer;
if (footer !== '') {
this.previousWasTextNode = false;
}
this.stack.pop();
if (frame.tag === 'select') {
this.currentSelectValue = null;
}
continue;
}
var child = frame.children[frame.childIndex++];
if (__DEV__) {
setCurrentDebugStack(this.stack);
}
out += this.render(child, frame.context, frame.domNamespace);
if (__DEV__) {
// TODO: Handle reentrant server render calls. This doesn't.
resetCurrentDebugStack();
}
}
return out;
}
render(
child: ReactNode | null,
context: Object,
parentNamespace: string,
): string {
if (typeof child === 'string' || typeof child === 'number') {
var text = '' + child;
if (text === '') {
return '';
}
if (this.makeStaticMarkup) {
return escapeTextForBrowser(text);
}
if (this.previousWasTextNode) {
return '<!-- -->' + escapeTextForBrowser(text);
}
this.previousWasTextNode = true;
return escapeTextForBrowser(text);
} else {
var nextChild;
({child: nextChild, context} = resolve(child, context));
if (nextChild === null || nextChild === false) {
return '';
} else if (!React.isValidElement(nextChild)) {
if (nextChild != null && nextChild.$$typeof != null) {
// Catch unexpected special types early.
const $$typeof = nextChild.$$typeof;
invariant(
$$typeof !== REACT_PORTAL_TYPE,
'Portals are not currently supported by the server renderer. ' +
'Render them conditionally so that they only appear on the client render.',
);
invariant(
$$typeof !== REACT_CALL_TYPE && $$typeof !== REACT_RETURN_TYPE,
'The experimental Call and Return types are not currently ' +
'supported by the server renderer.',
);
// Catch-all to prevent an infinite loop if React.Children.toArray() supports some new type.
invariant(
false,
'Unknown element-like object type: %s. This is likely a bug in React. ' +
'Please file an issue.',
($$typeof: any).toString(),
);
}
const nextChildren = toArray(nextChild);
const frame: Frame = {
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
} else if (
((nextChild: any): ReactElement).type === REACT_FRAGMENT_TYPE
) {
const nextChildren = toArray(
((nextChild: any): ReactElement).props.children,
);
const frame: Frame = {
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
} else {
// Safe because we just checked it's an element.
var nextElement = ((nextChild: any): ReactElement);
return this.renderDOM(nextElement, context, parentNamespace);
}
}
}
renderDOM(
element: ReactElement,
context: Object,
parentNamespace: string,
): string {
var tag = element.type.toLowerCase();
let namespace = parentNamespace;
if (parentNamespace === Namespaces.html) {
namespace = getIntrinsicNamespace(tag);
}
if (__DEV__) {
if (namespace === Namespaces.html) {
// Should this check be gated by parent namespace? Not sure we want to
// allow <SVG> or <mATH>.
warning(
tag === element.type,
'<%s /> is using uppercase HTML. Always use lowercase HTML tags ' +
'in React.',
element.type,
);
}
}
validateDangerousTag(tag);
var props = element.props;
if (tag === 'input') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'input',
props,
getStackAddendum,
);
if (
props.checked !== undefined &&
props.defaultChecked !== undefined &&
!didWarnDefaultChecked
) {
warning(
false,
'%s contains an input of type %s with both checked and defaultChecked props. ' +
'Input elements must be either controlled or uncontrolled ' +
'(specify either the checked prop, or the defaultChecked prop, but not ' +
'both). Decide between using a controlled or uncontrolled input ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
'A component',
props.type,
);
didWarnDefaultChecked = true;
}
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultInputValue
) {
warning(
false,
'%s contains an input of type %s with both value and defaultValue props. ' +
'Input elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled input ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
'A component',
props.type,
);
didWarnDefaultInputValue = true;
}
}
props = Object.assign(
{
type: undefined,
},
props,
{
defaultChecked: undefined,
defaultValue: undefined,
value: props.value != null ? props.value : props.defaultValue,
checked: props.checked != null ? props.checked : props.defaultChecked,
},
);
} else if (tag === 'textarea') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'textarea',
props,
getStackAddendum,
);
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultTextareaValue
) {
warning(
false,
'Textarea elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled textarea ' +
'and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
);
didWarnDefaultTextareaValue = true;
}
}
var initialValue = props.value;
if (initialValue == null) {
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var textareaChildren = props.children;
if (textareaChildren != null) {
if (__DEV__) {
warning(
false,
'Use the `defaultValue` or `value` props instead of setting ' +
'children on <textarea>.',
);
}
invariant(
defaultValue == null,
'If you supply `defaultValue` on a <textarea>, do not pass children.',
);
if (Array.isArray(textareaChildren)) {
invariant(
textareaChildren.length <= 1,
'<textarea> can only have at most one child.',
);
textareaChildren = textareaChildren[0];
}
defaultValue = '' + textareaChildren;
}
if (defaultValue == null) {
defaultValue = '';
}
initialValue = defaultValue;
}
props = Object.assign({}, props, {
value: undefined,
children: '' + initialValue,
});
} else if (tag === 'select') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'select',
props,
getStackAddendum,
);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
var isArray = Array.isArray(props[propName]);
if (props.multiple && !isArray) {
warning(
false,
'The `%s` prop supplied to <select> must be an array if ' +
'`multiple` is true.%s',
propName,
'', // getDeclarationErrorAddendum(),
);
} else if (!props.multiple && isArray) {
warning(
false,
'The `%s` prop supplied to <select> must be a scalar ' +
'value if `multiple` is false.%s',
propName,
'', // getDeclarationErrorAddendum(),
);
}
}
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultSelectValue
) {
warning(
false,
'Select elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled select ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
);
didWarnDefaultSelectValue = true;
}
}
this.currentSelectValue =
props.value != null ? props.value : props.defaultValue;
props = Object.assign({}, props, {
value: undefined,
});
} else if (tag === 'option') {
var selected = null;
var selectValue = this.currentSelectValue;
var optionChildren = flattenOptionChildren(props.children);
if (selectValue != null) {
var value;
if (props.value != null) {
value = props.value + '';
} else {
value = optionChildren;
}
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var j = 0; j < selectValue.length; j++) {
if ('' + selectValue[j] === value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === value;
}
props = Object.assign(
{
selected: undefined,
children: undefined,
},
props,
{
selected: selected,
children: optionChildren,
},
);
}
}
if (__DEV__) {
validatePropertiesInDevelopment(tag, props);
}
assertValidProps(tag, props, getStackAddendum);
var out = createOpenTagMarkup(
element.type,
tag,
props,
namespace,
this.makeStaticMarkup,
this.stack.length === 1,
);
var footer = '';
if (omittedCloseTags.hasOwnProperty(tag)) {
out += '/>';
} else {
out += '>';
footer = '</' + element.type + '>';
}
var children;
var innerMarkup = getNonChildrenInnerMarkup(props);
if (innerMarkup != null) {
children = [];
if (newlineEatingTags[tag] && innerMarkup.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
out += '\n';
}
out += innerMarkup;
} else {
children = toArray(props.children);
}
var frame = {
domNamespace: getChildNamespace(parentNamespace, element.type),
tag,
children,
childIndex: 0,
context: context,
footer: footer,
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
this.previousWasTextNode = false;
return out;
}
}
export default ReactDOMServerRenderer;
|
node_modules/antd/es/input-number/index.js | prodigalyijun/demo-by-antd | import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var __rest = this && this.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
}return t;
};
import React from 'react';
import classNames from 'classnames';
import RcInputNumber from 'rc-input-number';
var InputNumber = function (_React$Component) {
_inherits(InputNumber, _React$Component);
function InputNumber() {
_classCallCheck(this, InputNumber);
return _possibleConstructorReturn(this, (InputNumber.__proto__ || Object.getPrototypeOf(InputNumber)).apply(this, arguments));
}
_createClass(InputNumber, [{
key: 'render',
value: function render() {
var _classNames;
var _a = this.props,
className = _a.className,
size = _a.size,
others = __rest(_a, ["className", "size"]);
var inputNumberClass = classNames((_classNames = {}, _defineProperty(_classNames, this.props.prefixCls + '-lg', size === 'large'), _defineProperty(_classNames, this.props.prefixCls + '-sm', size === 'small'), _classNames), className);
return React.createElement(RcInputNumber, _extends({ className: inputNumberClass }, others));
}
}]);
return InputNumber;
}(React.Component);
export default InputNumber;
InputNumber.defaultProps = {
prefixCls: 'ant-input-number',
step: 1
}; |
docs/src/app/components/pages/components/TextField/ExampleSimple.js | tan-jerene/material-ui | import React from 'react';
import TextField from 'material-ui/TextField';
const TextFieldExampleSimple = () => (
<div>
<TextField
hintText="Hint Text"
/><br />
<br />
<TextField
hintText="The hint text can be as long as you want, it will wrap."
/><br />
<TextField
id="text-field-default"
defaultValue="Default Value"
/><br />
<TextField
hintText="Hint Text"
floatingLabelText="Floating Label Text"
/><br />
<TextField
hintText="Hint Text"
floatingLabelText="Fixed Floating Label Text"
floatingLabelFixed={true}
/><br />
<TextField
hintText="Password Field"
floatingLabelText="Password"
type="password"
/><br />
<TextField
hintText="MultiLine with rows: 2 and rowsMax: 4"
multiLine={true}
rows={2}
rowsMax={4}
/><br />
<TextField
hintText="Message Field"
floatingLabelText="MultiLine and FloatingLabel"
multiLine={true}
rows={2}
/><br />
<TextField
hintText="Full width"
fullWidth={true}
/>
</div>
);
export default TextFieldExampleSimple;
|
src/CitySearchPanel.js | cqqccqc/city-picker | import React, { Component } from 'react';
import { List } from 'immutable';
import './CitySearchPanel.css';
const classnames = require('classnames');
class CitySearchPanel extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div className="c_address_select">
<div className="c_address_wrap">
<div className="c_address_hd">h,按拼音排序</div>
<div className="c_address_list">
<a data="haerbin|哈尔滨|haerbin|哈尔滨|heb" style="display: block;" className="hover"><span>haerbin</span>哈尔滨</a>
<a data="haian|海安|haian|海安|ha" style="display: block;"><span>haian</span>海安</a>
<a data="haicheng|海城|haicheng|海城|hc" style="display: block;"><span>haicheng</span>海城</a>
<a data="haidong|海东|haidong|海东|hd" style="display: block;"><span>haidong</span>海东</a>
<a data="haifeng|海丰|haifeng|海丰|hf" style="display: block;"><span>haifeng</span>海丰</a>
<a data="haikou|海口|haikou|海口|hk" style="display: block;"><span>haikou</span>海口</a>
<a data="haimen|海门|haimen|海门|hm" style="display: block;"><span>haimen</span>海门</a>
<a data="haining|海宁|haining|海宁|hn" style="display: block;"><span>haining</span>海宁</a>
<a data="haixi|海西|haixi|海西|hx" style="display: block;"><span>haixi</span>海西</a>
<a data="haixing|海兴|haixing|海兴|hx" style="display: block;"><span>haixing</span>海兴</a>
<a data="haiyang|海阳|haiyang|海阳|hy" style="display: block;"><span>haiyang</span>海阳</a>
<a data="haiyuan2|海原|haiyuan2|海原|hy" style="display: block;"><span>haiyuan2</span>海原</a>
</div>
<div className="c_address_pagebreak" style="display: block;">
<a className="address_current" page="0">1</a>
<a page="1">2</a>
<a page="2">3</a>
<a page="3">4</a>
<a page="4">5</a>
<a page="1">-></a> </div>
</div>
</div>
</div>
);
}
}
export default CitySearchPanel;
|
src/components/DevIcon.js | abdulhannanali/github-organization-repos | import React from 'react';
import classnames from 'classnames';
const DevIcon = ({ language, colored, wikiLink }) => {
if (!language) {
throw new Error('`language` option is required for `DevIcon` component');
}
const devIconClasses = getDevIcon(language, colored);
let iTag = (<i className={devIconClasses} aria-hidden={true}></i>);
let devIconTag = iTag;
if (wikiLink) {
const wikiHref = `https://rosettacode.org/wiki/${language}`;
devIconTag = (
<a
href={wikiHref}
style={{ textDecoration: 'none' }}
aria-label={'Wiki for language ' + language}>{iTag}</a>
);
}
return (
<div className="DevIcon">
{devIconTag}
</div>
);
};
/**
* Gets the DevIcon for the given text
*/
function getDevIcon(language, colored = false) {
if (!language) {
return '';
}
language = language.toLowerCase();
/** Some languages that don't map well by default
* TODO: This should be ideally replaced with a better mechanism
* to better map languages to their correct representation.
*/
switch (language) {
case 'c#':
language = 'csharp';
break;
case 'c++':
language = 'cplusplus';
break;
default:
break;
}
return (
classnames('devicon-' + language + '-plain', {
colored,
})
);
}
export default DevIcon; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.