path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
react-flux-mui/js/material-ui/src/svg-icons/communication/screen-share.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationScreenShare = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.11-.9-2-2-2H4c-1.11 0-2 .89-2 2v10c0 1.1.89 2 2 2H0v2h24v-2h-4zm-7-3.53v-2.19c-2.78 0-4.61.85-6 2.72.56-2.67 2.11-5.33 6-5.87V7l4 3.73-4 3.74z"/>
</SvgIcon>
);
CommunicationScreenShare = pure(CommunicationScreenShare);
CommunicationScreenShare.displayName = 'CommunicationScreenShare';
CommunicationScreenShare.muiName = 'SvgIcon';
export default CommunicationScreenShare;
|
storybook/config.js | moeism/mastodon | import { configure, setAddon } from '@kadira/storybook';
import IntlAddon from 'react-storybook-addon-intl';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { addLocaleData } from 'react-intl';
import en from 'react-intl/locale-data/en';
import '../app/assets/stylesheets/components.scss'
import './storybook.scss'
setAddon(IntlAddon);
addLocaleData(en);
window.storiesOf = storiesOf;
window.action = action;
window.React = React;
let req = require.context('./stories/', true, /.story.jsx$/);
function loadStories () {
req.keys().forEach((filename) => req(filename))
}
configure(loadStories, module);
|
src/components/NeededEquipment.js | IAmPicard/StarTrekTimelinesSpreadsheet | import React from 'react';
import { getTheme } from '@uifabric/styling';
import { Input, Dropdown, Grid } from 'semantic-ui-react';
import { ItemDisplay } from './ItemDisplay';
import { ReplicatorDialog } from './ReplicatorDialog';
import { WarpDialog } from './WarpDialog';
import { CollapsibleSection } from './CollapsibleSection.js';
import STTApi from '../api';
import { CONFIG } from '../api';
import { download } from '../utils/pal';
import { simplejson2csv } from '../utils/simplejson2csv';
export class NeededEquipment extends React.Component {
constructor(props) {
super(props);
let peopleList = [];
STTApi.allcrew.forEach(crew => {
let have = STTApi.roster.find(c => c.symbol === crew.symbol);
peopleList.push({
key: crew.id,
value: crew.id,
image: { src: crew.iconUrl },
text: `${crew.name} (${have ? 'owned' : 'unowned'} ${crew.max_rarity}*)`
});
});
this.state = {
neededEquipment: [],
peopleList: peopleList,
currentSelectedItems: [],
filters: {
onlyNeeded: true,
onlyFaction: false,
cadetable: false,
allLevels: false,
userText: undefined
}
};
this._replicateDialog = React.createRef();
this._warpDialog = React.createRef();
}
_getMissionCost(id, mastery_level) {
for (let mission of STTApi.missions) {
let q = mission.quests.find(q => q.id === id);
if (q) {
if (q.locked || (q.mastery_levels[mastery_level].progress.goal_progress !== q.mastery_levels[mastery_level].progress.goals)) {
return undefined;
}
return q.mastery_levels[mastery_level].energy_cost;
}
}
return undefined;
}
_filterNeededEquipment(filters) {
const neededEquipment = STTApi.getNeededEquipment(filters, this.state.currentSelectedItems);
return this.setState({
neededEquipment: neededEquipment
});
}
_toggleFilter(name) {
const newFilters = Object.assign({}, this.state.filters);
newFilters[name] = !newFilters[name];
this.setState({
filters: newFilters
}, () => { this._updateCommandItems(); });
return this._filterNeededEquipment(newFilters);
}
_filterText(filterString) {
const newFilters = Object.assign({}, this.state.filters);
newFilters.userText = filterString;
this.setState({
filters: newFilters
});
return this._filterNeededEquipment(newFilters);
}
renderSources(entry) {
let equipment = entry.equipment;
let counts = entry.counts;
let disputeMissions = equipment.item_sources.filter(e => e.type === 0);
let shipBattles = equipment.item_sources.filter(e => e.type === 2);
let factions = equipment.item_sources.filter(e => e.type === 1);
let cadetSources = entry.cadetSources;
let factionSources = entry.factionSources;
let res = [];
res.push(<div key={'crew'}>
<b>Crew: </b>
{Array.from(counts.values()).sort((a, b) => b.count - a.count).map((entry, idx) =>
<span key={idx}>{entry.crew.name} (x{entry.count})</span>
).reduce((prev, curr) => [prev, ', ', curr])}
</div>)
if (disputeMissions.length > 0) {
res.push(<div key={'disputeMissions'} style={{ lineHeight: '2.5' }}>
<b>Missions: </b>
{disputeMissions.map((entry, idx) =>
<div className={"ui labeled button compact tiny" + ((this._getMissionCost(entry.id, entry.mastery) === undefined) ? " disabled" : "")} key={idx} onClick={() => this._warpDialog.current.show(entry.id, entry.mastery)}>
<div className="ui button compact tiny">
{entry.name} <span style={{ display: 'inline-block' }}><img src={CONFIG.MASTERY_LEVELS[entry.mastery].url()} height={14} /></span> ({entry.chance_grade}/5)
</div>
<a className="ui blue label">
{this._getMissionCost(entry.id, entry.mastery)} <span style={{ display: 'inline-block' }}><img src={CONFIG.SPRITES['energy_icon'].url} height={14} /></span>
</a>
</div>
).reduce((prev, curr) => [prev, ' ', curr])}
</div>)
}
if (shipBattles.length > 0) {
res.push(<div key={'shipBattles'} style={{ lineHeight: '2.5' }}>
<b>Ship battles: </b>
{shipBattles.map((entry, idx) =>
<div className={"ui labeled button compact tiny" + ((this._getMissionCost(entry.id, entry.mastery) === undefined) ? " disabled" : "")} key={idx} onClick={() => this._warpDialog.current.show(entry.id, entry.mastery)}>
<div className="ui button compact tiny">
{entry.name} <span style={{ display: 'inline-block' }}><img src={CONFIG.MASTERY_LEVELS[entry.mastery].url()} height={14} /></span> ({entry.chance_grade}/5)
</div>
<a className="ui blue label">
{this._getMissionCost(entry.id, entry.mastery)} <span style={{ display: 'inline-block' }}><img src={CONFIG.SPRITES['energy_icon'].url} height={14} /></span>
</a>
</div>
).reduce((prev, curr) => [prev, ' ', curr])}
</div>)
}
if (cadetSources.length > 0) {
res.push(<div key={'cadet'}>
<b>Cadet missions: </b>
{cadetSources.map((entry, idx) =>
<span key={idx}>{`${entry.quest.name} (${entry.mission.episode_title})`} <span style={{ display: 'inline-block' }}><img src={CONFIG.MASTERY_LEVELS[entry.masteryLevel].url()} height={16} /></span></span>
).reduce((prev, curr) => [prev, ', ', curr])}
</div>)
}
if (factions.length > 0) {
res.push(<div key={'factions'}>
<b>Faction missions: </b>
{factions.map((entry, idx) =>
`${entry.name} (${entry.chance_grade}/5)`
).join(', ')}
</div>)
}
if (factionSources.length > 0) {
res.push(<div key={'factionstores'}>
<b>Faction shops: </b>
{factionSources.map((entry, idx) =>
`${entry.cost_amount} ${CONFIG.CURRENCIES[entry.cost_currency].name} in the ${entry.faction.name} shop`
).join(', ')}
</div>)
}
return <div>{res}</div>;
}
_selectFavorites() {
let dupeChecker = new Set(this.state.currentSelectedItems);
STTApi.roster.filter(c => c.favorite).forEach(crew => {
if (!dupeChecker.has(crew.id)) {
dupeChecker.add(crew.id);
}
});
this.setState({ currentSelectedItems: Array.from(dupeChecker.values()) });
}
componentDidMount() {
this._updateCommandItems();
this._filterNeededEquipment(this.state.filters);
}
_updateCommandItems() {
if (this.props.onCommandItemsUpdate) {
this.props.onCommandItemsUpdate([
{
key: 'settings',
text: 'Settings',
iconProps: { iconName: 'Equalizer' },
subMenuProps: {
items: [{
key: 'onlyFavorite',
text: 'Show only for favorite crew',
onClick: () => { this._selectFavorites(); }
},
{
key: 'onlyNeeded',
text: 'Show only insufficient equipment',
canCheck: true,
isChecked: this.state.filters.onlyNeeded,
onClick: () => { this._toggleFilter('onlyNeeded'); }
},
{
key: 'onlyFaction',
text: 'Show items obtainable through faction missions only',
canCheck: true,
isChecked: this.state.filters.onlyFaction,
onClick: () => { this._toggleFilter('onlyFaction'); }
},
{
key: 'cadetable',
text: 'Show items obtainable through cadet missions only',
canCheck: true,
isChecked: this.state.filters.cadetable,
onClick: () => { this._toggleFilter('cadetable'); }
},
{
key: 'allLevels',
text: '(EXPERIMENTAL) show needs for all remaining level bands to FE',
canCheck: true,
isChecked: this.state.filters.allLevels,
onClick: () => { this._toggleFilter('allLevels'); }
}]
}
},
{
key: 'exportCsv',
name: 'Export CSV...',
iconProps: { iconName: 'ExcelDocument' },
onClick: () => { this._exportCSV(); }
}
]);
}
}
renderFarmList() {
if (!this.state.neededEquipment) {
return <span />;
}
let missionMap = new Map();
this.state.neededEquipment.forEach(entry => {
let equipment = entry.equipment;
let missions = equipment.item_sources.filter(e => (e.type === 0) || (e.type === 2));
missions.forEach(mission => {
if (!this._getMissionCost(mission.id, mission.mastery)) {
// Disabled missions are filtered out
return;
}
let key = mission.id * (mission.mastery + 1);
if (!missionMap.has(key)) {
missionMap.set(key, {
mission: mission,
equipment: []
});
}
missionMap.get(key).equipment.push(equipment);
});
});
let entries = Array.from(missionMap.values());
entries.sort((a, b) => a.equipment.length - b.equipment.length);
// Minimize entries
const obtainable = (equipment, entry) => entries.some(e => (e !== entry) && e.equipment.some(eq => eq.id === equipment.id));
// TODO: there must be a better algorithm for this, maybe one that also accounts for drop chances to break ties :)
let reducePossible = true;
while (reducePossible) {
reducePossible = false;
for (let entry of entries) {
if (entry.equipment.every(eq => obtainable(eq, entry))) {
entries.splice(entries.indexOf(entry), 1);
reducePossible = true;
}
}
}
entries.reverse();
let res = [];
for (let val of entries) {
let key = val.mission.id * (val.mission.mastery + 1);
let entry = val.mission;
res.push(<div key={key} style={{ lineHeight: '2.5' }}>
<div className="ui labeled button compact tiny" key={key} onClick={() => this._warpDialog.current.show(entry.id, entry.mastery)}>
<div className="ui button compact tiny">
{entry.name} <span style={{ display: 'inline-block' }}><img src={CONFIG.MASTERY_LEVELS[entry.mastery].url()} height={14} /></span> ({entry.chance_grade}/5)
</div>
<a className="ui blue label">
{this._getMissionCost(entry.id, entry.mastery)} <span style={{ display: 'inline-block' }}><img src={CONFIG.SPRITES['energy_icon'].url} height={14} /></span>
</a>
</div>
<div className="ui label small">
{val.equipment.map((entry, idx) => <span key={idx} style={{ color: entry.rarity && CONFIG.RARITIES[entry.rarity].color }}>{(entry.rarity ? CONFIG.RARITIES[entry.rarity].name : '')} {entry.name}</span>).reduce((prev, curr) => [prev, ', ', curr])}
</div>
</div>);
}
return <CollapsibleSection title='Farming list (WORK IN PROGRESS, NEEDS A LOT OF IMPROVEMENT)'>
<p>This list minimizes the number of missions that can yield all filtered equipment as rewards (it <b>doesn't</b> factor in drop chances).</p>
{res}
</CollapsibleSection>;
}
render() {
if (this.state.neededEquipment) {
return (<div className='tab-panel-x' data-is-scrollable='true'>
<p>Equipment required to fill all open slots for all crew currently in your roster{!this.state.filters.allLevels && <span>, for their current level band</span>}</p>
<small>Note that partially complete recipes result in zero counts for some crew and items</small>
{this.state.filters.allLevels && <div>
<br />
<p><span style={{ color: 'red', fontWeight: 'bold' }}>WARNING!</span> Equipment information for all levels is crowdsourced. It is most likely incomplete and potentially incorrect (especially if DB changed the recipe tree since the data was cached). This equipment may also not display an icon and may show erroneous source information! Use this data only as rough estimates.</p>
<br />
</div>}
<Grid>
<Grid.Column width={6}>
<Input fluid icon='search' placeholder='Filter...' value={this.state.filters.userText} onChange={(e, {value}) => this._filterText(value)} />
</Grid.Column>
<Grid.Column width={10}>
<Dropdown clearable fluid multiple search selection options={this.state.peopleList}
placeholder='Select or search crew'
label='Show only for these crew'
value={this.state.currentSelectedItems}
onChange={(e, { value }) => this.setState({ currentSelectedItems: value }, () => this._filterText(this.state.filters.userText))}
/>
</Grid.Column>
</Grid>
{this.state.neededEquipment.map((entry, idx) =>
<div key={idx} className="ui raised segment" style={{ display: 'grid', gridTemplateColumns: '128px auto', gridTemplateAreas: `'icon name' 'icon details'`, padding: '8px 4px', margin: '8px', backgroundColor: getTheme().palette.themeLighter }}>
<div style={{ gridArea: 'icon', textAlign: 'center' }}>
<ItemDisplay src={entry.equipment.iconUrl} size={128} maxRarity={entry.equipment.rarity} rarity={entry.equipment.rarity} />
<button style={{ marginBottom: '8px' }} className="ui button" onClick={() => this._replicateDialog.current.show(entry.equipment)}>Replicate...</button>
</div>
<div style={{ gridArea: 'name', alignSelf: 'start', margin: '0' }}>
<h4><a href={'https://stt.wiki/wiki/' + entry.equipment.name.split(' ').join('_')} target='_blank'>{entry.equipment.name}</a>
{` (need ${entry.needed}, have ${entry.have})`}</h4>
</div>
<div style={{ gridArea: 'details', alignSelf: 'start' }}>
{this.renderSources(entry)}
</div>
</div>
)}
{this.renderFarmList()}
<ReplicatorDialog ref={this._replicateDialog} />
<WarpDialog ref={this._warpDialog} onWarped={() => this._filterNeededEquipment(this.state.filters)} />
</div>);
}
else {
return <span />;
}
}
_exportCSV() {
let fields = [{
label: 'Equipment name',
value: (row) => row.equipment.name
},
{
label: 'Equipment rarity',
value: (row) => row.equipment.rarity
},
{
label: 'Needed',
value: (row) => row.needed
},
{
label: 'Have',
value: (row) => row.have
},
{
label: 'Missions',
value: (row) => row.equipment.item_sources.filter(e => e.type === 0).map((mission) => `${mission.name} (${CONFIG.MASTERY_LEVELS[mission.mastery].name} ${mission.chance_grade}/5, ${(mission.energy_quotient * 100).toFixed(2)}%)`).join(', ')
},
{
label: 'Ship battles',
value: (row) => row.equipment.item_sources.filter(e => e.type === 2).map((mission) => `${mission.name} (${CONFIG.MASTERY_LEVELS[mission.mastery].name} ${mission.chance_grade}/5, ${(mission.energy_quotient * 100).toFixed(2)}%)`).join(', ')
},
{
label: 'Faction missions',
value: (row) => row.equipment.item_sources.filter(e => e.type === 1).map((mission) => `${mission.name} (${mission.chance_grade}/5, ${(mission.energy_quotient * 100).toFixed(2)}%)`).join(', ')
},
{
label: 'Cadet misions',
value: (row) => row.cadetSources.map((mission) => `${mission.quest.name} from ${mission.mission.episode_title} (${CONFIG.MASTERY_LEVELS[mission.masteryLevel].name})`).join(', ')
}
];
let csv = simplejson2csv(this.state.neededEquipment, fields);
let today = new Date();
download('Equipment-' + (today.getUTCMonth() + 1) + '-' + (today.getUTCDate()) + '.csv', csv, 'Export needed equipment', 'Export');
}
} |
examples/browserify-gulp-example/src/app/app.js | xmityaz/material-ui | import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Main from './Main'; // Our custom react component
//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(<Main />, document.getElementById('app'));
|
js/src/component/DragAndDrop/Target.js | outeredge/edge-magento-module-menu | import React from 'react';
import { findDOMNode } from 'react-dom';
import ItemActions from './../../data/ItemActions';
import ItemStore from './../../data/ItemStore';
import Item from './../../data/Item';
import { api } from './../../helpers/api';
export const besideTarget = {
canDrop: (props, monitor) => props.item.item_id !== monitor.getItem().item.item_id,
drop(props, monitor, component) {
if (monitor.didDrop()) {
return;
}
const dropDOMNode = findDOMNode(component);
if (monitor.getItem().dragDOMNode.contains(dropDOMNode)) {
return;
}
const item = monitor.getItem().item;
const movedItem = monitor.getItem().item.merge({
parent_id: props.item.parent_id,
sort_order: props.before ? props.item.sort_order : props.item.sort_order + 1
});
const state = ItemStore.getState();
const stateRemovedItem = state.deleteIn(ItemStore.getPath(item));
ItemStore.setPath(movedItem);
const stateAddedItem = stateRemovedItem.setIn(ItemStore.getPath(movedItem), new Item(movedItem));
const stateSorted = stateAddedItem.getIn(ItemStore.getPath(movedItem, true)).map(sibling => {
if (sibling.item_id === movedItem.item_id) {
return sibling;
}
if (props.before) {
if (sibling.sort_order >= movedItem.sort_order) {
return sibling.set('sort_order', sibling.sort_order + 1);
}
} else {
if (sibling.sort_order > movedItem.sort_order) {
return sibling.set('sort_order', sibling.sort_order + 1);
}
}
return sibling;
}).sort(ItemStore.sortItems);
const newTree = stateAddedItem.setIn(ItemStore.getPath(movedItem, true), stateSorted);
ItemActions.updateTree(newTree);
const sortData = [];
stateSorted.forEach(item => {
sortData.push(JSON.stringify(item));
});
api.saveItems(sortData);
}
};
export const itemTarget = {
canDrop: (props, monitor) => props.item.item_id !== monitor.getItem().item.item_id,
drop(props, monitor, component) {
if (monitor.didDrop()) {
return;
}
const dropDOMNode = findDOMNode(component);
if (monitor.getItem().dragDOMNode.contains(dropDOMNode)) {
return;
}
const item = monitor.getItem().item;
const movedItem = monitor.getItem().item.set('parent_id', props.item.item_id);
api.saveItem(movedItem).then(() => {
ItemActions.addItem(movedItem);
ItemActions.deleteItem(item);
});
}
};
export default class Target extends React.Component {
constructor(props) {
super(props);
this.state = {
isOver: false
};
}
componentWillReceiveProps(nextProps) {
if (!this.props.canDrop) {
return;
}
if (!this.props.isOverCurrent && nextProps.isOverCurrent) {
this.setState({ isOver: true });
}
if (this.props.isOverCurrent && !nextProps.isOverCurrent) {
this.setState({ isOver: false });
}
}
}; |
admin/src/page/post-detail.js | grumoon/GruBlog | import React from 'react'
import {browserHistory} from 'react-router'
import {Constants, Utils} from '../lib/common.js'
import $ from 'jquery';
import * as showdown from 'showdown';
import {EditableTagGroup} from '../component/editable-tag-group'
import '../css/post-detail.css'
import {Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, Radio, Tag as AntTag} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
class PostForm extends React.Component {
constructor(props) {
super(props);
var converter = new showdown.Converter();
converter.setFlavor('github');
this.state = {
modifyInitFlag: false,
postId: -1,
action: Constants.post.action.NONE,
categoryList: [],
postData: {},
converter: converter
}
}
componentWillReceiveProps(nextProps) {
this.setState({
categoryList: nextProps.categoryList,
action: nextProps.action,
postId: nextProps.postId,
postData: nextProps.postData
});
}
componentDidUpdate() {
if (this.isPostModify() && this.checkPostData() && !this.state.modifyInitFlag) {
var tags = [];
this.state.postData.rela_tag_posts.map((tagRela) => {
tags.push(tagRela.tag.title);
});
this.props.form.setFieldsValue({
"title": this.state.postData.title,
"summary": this.state.postData.summary,
"content": this.state.postData.content,
"category": this.state.postData.categoryId,
"editableTagGroup": {tags: tags},
"status": this.state.postData.status,
});
this.setState({
modifyInitFlag: true
});
}
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
if (this.state.action == Constants.post.action.ADD) {
this.addPost(values);
}
else if (this.state.action == Constants.post.action.MODIFY) {
this.modifyPost(values);
}
}
});
};
addPost = (values) => {
$.ajax({
method: "POST",
url: Constants.baseCGIUrl + "post/add",
dataType: 'json',
data: {
title: values.title,
summary: values.summary,
content: values.content,
categoryId: values.category,
tags: values.editableTagGroup.tags,
status: values.status
},
success: function (data) {
if (!Utils.checkNeedLogin(data.resCode)) {
if (data.resCode == 0) {
browserHistory.replace("/post");
}
else {
message.info(data.resMsg);
}
}
}.bind(this),
error: function (errorData) {
Utils.dealAjaxError(errorData);
}
});
};
modifyPost = (values) => {
$.ajax({
method: "POST",
url: Constants.baseCGIUrl + "post/modify",
dataType: 'json',
data: {
postId: this.state.postId,
summary: values.summary,
title: values.title,
content: values.content,
categoryId: values.category,
tags: values.editableTagGroup.tags,
status: values.status
},
success: function (data) {
if (!Utils.checkNeedLogin(data.resCode)) {
if (data.resCode == 0) {
browserHistory.replace("/post");
}
else {
message.info(data.resMsg);
}
}
}.bind(this),
error: function (errorData) {
Utils.dealAjaxError(errorData);
}
});
};
checkPostData = () => {
return this.state.postData != undefined && this.state.postData != null && this.state.postData.title != undefined;
};
isPostModify = () => {
return this.state.action == Constants.post.action.MODIFY;
}
getRenderContent = () => {
const {getFieldDecorator} = this.props.form;
const formItemLayout = {
labelCol: {
xs: {span: 24},
sm: {span: 2},
},
wrapperCol: {
xs: {span: 24},
sm: {span: 18},
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 2,
},
},
};
if (this.state.action != Constants.post.action.ADD && this.state.action != Constants.post.action.MODIFY) {
return (
<div>
<div className="post-title">
{this.checkPostData() ? this.state.postData.title : "暂无标题"}
</div>
<div className="post-attr">
<div
className="post-time">{Utils.getCreateTime(this.checkPostData() ? this.state.postData.created : new Date())}</div>
<div className="post-category">
分类:
{this.checkPostData() ? this.state.postData.category.title : "暂无"}
</div>
<div className="post-tag">标签:
{
(this.checkPostData() && this.state.postData.rela_tag_posts.length > 0) ?
this.state.postData.rela_tag_posts.map((tagRela) => {
return (
<AntTag>
{tagRela.tag.title}
</AntTag>
)
})
:
<span>暂无</span>
}
</div>
</div>
<div className="post-summary">
{this.checkPostData() ? this.state.postData.summary : ""}
</div>
<div className="markdown-body"
dangerouslySetInnerHTML={{__html: (this.checkPostData() && this.state.postData.content) ? new showdown.Converter().makeHtml(this.state.postData.content) : "暂无内容"}}>
</div>
</div>
)
}
else {
return (
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="标题"
hasFeedback
>
{getFieldDecorator('title', {
rules: [{
required: true, message: '请输入标题',
}],
})(
<Input/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="摘要"
hasFeedback
>
{getFieldDecorator('summary', {
rules: [{
required: false, message: '请输入摘要',
}],
})(
<Input type="textarea" rows={10}/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="内容"
hasFeedback
>
{getFieldDecorator('content', {
rules: [{
required: true, message: '请输入内容',
}],
})(
<Input type="textarea" rows={30}/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="分类"
>
{getFieldDecorator('category', {
rules: [{
required: true, message: '请选择分类',
}],
})(
<Select style={{width: "200px"}}>
{
this.state.categoryList.map((item) => {
return (<Option value={item.categoryId}>{item.title}</Option>);
})
}
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="标签"
>
{getFieldDecorator('editableTagGroup', {
initialValue: {tags: []},
})(
<EditableTagGroup/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="状态"
>
{getFieldDecorator('status', {
rules: [{
required: true, message: '请选择状态',
}],
})(
<RadioGroup>
<Radio value={0}>草稿</Radio>
<Radio value={1}>发布</Radio>
</RadioGroup>
)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" htmlType="submit" size="large">保存</Button>
</FormItem>
</Form>
)
}
};
render() {
return (
<div>
{this.getRenderContent()}
</div>
)
}
}
const WrappedPostForm = Form.create()(PostForm);
export class PostDetailPage extends React.Component {
constructor(props) {
super(props);
this.state = {
postId: -1,
action: Constants.post.action.NONE,
categoryList: [],
postData: {},
}
}
componentWillMount() {
this.setState({
action: Utils.getParameterByName("action"),
postId: Utils.getParameterByName("id")
});
}
componentDidMount() {
this.initCategory();
}
initCategory = () => {
$.ajax({
method: "POST",
url: Constants.baseCGIUrl + "/category",
dataType: 'json',
success: function (data) {
if (!Utils.checkNeedLogin(data.resCode)) {
if (data.resCode == 0) {
this.setState({categoryList: data.resData});
this.initPost();
}
else {
message.info(data.resMsg);
}
}
}.bind(this),
error: function (errorData) {
Utils.dealAjaxError(errorData);
}
});
};
initPost = () => {
if (this.state.action == Constants.post.action.MODIFY || this.state.action == Constants.post.action.VIEW) {
if (this.state.postId != undefined && this.state.postId != null && this.state.postId.length > 0) {
$.ajax({
method: "POST",
url: Constants.baseCGIUrl + "post/detail",
dataType: 'json',
data: {
postId: this.state.postId
},
success: function (data) {
if (!Utils.checkNeedLogin(data.resCode)) {
if (data.resCode == 0) {
this.setState({
postData: data.resData
});
}
else {
message.info(data.resMsg);
}
}
}.bind(this),
error: function (errorData) {
Utils.dealAjaxError(errorData);
}
});
}
}
};
render() {
return (
<div>
<WrappedPostForm categoryList={this.state.categoryList} action={this.state.action}
postId={this.state.postId} postData={this.state.postData}/>
</div>
)
}
}
|
examples/Overlay.js | HPate-Riptide/react-overlays | import React from 'react';
import { findDOMNode } from 'react-dom';
import Overlay from 'react-overlays/Overlay';
import Button from 'react-bootstrap/lib/Button';
// Styles Mostly from Bootstrap
const TooltipStyle = {
position: 'absolute',
padding: '0 5px'
};
const TooltipInnerStyle = {
padding: '3px 8px',
color: '#fff',
textAlign: 'center',
borderRadius: 3,
backgroundColor: '#000',
opacity: .75
};
const TooltipArrowStyle = {
position: 'absolute',
width: 0, height: 0,
borderRightColor: 'transparent',
borderLeftColor: 'transparent',
borderTopColor: 'transparent',
borderBottomColor: 'transparent',
borderStyle: 'solid',
opacity: .75
};
const PlacementStyles = {
left: {
tooltip: { marginLeft: -3, padding: '0 5px' },
arrow: {
right: 0, marginTop: -5, borderWidth: '5px 0 5px 5px', borderLeftColor: '#000'
}
},
right: {
tooltip: { marginRight: 3, padding: '0 5px' },
arrow: { left: 0, marginTop: -5, borderWidth: '5px 5px 5px 0', borderRightColor: '#000' }
},
top: {
tooltip: { marginTop: -3, padding: '5px 0' },
arrow: { bottom: 0, marginLeft: -5, borderWidth: '5px 5px 0', borderTopColor: '#000' }
},
bottom: {
tooltip: { marginBottom: 3, padding: '5px 0' },
arrow: { top: 0, marginLeft: -5, borderWidth: '0 5px 5px', borderBottomColor: '#000' }
}
};
const ToolTip = props => {
let placementStyle = PlacementStyles[props.placement];
let {
style,
arrowOffsetLeft: left = placementStyle.arrow.left,
arrowOffsetTop: top = placementStyle.arrow.top,
children
} = props;
return (
<div style={{...TooltipStyle, ...placementStyle.tooltip, ...style}}>
<div style={{...TooltipArrowStyle, ...placementStyle.arrow, left, top }}/>
<div style={TooltipInnerStyle}>
{children}
</div>
</div>
);
};
const OverlayExample = React.createClass({
getInitialState(){
return { show: false };
},
toggle(){
let show = this.state.show;
let placements = ['left', 'top', 'right', 'bottom'];
let placement = this.state.placement;
placement = placements[placements.indexOf(placement) + 1];
if (!show) {
show = true;
placement = placements[0];
}
else if (!placement) {
show = false;
}
return this.setState({ show, placement });
},
render(){
return (
<div className='overlay-example'>
<Button bsStyle='primary' ref='target' onClick={this.toggle}>
I am an Overlay target
</Button>
<p>
keep clicking to see the overlay placement change
</p>
<Overlay
show={this.state.show}
onHide={() => this.setState({ show: false })}
placement={this.state.placement}
container={this}
target={ props => findDOMNode(this.refs.target)}
portalClassName="test-portal-class"
>
<ToolTip>
I’m placed to the: <strong>{this.state.placement}</strong>
</ToolTip>
</Overlay>
</div>
);
}
});
export default OverlayExample;
|
src/main/resources/react/src/ssl-report/components/__ReportSheet__/__Certificates__/CertificateChain.js | marthie/SSLReport | /*
The MIT License (MIT)
Copyright (c) 2018 Marius Thiemann <marius dot thiemann at ploin dot de>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import React from 'react';
import PropTypes from "prop-types";
import Certificate from './Certificate';
export default function CertificateChain({version, chain}) {
const certificates = [];
chain.map((certificate)=>{
certificates.push(<Certificate key={certificate.uiKey} version={version} certificate={certificate} />);
});
return (<React.Fragment>{certificates}</React.Fragment>);
}
CertificateChain.propTypes = {
version: PropTypes.string.isRequired,
chain: PropTypes.array.isRequired
};
|
MobileApp/node_modules/react-native-elements/src/rating/Rating.js | VowelWeb/CoinTradePros.com | import times from 'lodash.times';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import {
View,
Animated,
PanResponder,
Image,
StyleSheet,
Platform,
} from 'react-native';
import Text from '../text/Text';
const STAR_IMAGE = require('./images/star.png');
const HEART_IMAGE = require('./images/heart.png');
const ROCKET_IMAGE = require('./images/rocket.png');
const BELL_IMAGE = require('./images/bell.png');
const STAR_WIDTH = 60;
const TYPES = {
star: {
source: STAR_IMAGE,
color: '#f1c40f',
backgroundColor: 'white',
},
heart: {
source: HEART_IMAGE,
color: '#e74c3c',
backgroundColor: 'white',
},
rocket: {
source: ROCKET_IMAGE,
color: '#2ecc71',
backgroundColor: 'white',
},
bell: {
source: BELL_IMAGE,
color: '#f39c12',
backgroundColor: 'white',
},
};
export default class Rating extends Component {
static defaultProps = {
type: 'star',
ratingImage: require('./images/star.png'),
ratingColor: '#f1c40f',
ratingBackgroundColor: 'white',
ratingCount: 5,
imageSize: STAR_WIDTH,
onFinishRating: () => console.log('Attach a function here.'),
};
constructor(props) {
super(props);
const { onFinishRating, fractions } = this.props;
const position = new Animated.ValueXY();
const panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: (event, gesture) => {
const newPosition = new Animated.ValueXY();
newPosition.setValue({ x: gesture.dx, y: 0 });
this.setState({ position: newPosition, value: gesture.dx });
},
onPanResponderRelease: event => {
const rating = this.getCurrentRating();
if (!fractions) {
// "round up" to the nearest star/rocket/whatever
this.setCurrentRating(rating);
}
onFinishRating(rating);
},
});
this.state = { panResponder, position };
}
componentDidMount() {
this.setCurrentRating(this.props.startingValue);
}
getPrimaryViewStyle() {
const { position } = this.state;
const { imageSize, ratingCount, type } = this.props;
const color = TYPES[type].color;
const width = position.x.interpolate(
{
inputRange: [
-ratingCount * (imageSize / 2),
0,
ratingCount * (imageSize / 2),
],
outputRange: [0, ratingCount * imageSize / 2, ratingCount * imageSize],
extrapolate: 'clamp',
},
{ useNativeDriver: true }
);
return {
backgroundColor: color,
width,
height: width ? imageSize : 0,
};
}
getSecondaryViewStyle() {
const { position } = this.state;
const { imageSize, ratingCount, type } = this.props;
const backgroundColor = TYPES[type].backgroundColor;
const width = position.x.interpolate(
{
inputRange: [
-ratingCount * (imageSize / 2),
0,
ratingCount * (imageSize / 2),
],
outputRange: [ratingCount * imageSize, ratingCount * imageSize / 2, 0],
extrapolate: 'clamp',
},
{ useNativeDriver: true }
);
return {
backgroundColor,
width,
height: width ? imageSize : 0,
};
}
renderRatings() {
const { imageSize, ratingCount, type } = this.props;
const source = TYPES[type].source;
return times(ratingCount, index =>
<View key={index} style={styles.starContainer}>
<Image
source={source}
style={{ width: imageSize, height: imageSize }}
/>
</View>
);
}
getCurrentRating() {
const { value } = this.state;
const { fractions, imageSize, ratingCount } = this.props;
const startingValue = ratingCount / 2;
let currentRating = 0;
if (value > ratingCount * imageSize / 2) {
currentRating = ratingCount;
} else if (value < -ratingCount * imageSize / 2) {
currentRating = 0;
} else if (value < imageSize || value > imageSize) {
currentRating = startingValue + value / imageSize;
currentRating = !fractions
? Math.ceil(currentRating)
: +currentRating.toFixed(fractions);
} else {
currentRating = !fractions
? Math.ceil(startingValue)
: +startingValue.toFixed(fractions);
}
return currentRating;
}
setCurrentRating(rating) {
const { imageSize, ratingCount } = this.props;
// `initialRating` corresponds to `startingValue` in the getter. Naming it
// differently here avoids confusion with `value` below.
const initialRating = ratingCount / 2;
let value = null;
if (rating > ratingCount) {
value = ratingCount * imageSize / 2;
} else if (rating < 0) {
value = -ratingCount * imageSize / 2;
} else if (rating < ratingCount / 2 || rating > ratingCount / 2) {
value = (rating - initialRating) * imageSize;
} else {
value = 0;
}
const newPosition = new Animated.ValueXY();
newPosition.setValue({ x: value, y: 0 });
this.setState({ position: newPosition, value });
}
displayCurrentRating() {
const { ratingCount, type, readonly } = this.props;
const color = TYPES[type].color;
return (
<View style={styles.showRatingView}>
<View style={styles.ratingView}>
<Text style={styles.ratingText}>Rating: </Text>
<Text style={[styles.currentRatingText, { color }]}>
{this.getCurrentRating()}
</Text>
<Text style={styles.maxRatingText}>/{ratingCount}</Text>
</View>
<View>
{readonly && <Text style={styles.readonlyLabel}>(readonly)</Text>}
</View>
</View>
);
}
render() {
const {
readonly,
type,
ratingImage,
ratingColor,
ratingBackgroundColor,
style,
showRating,
} = this.props;
if (type === 'custom') {
let custom = {
source: ratingImage,
color: ratingColor,
backgroundColor: ratingBackgroundColor,
};
TYPES.custom = custom;
}
return (
<View pointerEvents={readonly ? 'none' : 'auto'} style={style}>
{showRating && this.displayCurrentRating()}
<View
style={styles.starsWrapper}
{...this.state.panResponder.panHandlers}
>
<View style={styles.starsInsideWrapper}>
<Animated.View style={this.getPrimaryViewStyle()} />
<Animated.View style={this.getSecondaryViewStyle()} />
</View>
{this.renderRatings()}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
starsWrapper: {
flexDirection: 'row',
},
starsInsideWrapper: {
position: 'absolute',
top: 0,
left: 0,
flexDirection: 'row',
},
showRatingView: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
paddingBottom: 5,
},
ratingView: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
paddingBottom: 5,
},
ratingText: {
fontSize: 15,
textAlign: 'center',
fontFamily: Platform.OS === 'ios' ? 'Trebuchet MS' : null,
color: '#34495e',
},
readonlyLabel: {
justifyContent: 'center',
alignItems: 'center',
fontSize: 12,
textAlign: 'center',
fontFamily: Platform.OS === 'ios' ? 'Trebuchet MS' : null,
color: '#34495a',
},
currentRatingText: {
fontSize: 30,
textAlign: 'center',
fontFamily: Platform.OS === 'ios' ? 'Trebuchet MS' : null,
},
maxRatingText: {
fontSize: 18,
textAlign: 'center',
fontFamily: Platform.OS === 'ios' ? 'Trebuchet MS' : null,
color: '#34495e',
},
});
const fractionsType = (props, propName, componentName) => {
if (props[propName]) {
const value = props[propName];
if (typeof value === 'number') {
return value >= 0 && value <= 20
? null
: new Error(
`\`${propName}\` in \`${componentName}\` must be between 0 and 20`
);
}
return new Error(
`\`${propName}\` in \`${componentName}\` must be a number`
);
}
};
Rating.propTypes = {
type: PropTypes.string,
ratingImage: Image.propTypes.source,
ratingColor: PropTypes.string,
ratingBackgroundColor: PropTypes.string,
ratingCount: PropTypes.number,
imageSize: PropTypes.number,
onFinishRating: PropTypes.func,
showRating: PropTypes.bool,
style: View.propTypes.style,
readonly: PropTypes.bool,
startingValue: PropTypes.number,
fractions: fractionsType,
};
|
src/components/Torrent/StatusDetails/Seeding.js | fcsonline/react-transmission | import React from 'react';
import { FormattedMessage } from 'react-intl';
import { formatUL } from 'util/formatters';
export default ({ torrent: { peersGettingFromUs, peersConnected, rateUpload } }) => (
<FormattedMessage
id='torrent.full.seeding'
defaultMessage={`Seeding to {peersGettingFromUs, number} of {peersConnected, number} connected {peersConnected, plural, one{peer} other{peers}} - {formattedRateUpload}`}
values={{
peersGettingFromUs,
peersConnected,
formattedRateUpload: formatUL(rateUpload),
}}
/>
);
|
docs/src/examples/elements/Header/Variations/HeaderExampleInverted.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Header, Segment } from 'semantic-ui-react'
const HeaderExampleInverted = () => (
<Segment inverted>
<Header as='h4' inverted color='red'>
Red
</Header>
<Header as='h4' inverted color='orange'>
Orange
</Header>
<Header as='h4' inverted color='yellow'>
Yellow
</Header>
<Header as='h4' inverted color='olive'>
Olive
</Header>
<Header as='h4' inverted color='green'>
Green
</Header>
<Header as='h4' inverted color='teal'>
Teal
</Header>
<Header as='h4' inverted color='blue'>
Blue
</Header>
<Header as='h4' inverted color='purple'>
Purple
</Header>
<Header as='h4' inverted color='violet'>
Violet
</Header>
<Header as='h4' inverted color='pink'>
Pink
</Header>
<Header as='h4' inverted color='brown'>
Brown
</Header>
<Header as='h4' inverted color='grey'>
Grey
</Header>
</Segment>
)
export default HeaderExampleInverted
|
src/Materijal/components/PostList.js | zeljkoX/e-learning | import React from 'react';
import ReactDOM from'react-dom';
import {Paper} from 'material-ui';
class PostList extends React.Component {
render() {
return (
<div style={{height:'90%'}}>
{this.props.children}
</div>
)}
};
export default PostList;
|
test/do-not-focus-input-on-suggestion-click/AutosuggestApp.js | JacksonKearl/react-autosuggest-ie11-compatible | import React, { Component } from 'react';
import sinon from 'sinon';
import Autosuggest from '../../src/Autosuggest';
import languages from '../plain-list/languages';
import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js';
const getMatchingLanguages = value => {
const escapedValue = escapeRegexCharacters(value.trim());
const regex = new RegExp('^' + escapedValue, 'i');
return languages.filter(language => regex.test(language.name));
};
let app = null;
export const getSuggestionValue = sinon.spy(suggestion => {
return suggestion.name;
});
export const renderSuggestion = sinon.spy(suggestion => {
return <span>{suggestion.name}</span>;
});
export const onChange = sinon.spy((event, { newValue }) => {
app.setState({
value: newValue
});
});
export const onBlur = sinon.spy();
export const onSuggestionsFetchRequested = sinon.spy(({ value }) => {
app.setState({
suggestions: getMatchingLanguages(value)
});
});
export const onSuggestionsClearRequested = sinon.spy(() => {
app.setState({
suggestions: []
});
});
export const onSuggestionSelected = sinon.spy();
export default class AutosuggestApp extends Component {
constructor() {
super();
app = this;
this.state = {
value: '',
suggestions: []
};
}
render() {
const { value, suggestions } = this.state;
const inputProps = {
value,
onChange,
onBlur
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={onSuggestionsFetchRequested}
onSuggestionsClearRequested={onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
onSuggestionSelected={onSuggestionSelected}
focusInputOnSuggestionClick={false}
/>
);
}
}
|
src/components/Projects/TheRunners/TheRunners.js | NathanBWaters/website | import React, { Component } from 'react';
import Helmet from 'react-helmet';
// import ReactMarkdown from 'react-markdown';
// import Markdown2HTML from 'react-markdown-to-html';
export default class TheRunners extends Component {
render() {
const pStyles = require('../Projects.scss');
const rStyles = require('./TheRunners.scss');
const olympus = require('./olympus.png');
const newman = require('./runnerschar.gif');
const storyline = require('./storyline.png');
const research = require('./research.png');
return (
<div>
<Helmet title="TheRunners"/>
<div className={rStyles.landing_wrapper}>
<div className={pStyles.article_info}>
<img src={olympus} className={pStyles.article_image} />
<h1 className={pStyles.article_title}>The Runners</h1>
<p className={pStyles.article_subtitle}>Video Game created in Unity3D</p>
<p className={pStyles.article_subtitle}><b>Role: </b>Director, Game Designer, Technical Artist, Programmer, Modeler, Texturer, Animator</p>
<p className={pStyles.article_subtitle}><b>Tools: </b>Unity3D, C#, Autodesk Maya, Adobe Photoshop</p>
</div>
</div>
<div className={pStyles.article_center}>
<div className={pStyles.article_content}>
<p>The Runners was born out of curiosity on how to build a video game and how to create a world from scratch.</p>
<p>I was blessed to have known some <a href="https://github.com/jkhust">incredibly </a>
<a href="https://github.com/davidmfinol/">smart</a> <a href="https://github.com/thomascardwell7">
and</a> <a href="https://www.youtube.com/channel/UC-B06UJxJ20HYv15lzrm9mA">talented</a> people who were up
for the task as well as some wonderful mentors. Making a video game was challenging,
and in my opinion it was far harder than making a film. What I got out of it was invaluable
learning experience.</p>
<figure>
<img src={newman} alt="Newman 3D Model"/>
<figcaption>Newman - main character of The Runners. Untextured model</figcaption>
</figure>
<p>It was developed over the period of my junior year and ended with the tech lead graduating from UT Austin. </p>
<h2>Beginning the Journey</h2>
<p>The Runners began right before the summer of my junior year. I reached out for advice to <a href="http://gammaprogram.utexas.edu/about/the-team/">Professor Toprac</a>,
head of Game and Mobile Media Applications at the University of Texas at Austin.
He took me under his wing and in return I did <a href="https://drive.google.com/file/d/0B14FG4S3JgjVVnZjQVJIb2FjaU0/view">research</a> with him on
3D video game development. The output was used for future teams developing three-dimensional video games,
starting with the first 3D video game development at UT Austin in Spring 2014. </p>
<figure>
<img src={research} alt="Research" />
<figcaption>Explaining the fundamentals to save future teams time. That way they have more time to make a better game!</figcaption>
</figure>
<h2>Scope</h2>
<p>As a first time product developer I learned some valuable lessons in striving for a vision: it’s important to maintain
a clear long-term vision but you must break down that vision into achievable milestones. We made the rookie mistake of
starting out the race shooting for the moon without focusing on first nailing the core of the gameplay</p>
<figure>
<img src={storyline} alt="WorldBuilding" />
<figcaption>Worldbuilding. We were prepping for making the entire game</figcaption>
</figure>
<p>After some <del>consideration</del> months we realized we probably could not make a 2.5D game on the scale of Grand Theft Auto
with a team of five people (and only 3 developers). So we tied up loose ends for the demo day at the end of
the year and had the following product that I could not be more proud of:</p>
<iframe src="http://www.youtube.com/embed/4rTT_eflPGs?autoplay=0" className={pStyles.header_media}></iframe>
<h2>Conclusions</h2>
<p>I am super grateful for the experience to have worked so tirelessly on a video game. Helped shape my career, introduced me to the power and fun of computer science,
and taught me an immeasurable amount about making art. </p>
<p>I now know the importance of three things:</p>
<ul>
<li>Learning constantly when tackling big projects</li>
<li>Making a minimum viable product that people liked. Then progress.</li>
<li>Whatever the project, understand the entire system. </li>
</ul>
<p><br/></p>
<p><br/></p>
<p><br/></p>
</div>
</div>
</div>
);
}
}
|
blueocean-material-icons/src/js/components/svg-icons/av/fiber-manual-record.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const AvFiberManualRecord = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="8"/>
</SvgIcon>
);
AvFiberManualRecord.displayName = 'AvFiberManualRecord';
AvFiberManualRecord.muiName = 'SvgIcon';
export default AvFiberManualRecord;
|
src/interface/report/FightSelectionPanelList.js | yajinni/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Trans } from '@lingui/macro';
import getFightName from 'common/getFightName';
import getWipeCount from 'common/getWipeCount';
import { formatDuration } from 'common/format';
import makeAnalyzerUrl from 'interface/makeAnalyzerUrl';
import SkullIcon from 'interface/icons/Skull';
import CancelIcon from 'interface/icons/Cancel';
import InformationIcon from 'interface/icons/Information';
import { findByBossId } from 'game/raids';
import ProgressBar from './ProgressBar';
class FightSelectionPanelList extends React.PureComponent {
static propTypes = {
report: PropTypes.shape({
code: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
}),
fights: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
difficulty: PropTypes.number,
boss: PropTypes.number.isRequired,
// use fight interface when converting to TS
// eslint-disable-next-line @typescript-eslint/camelcase
start_time: PropTypes.number.isRequired,
// eslint-disable-next-line @typescript-eslint/camelcase
end_time: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
kill: PropTypes.bool,
})),
killsOnly: PropTypes.bool.isRequired,
playerId: PropTypes.number,
resultTab: PropTypes.string,
};
static groupByFight(fights) {
let last = null;
return fights.reduce((arr, fight) => {
const isDifferent = last === null || last[0].boss !== fight.boss || last[0].difficulty !== fight.difficulty;
if (isDifferent) {
last = [];
arr.push(last);
}
last.push(fight);
return arr;
}, []);
}
render() {
const { fights, report, killsOnly, playerId, resultTab } = this.props;
const filteredFights = fights.filter(fight => {
if (fight.boss === 0) {
// Hide trashfights
return false;
}
if (killsOnly && fight.kill === false) {
return false;
}
return true;
});
return (
<ul className="list">
{this.constructor.groupByFight(filteredFights).map(pulls => {
const firstPull = pulls[0];
const boss = findByBossId(firstPull.boss);
return (
<li key={firstPull.id} className="item">
<div className="flex">
<div className="flex-sub content">
{boss && boss.headshot && (
<img
src={boss.headshot}
className="headshot"
alt=""
/>
)}
</div>
<div className="flex-main">
<h2 style={{ marginTop: 0 }}>
{getFightName(report, firstPull)}
</h2>
<div className="pulls">
{pulls.map(pull => {
const duration = Math.round((pull.end_time - pull.start_time) / 1000);
const Icon = pull.kill ? SkullIcon : CancelIcon;
return (
<Link
key={pull.id}
to={makeAnalyzerUrl(report, pull.id, playerId, resultTab)}
className={`pull ${pull.kill ? 'kill' : 'wipe'}`}
>
<div className="flex">
<div className="flex-main">
<Icon /> {pull.kill ? <Trans id="interface.report.fightSelectionPanelList.kill">Kill</Trans> : <Trans id="interface.report.fightSelectionPanelList.wipe">Wipe {getWipeCount(fights, pull)}</Trans>}
</div>
<div className="flex-sub">
<small>{formatDuration(duration)}</small>{' '}
<ProgressBar
percentage={pull.kill ? 100 : (10000 - pull.fightPercentage) / 100}
width={100}
height={8}
/>
</div>
</div>
</Link>
);
})}
</div>
</div>
</div>
</li>
);
})}
<li className="item clearfix text-muted" style={{ paddingTop: 10, paddingBottom: 10 }}>
<InformationIcon /> <Trans id="interface.report.fightSelectionPanelList.information">You will usually get the most helpful results using raid fights where you're being challenged, such as progress raids.</Trans>
</li>
</ul>
);
}
}
export default FightSelectionPanelList;
|
js/jqwidgets/demos/react/app/slider/rangeslider/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxSlider from '../../../jqwidgets-react/react_jqxslider.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
class App extends React.Component {
componentDidMount() {
this.shop().init(this.refs.priceSlider, this.refs.displaySlider, this.refs.ramSlider, this.refs.hddSlider, this.refs.resetButton);
}
shop() {
let laptops = {
'l-1': { ram: 2, price: 510, display: 15.6, hdd: 320, model: 'Toshiba Satellite C660', marked: false },
'l-2': { ram: 6, price: 594, display: 15.6, hdd: 500, model: 'TOSHIBA Satellite L675', marked: false },
'l-3': { ram: 4, price: 918, display: 14.5, hdd: 500, model: 'HP Envy 14-1190', marked: false },
'l-4': { ram: 4, price: 1165, display: 15.6, hdd: 500, model: 'Dell Vostro 3500', marked: false },
'l-5': { ram: 12, price: 1306, display: 15.6, hdd: 750, model: 'ASUS N73JQ-A2', marked: false },
'l-6': { ram: 8, price: 3732, display: 17, hdd: 1280, model: 'Alienware M17X', marked: false },
'l-7': { ram: 4, price: 800, display: 17, hdd: 500, model: 'Toshiba Satellite P300-21E', marked: false },
'l-8': { ram: 12, price: 3595, display: 18.4, hdd: 1024, model: 'ASUS NX90JQ', visible: false },
'l-9': { ram: 2, price: 631, display: 14.1, hdd: 500, model: 'Packard Bell EasyNote', marked: false },
'l-10': { ram: 2, price: 550, display: 13.3, hdd: 320, model: 'Lenovo ThinkPad Edge', marked: false },
'l-11': { ram: 3, price: 529, display: 15.6, hdd: 320, model: 'Fujitsu Lifebook A531', marked: false },
'l-12': { ram: 8, price: 2401, display: 16.5, hdd: 500, model: 'SONY VAIO F', marked: false }
};
let drawTable = () => {
let catalogue = '<table class="demo-laptop-catalog-table"><tr>', counter = 0;
for (let laptop in laptops) {
if (laptops.hasOwnProperty(laptop)) {
counter += 1;
if (counter % 3 === 1 && counter !== 1) {
catalogue += '</tr><tr>';
}
catalogue += '<td class="demo-laptop-cell jqx-rc-all" id="' + laptop + '">' +
'<div class="demo-laptop-cell-header"><div class="demo-laptop-cell-header-content">' + laptops[laptop].model + '</div></div>' +
'<div class="demo-laptop-cell-content"><img src="../../images/' + laptop + '.jpg" alt="' + laptops[laptop].model + '" title="' + laptops[laptop].model + '" /></div>' +
'<div class="demo-laptop-cell-price jqx-rc-all">$ ' + laptops[laptop].price + '</div>' +
'</td>';
}
}
catalogue += '</tr></table>';
document.getElementById('catalogue').innerHTML = catalogue;
};
let addEventListeners = () => {
let references = this.refs;
for (let slider in references) {
let currentSlider = references[slider];
if (currentSlider.componentSelector.indexOf('jqxSlider') != -1) {
currentSlider.on('change', (event) => {
// Get name of current slider
let filter = slider.slice(0, slider.indexOf('Slider'));
handleSlide(filter, event.args.value);
});
}
}
this.refs.resetButton.on('click', () => {
resetFilters();
});
};
let resetFilters = () => {
this.priceSlider.setValue([this.priceSlider.min(), this.priceSlider.max()]);
this.displaySlider.setValue([this.displaySlider.min(), this.displaySlider.max()]);
this.hddSlider.setValue([this.hddSlider.min(), this.hddSlider.max()]);
this.ramSlider.setValue([this.ramSlider.min(), this.ramSlider.max()]);
};
let handleSlide = (option, value) => {
filterItems(updateFilter(option, value));
setLabelValue(this[option + 'Slider'], option, value);
};
let setLabelValue = (slider, option, value) => {
let label;
switch (option) {
case 'price':
label = 'USD';
break;
case 'hdd':
label = 'GB';
break;
case 'display':
label = 'inches';
break;
case 'ram':
label = 'GB';
break;
}
document.getElementById(option + 'Max').innerHTML = value.rangeEnd + ' ' + label;
document.getElementById(option + 'Min').innerHTML = value.rangeStart + ' ' + label;
};
let filterItems = (filter) => {
let failed = false;
for (let laptop in laptops) {
for (let property in filter) {
if (filter[property].max < laptops[laptop][property] || filter[property].min > laptops[laptop][property]) {
failed = true;
}
}
if (failed) {
if (!laptops[laptop].marked) {
markItem(laptop);
}
} else {
if (laptops[laptop].marked) {
unmarkItem(laptop);
}
}
failed = false;
}
};
//let resetItemFilter = (laptop) => {
// let laptopCells = $('.demo-laptop-cell');
// for (let i = 0; i < laptopCells.length; i += 1) {
// laptopCells[i].css('opacity', 1);
// }
//};
let unmarkItem = (laptop) => {
document.getElementById(laptop).style.opacity = 1;
laptops[laptop].marked = false;
};
let markItem = (laptop) => {
document.getElementById(laptop).style.opacity = 0.5;
laptops[laptop].marked = true;
};
let initSliders = (priceSlider, displaySlider, ramSlider, hddSlider, resetButton) => {
this.priceSlider = priceSlider;
this.displaySlider = displaySlider;
this.ramSlider = ramSlider;
this.hddSlider = hddSlider;
this.resetButton = resetButton;
buildFilter();
};
let buildFilter = () => {
let priceValue = this.priceSlider.value(),
displayValue = this.displaySlider.value(),
ramValue = this.ramSlider.value(),
hddValue = this.hddSlider.value();
this.filter = {
price: {
max: priceValue.rangeEnd,
min: priceValue.rangeStart
},
display: {
max: displayValue.rangeEnd,
min: displayValue.rangeStart
},
hdd: {
max: hddValue.rangeEnd,
min: hddValue.rangeStart
},
ram: {
max: ramValue.rangeEnd,
min: ramValue.rangeStart
}
};
};
let updateFilter = (option, value) => {
this.filter[option].min = value.rangeStart;
this.filter[option].max = value.rangeEnd;
return this.filter;
};
return {
init: (priceSlider, displaySlider, ramSlider, hddSlider, resetButton) => {
drawTable();
initSliders(priceSlider, displaySlider, ramSlider, hddSlider, resetButton);
addEventListeners();
setLabelValue(priceSlider, 'price', priceSlider.value());
setLabelValue(displaySlider, 'display', displaySlider.value());
setLabelValue(ramSlider, 'ram', ramSlider.value());
setLabelValue(hddSlider, 'hdd', hddSlider.value());
}
};
}
render() {
return (
<div id='jqxWidget'>
<div id='main-container' className='main-container jqx-rc-all'>
<div style={{ float: 'left' }}>
<div id='catalogue' className='catalogue jqx-rc-all'>
</div>
</div>
<div id='options' className='options jqx-rc-all'>
<div id='options-container' className='options-container'>
<div className='label'>
Price</div>
<div className='options-value'>
<div style={{ float: 'left' }} id='priceMin'>
</div>
<div style={{ float: 'right' }} id='priceMax'>
</div>
</div>
<br />
<JqxSlider ref='priceSlider'
showButtons={true}
height={30} width={180}
min={500} max={4000}
step={350} ticksFrequency={350}
rangeSlider={true} mode={'fixed'}
value={[500, 4000]}
/>
<div className='label'>
Screen Size</div>
<div className='options-value'>
<div style={{ float: 'left' }} id='displayMin'>
</div>
<div style={{ float: 'right' }} id='displayMax'>
</div>
</div>
<br />
<JqxSlider ref='displaySlider'
height={30} width={180}
min={9} max={19}
step={1} ticksFrequency={1}
rangeSlider={true} mode={'fixed'}
value={[9, 19]}
/>
<div className='label'>
RAM</div>
<div className='options-value'>
<div style={{ float: 'left' }} id='ramMin'>
</div>
<div style={{ float: 'right' }} id='ramMax'>
</div>
</div>
<br />
<JqxSlider ref='ramSlider'
height={30} width={180}
min={2} max={12}
step={1} ticksFrequency={1}
rangeSlider={true} mode={'fixed'}
value={[2, 12]}
/>
<div className='label'>
HDD</div>
<div className='options-value'>
<div style={{ float: 'left' }} id='hddMin'>
</div>
<div style={{ float: 'right' }} id='hddMax'>
</div>
</div>
<br />
<JqxSlider ref='hddSlider'
height={30} width={180}
min={150} max={1500}
step={135} ticksFrequency={135}
rangeSlider={true} mode={'fixed'}
value={[150, 1500]}
/>
<JqxButton ref='resetButton' value='Reset filters' width={100} className='resetButton' />
</div>
</div>
<div style={{ clear: 'both' }}>
</div>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/places/golf-course.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesGolfCourse = (props) => (
<SvgIcon {...props}>
<circle cx="19.5" cy="19.5" r="1.5"/><path d="M17 5.92L9 2v18H7v-1.73c-1.79.35-3 .99-3 1.73 0 1.1 2.69 2 6 2s6-.9 6-2c0-.99-2.16-1.81-5-1.97V8.98l6-3.06z"/>
</SvgIcon>
);
PlacesGolfCourse = pure(PlacesGolfCourse);
PlacesGolfCourse.displayName = 'PlacesGolfCourse';
PlacesGolfCourse.muiName = 'SvgIcon';
export default PlacesGolfCourse;
|
app/components/pipeline/teams/Index/chooser.js | buildkite/frontend | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import shallowCompare from 'react-addons-shallow-compare';
import AutocompleteDialog from 'app/components/shared/Autocomplete/Dialog';
import Button from 'app/components/shared/Button';
import FlashesStore from 'app/stores/FlashesStore';
import TeamSuggestion from './team-suggestion';
import TeamPipelineCreateMutation from 'app/mutations/TeamPipelineCreate';
class Chooser extends React.Component {
static displayName = "PipelineTeamIndex.Chooser";
static propTypes = {
pipeline: PropTypes.shape({
id: PropTypes.string.isRequired,
slug: PropTypes.string.isRequired,
organization: PropTypes.shape({
teams: PropTypes.shape({
edges: PropTypes.array.isRequired
})
})
}).isRequired,
relay: PropTypes.object.isRequired,
onChoose: PropTypes.func.isRequired
};
state = {
loading: false,
searching: false,
removing: null,
showingDialog: false
};
shouldComponentUpdate(nextProps, nextState) {
// Only update when a forceFetch isn't pending, and we also meet the usual
// requirements to update. This avoids any re-use of old cached Team data.
return !nextState.searching && shallowCompare(this, nextProps, nextState);
}
render() {
return (
<div>
<Button
onClick={this.handleDialogOpen}
>
Add to Team
</Button>
<AutocompleteDialog
isOpen={this.state.showingDialog}
onRequestClose={this.handleDialogClose}
width={400}
onSearch={this.handleTeamSearch}
onSelect={this.handleTeamSelect}
items={this.renderAutoCompleteSuggstions(this.props.relay.variables.teamAddSearch)}
placeholder="Search all teams…"
selectLabel="Add"
popover={false}
/>
</div>
);
}
renderAutoCompleteSuggstions(teamAddSearch) {
const organizationTeams = this.props.pipeline.organization.teams;
if (!organizationTeams || this.state.loading) {
return [<AutocompleteDialog.Loader key="loading" />];
}
// Filter team edges by permission to add them
const relevantTeamEdges = organizationTeams.edges.filter(({ node }) => (
node.permissions.teamPipelineCreate.allowed
));
// Either render the suggestions, or show a "not found" error
if (relevantTeamEdges.length > 0) {
return relevantTeamEdges.map(({ node }) => {
return [<TeamSuggestion key={node.id} team={node} />, node];
});
} else if (teamAddSearch !== "") {
return [
<AutocompleteDialog.ErrorMessage key="error">
Could not find a team with name <em>{teamAddSearch}</em>
</AutocompleteDialog.ErrorMessage>
];
}
return [
<AutocompleteDialog.ErrorMessage key="error">
Could not find any more teams to add
</AutocompleteDialog.ErrorMessage>
];
}
handleDialogOpen = () => {
// First switch the component into a "loading" mode and refresh the data in the chooser
this.setState({ loading: true });
this.props.relay.forceFetch({ includeSearchResults: true, pipelineSelector: `!${this.props.pipeline.slug}` }, (state) => {
if (state.done) {
this.setState({ loading: false });
}
});
// Now start showing the dialog
this.setState({ showingDialog: true });
};
handleDialogClose = () => {
this.setState({ showingDialog: false });
this.props.relay.setVariables({ teamAddSearch: '' });
};
handleTeamSearch = (teamAddSearch) => {
this.setState({ searching: true });
this.props.relay.forceFetch(
{ teamAddSearch },
(state) => {
if (state.done) {
this.setState({ searching: false });
}
}
);
};
handleTeamSelect = (team) => {
this.setState({ showingDialog: false });
this.props.relay.setVariables({ teamAddSearch: '' });
const mutation = new TeamPipelineCreateMutation({
team: team,
pipeline: this.props.pipeline
});
Relay.Store.commitUpdate(mutation, {
onFailure: this.handleMutationFailure,
onSuccess: this.handleMutationSuccess
});
};
handleMutationSuccess = () => {
this.props.onChoose();
};
handleMutationFailure = (transaction) => {
FlashesStore.flash(FlashesStore.ERROR, transaction.getError());
};
}
export default Relay.createContainer(Chooser, {
initialVariables: {
isMounted: false,
includeSearchResults: false,
teamAddSearch: '',
pipelineSelector: null
},
fragments: {
pipeline: () => Relay.QL`
fragment on Pipeline {
${TeamPipelineCreateMutation.getFragment('pipeline')}
id
slug
organization {
teams(search: $teamAddSearch, first: 10, order: RELEVANCE, pipeline: $pipelineSelector) @include (if: $includeSearchResults) {
edges {
node {
id
permissions {
teamPipelineCreate {
allowed
}
}
${TeamSuggestion.getFragment('team')}
${TeamPipelineCreateMutation.getFragment('team')}
}
}
}
}
}
`
}
});
|
src/collections/Table/TableHeaderCell.js | aabustamante/Semantic-UI-React | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
customPropTypes,
getUnhandledProps,
META,
useValueAndKey,
} from '../../lib'
import TableCell from './TableCell'
/**
* A table can have a header cell.
*/
function TableHeaderCell(props) {
const { as, className, sorted } = props
const classes = cx(
useValueAndKey(sorted, 'sorted'),
className
)
const rest = getUnhandledProps(TableHeaderCell, props)
return <TableCell {...rest} as={as} className={classes} />
}
TableHeaderCell._meta = {
name: 'TableHeaderCell',
type: META.TYPES.COLLECTION,
parent: 'Table',
}
TableHeaderCell.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Additional classes. */
className: PropTypes.string,
/** A header cell can be sorted in ascending or descending order. */
sorted: PropTypes.oneOf(['ascending', 'descending']),
}
TableHeaderCell.defaultProps = {
as: 'th',
}
export default TableHeaderCell
|
src/routes.js | Padelas649/moralgram | 'use strict';
import React from 'react'
import { Route, IndexRoute } from 'react-router'
import Layout from './components/Layout';
import IndexPage from './components/IndexPage';
import AboutPage from './components/AboutPage';
import NotFoundPage from './components/NotFoundPage';
const routes = (
<Route path="/" component={Layout}>
<IndexRoute component={IndexPage}/>
<Route path="about" component={AboutPage}/>
<Route path="*" component={NotFoundPage}/>
</Route>
);
export default routes; |
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | ea-zhongxiaochun/angularStudy | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
src/scripts/pages/Login.page.story.js | kodokojo/kodokojo-ui | /**
* Kodo Kojo - Software factory done right
* Copyright © 2017 Kodo Kojo ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import { Provider } from 'react-redux'
import { IntlProvider } from 'react-intl'
import { storiesOf, linkTo } from '@kadira/storybook'
// contexte
import configureStore from '../store/configureStore'
import en from '../i18n/en'
// component to story
import App from '../components/app/App.component'
import LoginPage from './Login.page'
const initialState = {
auth: {
account: {},
captcha: {
value: '',
reset: false
},
isAuthenticated: false,
isFetching: false
}
}
const initialStore = configureStore(initialState)
storiesOf('LoginPage', module)
.add('default', () => (
<Provider store={initialStore}>
<IntlProvider locale="en" messages={ en }>
<App>
<LoginPage />
</App>
</IntlProvider>
</Provider>
)) |
src/js/shared/components/media.js | akornatskyy/sample-blog-react | import React from 'react';
import PropTypes from 'prop-types';
const Media = ({src, heading, children}) => (
<div className="mt-2 d-flex">
<div className="flex-shrink-0">
<img className="me-3" src={src} />
</div>
<div>
<h5 className="mt-0">{heading}</h5>
{children}
</div>
</div>
);
Media.propTypes = {
src: PropTypes.string.isRequired,
heading: PropTypes.node.isRequired,
children: PropTypes.node.isRequired
};
export default Media;
|
node_modules/semantic-ui-react/dist/es/views/Statistic/Statistic.js | SuperUncleCat/ServerMonitoring | import _extends from 'babel-runtime/helpers/extends';
import _without from 'lodash/without';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { childrenUtils, customPropTypes, getElementType, getUnhandledProps, META, SUI, useKeyOnly, useValueAndKey } from '../../lib';
import StatisticGroup from './StatisticGroup';
import StatisticLabel from './StatisticLabel';
import StatisticValue from './StatisticValue';
/**
* A statistic emphasizes the current value of an attribute.
*/
function Statistic(props) {
var children = props.children,
className = props.className,
color = props.color,
floated = props.floated,
horizontal = props.horizontal,
inverted = props.inverted,
label = props.label,
size = props.size,
text = props.text,
value = props.value;
var classes = cx('ui', color, size, useValueAndKey(floated, 'floated'), useKeyOnly(horizontal, 'horizontal'), useKeyOnly(inverted, 'inverted'), 'statistic', className);
var rest = getUnhandledProps(Statistic, props);
var ElementType = getElementType(Statistic, props);
if (!childrenUtils.isNil(children)) return React.createElement(
ElementType,
_extends({}, rest, { className: classes }),
children
);
return React.createElement(
ElementType,
_extends({}, rest, { className: classes }),
React.createElement(StatisticValue, { text: text, value: value }),
React.createElement(StatisticLabel, { label: label })
);
}
Statistic.handledProps = ['as', 'children', 'className', 'color', 'floated', 'horizontal', 'inverted', 'label', 'size', 'text', 'value'];
Statistic._meta = {
name: 'Statistic',
type: META.TYPES.VIEW
};
Statistic.propTypes = process.env.NODE_ENV !== "production" ? {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** A statistic can be formatted to be different colors. */
color: PropTypes.oneOf(SUI.COLORS),
/** A statistic can sit to the left or right of other content. */
floated: PropTypes.oneOf(SUI.FLOATS),
/** A statistic can present its measurement horizontally. */
horizontal: PropTypes.bool,
/** A statistic can be formatted to fit on a dark background. */
inverted: PropTypes.bool,
/** Label content of the Statistic. */
label: customPropTypes.contentShorthand,
/** A statistic can vary in size. */
size: PropTypes.oneOf(_without(SUI.SIZES, 'big', 'massive', 'medium')),
/** Format the StatisticValue with smaller font size to fit nicely beside number values. */
text: PropTypes.bool,
/** Value content of the Statistic. */
value: customPropTypes.contentShorthand
} : {};
Statistic.Group = StatisticGroup;
Statistic.Label = StatisticLabel;
Statistic.Value = StatisticValue;
export default Statistic; |
packages/wix-style-react/src/MarketingLayout/components/Content.js | wix/wix-style-react | import React from 'react';
import PropTypes from 'prop-types';
import Description from './Description';
import Title from './Title';
import { SIZES } from '../constants';
import { APPEARANCES } from '../../Heading';
import { SIZES as TEXT_SIZES } from '../../Text';
import { classes } from '../MarketingLayout.st.css';
const titleAppearanceBySize = {
[SIZES.tiny]: SIZES.tiny,
[SIZES.small]: APPEARANCES.H3,
[SIZES.medium]: APPEARANCES.H2,
[SIZES.large]: APPEARANCES.H2,
};
const descriptionSizeBySize = {
[SIZES.tiny]: TEXT_SIZES.small,
[SIZES.small]: TEXT_SIZES.small,
[SIZES.medium]: TEXT_SIZES.medium,
[SIZES.large]: TEXT_SIZES.medium,
};
const Content = ({ size, actions, title, description }) => (
<div className={classes.contentContainer}>
<div>
<Title appearance={titleAppearanceBySize[size]}>{title}</Title>
<Description size={descriptionSizeBySize[size]}>
{description}
</Description>
</div>
{actions}
</div>
);
Content.propTypes = {
size: PropTypes.string,
actions: PropTypes.node,
title: PropTypes.node,
description: PropTypes.node,
};
export default Content;
|
dist/lib/carbon-fields/assets/js/fields/components/association/list-item.js | ArtFever911/statrer-kit | /**
* The external dependencies.
*/
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { withHandlers } from 'recompose';
/**
* The internal dependencies.
*/
import { preventDefault } from 'lib/helpers';
/**
* Render an item that can be associated.
*
* @param {Object} props
* @param {String} props.prefix
* @param {Number} props.index
* @param {Object[]} props.item
* @param {Boolean} props.associated
* @param {Boolean} props.visible
* @param {Function} props.handleClick
* @return {React.Element}
*
* TODO: Clean up the mess in `handleClick` introduced by the incorrect HTML in the template.
*/
export const AssociationListItem = ({
prefix,
index,
item,
associated,
visible,
handleClick
}) => {
return <li id={item.id} className={cx({ 'inactive': item.disabled })}>
<span className="mobile-handle dashicons-before dashicons-menu"></span>
<a href="#" onClick={handleClick}>
{
item.edit_link && !associated
? <em className="edit-link dashicons-before dashicons-edit"></em>
: null
}
<em>{item.label}</em>
<span className="dashicons-before dashicons-plus-alt"></span>
{item.title}
{
item.is_trashed
? <i className="trashed dashicons-before dashicons-trash"></i>
: null
}
</a>
{
associated
? <input
type="hidden"
name={`${prefix}[${index}]`}
value={`${item.type}:${item.subtype}:${item.id}`}
disabled={!visible}
readOnly={true} />
: null
}
</li>;
};
/**
* Validate the props.
*
* @type {Object}
*
* TODO: Fix the type of the `id` attribute to be consistent.
*/
AssociationListItem.propTypes = {
prefix: PropTypes.string,
index: PropTypes.number,
item: PropTypes.shape({
id: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
label: PropTypes.string,
title: PropTypes.string,
type: PropTypes.string,
subtype: PropTypes.string,
edit_link: PropTypes.string,
}),
associated: PropTypes.bool,
visible: PropTypes.bool,
handleClick: PropTypes.func,
};
const enhance = withHandlers({
handleClick: ({ item, associated, onClick }) => preventDefault((e) => {
const { target } = e;
if (target.nodeName === 'SPAN') {
onClick(item);
} if (target.classList.contains('edit-link')) {
e.stopPropagation();
window.open(item.edit_link.replace('&', '&', 'g'), '_blank');
} else {
if (!associated && !item.disabled) {
onClick(item);
}
}
}),
});
export default enhance(AssociationListItem);
|
src/components/TodoTextInput.js | taggon/redux-example-todo | import React, { Component } from 'react';
class TodoTextInput extends Component {
constructor(props, context) {
super(props, context);
this.state = {
text: this.props.text || ''
};
}
handleChange(event) {
this.setState( {text: event.target.value} );
}
handleKeyUp(event) {
if (event.which === 13) {
this.props.onSave(event.target.value.trim());
this.setState( {text: ''} );
}
return true;
}
render() {
return (
<input
type="text"
placeholder={this.props.placeholder}
autoFocus="true"
value={this.state.text}
onChange={this.handleChange.bind(this)}
onKeyUp={this.handleKeyUp.bind(this)} />
);
}
}
export default TodoTextInput;
|
src/js/App.js | nirrattner/KnitPix | import React, { Component } from 'react';
import { Col, Grid, Row } from 'react-bootstrap';
import debounce from 'javascript-debounce';
import Sidebar from './container/Sidebar';
import OriginalImage from './container/OriginalImage';
import ModifiedImage from './container/ModifiedImage';
import * as DimensionCalculator from './library/DimensionCalculator';
import * as ImageProcessor from './library/ImageProcessor';
import * as ImageReader from './library/ImageReader';
import * as ImageSerializer from './library/ImageSerializer';
import '../css/app.css'
class App extends Component {
constructor(props) {
super(props);
this.debounceUpdateImage = debounce(this.updateImage, 350);
this.state = {
colorQuantity: '',
hasGaugeAdjustments: false,
isHeightLastModified: false,
gaugeHigh: '',
gaugeWide: '',
gridColor: '#000000',
modifiedImageSource: null,
originalImage: null,
originalImageSource: null,
stitchesHigh: '',
stitchesWide: '',
};
}
onColorQuantityChange({ target: { value } }) {
const colorQuantity = parseInt(value, 10);
if (colorQuantity) {
this.setState({ colorQuantity });
} else if (!value) {
this.setState({ colorQuantity: '' });
}
this.debounceUpdateImage();
}
onGaugeHighChange({ target: { value } }) {
const { hasGaugeAdjustments, gaugeWide } = this.state;
const gaugeHigh = parseInt(value, 10);
if (gaugeHigh) {
this.setState({ gaugeHigh });
this.updateStitches({ hasGaugeAdjustments, gaugeHigh, gaugeWide });
} else if (!value) {
this.setState({ gaugeHigh: '' });
}
}
onGaugeWideChange({ target: { value } }) {
const { hasGaugeAdjustments, gaugeHigh } = this.state;
const gaugeWide = parseInt(value, 10);
if (gaugeWide) {
this.setState({ gaugeWide });
this.updateStitches({ hasGaugeAdjustments, gaugeHigh, gaugeWide });
} else if (!value) {
this.setState({ gaugeWide: '' });
}
}
onHasGaugeAdjustmentChange() {
const { hasGaugeAdjustments } = this.state;
this.setState({
gaugeHigh: '',
gaugeWide: '',
hasGaugeAdjustments: !hasGaugeAdjustments
});
this.updateStitches({ hasGaugeAdjustments: !hasGaugeAdjustments });
}
updateStitches({ gaugeHigh, gaugeWide, hasGaugeAdjustments }) {
const { isHeightLastModified, originalImage, stitchesHigh, stitchesWide } = this.state;
if (isHeightLastModified && stitchesHigh) {
this.setState(DimensionCalculator.byHeight(stitchesHigh, originalImage, hasGaugeAdjustments, gaugeHigh, gaugeWide));
this.debounceUpdateImage();
} else if (stitchesWide) {
this.setState(DimensionCalculator.byWidth(stitchesWide, originalImage, hasGaugeAdjustments, gaugeHigh, gaugeWide));
this.debounceUpdateImage();
}
}
onFileChange({ target: { files } }) {
const file = files[0];
ImageReader.readImage(file)
.then(ImageProcessor.opaque)
.then(image => {
this.setState({originalImage: image});
return image;
})
.then(ImageSerializer.toSource)
.then(imageSource => {
this.setState({
originalImageSource: imageSource,
gaugeHigh: '',
gaugeWide: '',
hasGaugeAdjustments: false,
gridColor: '#000000',
stitchesHigh: '',
stitchesWide: '',
modifiedImageSource: null,
});
});
}
onGridColorChange({ target: { value: gridColor } }) {
this.setState({ gridColor });
this.debounceUpdateImage();
}
onStitchesHighChange({ target: { value } }) {
this.onStitchesChange(value, DimensionCalculator.byHeight);
}
onStitchesWideChange({ target: { value } }) {
this.onStitchesChange(value, DimensionCalculator.byWidth);
}
onStitchesChange(value, getDimensions) {
const intValue = parseInt(value, 10);
if (intValue) {
const { originalImage, hasGaugeAdjustments, gaugeHigh, gaugeWide } = this.state;
const { isHeightLastModified, stitchesHigh, stitchesWide } = getDimensions(intValue, originalImage, hasGaugeAdjustments, gaugeHigh, gaugeWide);
this.setState({
isHeightLastModified,
stitchesHigh,
stitchesWide,
});
this.debounceUpdateImage();
} else {
this.setState({
gridColor: '#000000',
stitchesHigh: '',
stitchesWide: '',
modifiedImageSource: null,
});
}
}
updateImage() {
const {
colorQuantity,
hasGaugeAdjustments,
gaugeHigh,
gaugeWide,
gridColor,
originalImage,
stitchesHigh,
stitchesWide,
} = this.state;
if (originalImage && stitchesHigh && stitchesWide) {
ImageProcessor.update(originalImage, colorQuantity, gridColor, stitchesHigh, stitchesWide, hasGaugeAdjustments, gaugeHigh, gaugeWide)
.then(imageSource => this.setState({ modifiedImageSource: imageSource }));
}
}
render() {
const { originalImageSource, modifiedImageSource } = this.state;
return (
<div className="app">
<header>
<h1>KnitPix</h1>
</header>
<Grid>
<Row className="show-grid">
<Col xs={6} md={4}>
<Sidebar
{...this.state}
onColorQuantityChange={this.onColorQuantityChange.bind(this)}
onGaugeHighChange={this.onGaugeHighChange.bind(this)}
onGaugeWideChange={this.onGaugeWideChange.bind(this)}
onFileChange={this.onFileChange.bind(this)}
onHasGaugeAdjustmentChange={this.onHasGaugeAdjustmentChange.bind(this)}
onGridColorChange={this.onGridColorChange.bind(this)}
onStitchesHighChange={this.onStitchesHighChange.bind(this)}
onStitchesWideChange={this.onStitchesWideChange.bind(this)}
/>
</Col>
<Col xs={6} md={4}>
<OriginalImage src={originalImageSource} />
</Col>
<Col xs={6} md={4}>
<ModifiedImage src={modifiedImageSource} />
</Col>
</Row>
</Grid>
</div>
);
}
}
export default App;
|
MusicPlayer/index.ios.js | hkhungit/react-native-sound-management | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class MusicPlayer extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('MusicPlayer', () => MusicPlayer);
|
src/pages/Games/components/Pagination.js | iGameLab/teleport-client | import React from 'react'
import { Link } from 'react-router'
export default class Pagination extends React.Component{
render() {
return (
<div className="row text-center">
<div className="col-lg-12">
<ul className="pagination">
<li>
<Link to={'/'}>«</Link>
</li>
<li className="active">
<Link to={'/'}>1</Link>
</li>
<li>
<Link to={'/'}>2</Link>
</li>
<li>
<Link to={'/'}>3</Link>
</li>
<li>
<Link to={'/'}>4</Link>
</li>
<li>
<Link to={'/'}>5</Link>
</li>
<li>
<Link to={'/'}>»</Link>
</li>
</ul>
</div>
</div>
)
}
} |
examples/src/components/RemoteSelectField.js | alanrsoares/react-select | import React from 'react';
import Select from 'react-select';
var RemoteSelectField = React.createClass({
displayName: 'RemoteSelectField',
propTypes: {
hint: React.PropTypes.string,
label: React.PropTypes.string,
},
loadOptions (input, callback) {
input = input.toLowerCase();
var rtn = {
options: [
{ label: 'One', value: 'one' },
{ label: 'Two', value: 'two' },
{ label: 'Three', value: 'three' }
],
complete: true
};
if (input.slice(0, 1) === 'a') {
if (input.slice(0, 2) === 'ab') {
rtn = {
options: [
{ label: 'AB', value: 'ab' },
{ label: 'ABC', value: 'abc' },
{ label: 'ABCD', value: 'abcd' }
],
complete: true
};
} else {
rtn = {
options: [
{ label: 'A', value: 'a' },
{ label: 'AA', value: 'aa' },
{ label: 'AB', value: 'ab' }
],
complete: false
};
}
} else if (!input.length) {
rtn.complete = false;
}
setTimeout(function() {
callback(null, rtn);
}, 500);
},
renderHint () {
if (!this.props.hint) return null;
return (
<div className="hint">{this.props.hint}</div>
);
},
render () {
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select asyncOptions={this.loadOptions} className="remote-example" />
{this.renderHint()}
</div>
);
}
});
module.exports = RemoteSelectField;
|
src/about/index.js | BelwoodBakeryCafe/belwoodbakerycafe | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import s from './styles.css';
import { title, html } from './index.md';
class AboutPage extends React.Component {
componentDidMount() {
document.title = title;
}
render() {
return (
<Layout className={s.content}>
<h1>{title}</h1>
<div
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: html }}
/>
</Layout>
);
}
}
export default AboutPage;
|
src/Focus.js | prometheusresearch/react-ui | /**
* @copyright 2016-present, Prometheus Research, LLC
* @flow
*/
import React from 'react';
import findHTMLElement from './findHTMLElement';
import {debounce} from './Utils';
export let contextTypes = {
focusable: React.PropTypes.object,
};
type FocusableProps = {
children: React.Element<*>,
inputRef: (HTMLElement) => *,
focusIndex: number,
};
export class Focusable extends React.Component<*, FocusableProps, *> {
_ref: ?HTMLElement;
_inputRef: ?HTMLElement;
static contextTypes = contextTypes;
constructor(props: FocusableProps) {
super(props);
this._ref = null;
this._inputRef = null;
}
get input(): ?HTMLElement {
return findHTMLElement(this._inputRef || this._ref || this);
}
get isFocused(): boolean {
return this.input === document.activeElement;
}
render() {
return React.cloneElement(React.Children.only(this.props.children), {
ref: this.onRef,
inputRef: this.onInputRef,
});
}
onInputRef = (_inputRef: HTMLElement) => {
this._inputRef = _inputRef;
if (this.props.inputRef) {
this.props.inputRef(_inputRef);
}
};
onRef = (_ref: HTMLElement) => {
this._ref = _ref;
};
componentDidMount() {
if (this.props.focusIndex != null) {
this.context.focusable.register(this, this.props.focusIndex);
}
}
componentWillUnmount() {
if (this.props.focusIndex != null) {
this.context.focusable.unregister(this, this.props.focusIndex);
}
}
componentWillReceiveProps(nextProps: FocusableProps) {
if (this.props.focusIndex !== nextProps.focusIndex) {
if (this.props.focusIndex != null) {
this.context.focusable.unregister(this, this.props.focusIndex);
}
if (nextProps.focusIndex != null) {
this.context.focusable.register(this, nextProps.focusIndex);
}
}
}
focus() {
if (this.input) {
this.input.focus();
}
}
}
type FocusableListProps = {
tabIndex: number,
children: any,
activeDescendant: string,
};
export class FocusableList extends React.Component<*, FocusableListProps, *> {
items: {
[name: string]: Focusable,
};
state: {
focused: false,
};
static childContextTypes = contextTypes;
constructor(props: FocusableListProps) {
super(props);
this.items = {};
this.state = {focused: false};
}
toggleFocused = debounce(
focused =>
this.setState(state => {
if (state.focused !== focused) {
state = {...state, focused};
}
return state;
}),
0,
);
getChildContext() {
return {
focusable: this,
};
}
render() {
let {tabIndex, children} = this.props;
let {focused} = this.state;
if (focused) {
tabIndex = -1;
}
return React.cloneElement(React.Children.only(children), {
tabIndex,
onKeyDown: this.onKeyDown,
onFocus: this.onFocus,
onBlur: this.onBlur,
});
}
getFocusedIndex() {
let keys = this.getKeys();
let focused = keys.findIndex(key => this.items[key].isFocused);
if (focused === undefined) {
focused = -1;
}
return parseInt(focused, 10);
}
getKeys() {
let keys = Object.keys(this.items);
keys.sort();
return keys;
}
register = (focusable: Focusable, focusIndex: string) => {
this.items[focusIndex] = focusable;
};
unregister = (focusable: Focusable, focusIndex: string) => {
// We check if focusable wasn't overridden earlier due to another child's
// update
if (this.items[focusIndex] === focusable) {
delete this.items[focusIndex];
}
};
focusPrev = () => {
let fromIndex = this.getFocusedIndex();
let keys = this.getKeys();
let nextKey;
if (fromIndex === -1) {
nextKey = keys[keys.length - 1];
} else if (fromIndex === 0) {
nextKey = keys[keys.length - 1];
} else {
nextKey = keys[fromIndex - 1];
}
if (this.items[nextKey] !== undefined) {
this.items[nextKey].focus();
return true;
} else {
return false;
}
};
focusNext = () => {
let fromIndex = this.getFocusedIndex();
let keys = this.getKeys();
let nextKey;
if (fromIndex === -1) {
nextKey = keys[0];
} else if (fromIndex === keys.length - 1) {
nextKey = keys[0];
} else {
nextKey = keys[fromIndex + 1];
}
if (this.items[nextKey] !== undefined) {
this.items[nextKey].focus();
return true;
} else {
return false;
}
};
onKeyDown = (event: KeyboardEvent) => {
switch (event.key) {
case 'ArrowUp':
case 'ArrowLeft':
if (this.focusPrev()) {
event.preventDefault();
}
break;
case 'ArrowDown':
case 'ArrowRight':
if (this.focusNext()) {
event.preventDefault();
}
break;
}
if (this.props.children.props.onKeyDown) {
this.props.children.props.onKeyDown(event);
}
};
onBlur = (event: UIEvent) => {
this.toggleFocused(false);
if (this.props.children.props.onBlur) {
this.props.children.props.onBlur(event);
}
};
onFocus = (event: UIEvent) => {
let focusedIndex = this.getFocusedIndex();
this.toggleFocused(true);
if (focusedIndex === -1) {
let activeDescendant = this.props.activeDescendant;
if (activeDescendant && this.items[activeDescendant]) {
this.items[activeDescendant].focus();
} else {
let keys = this.getKeys();
activeDescendant = keys[0];
if (activeDescendant && this.items[activeDescendant]) {
this.items[activeDescendant].focus();
}
}
}
if (this.props.children.props.onFocus) {
this.props.children.props.onFocus(event);
}
};
}
|
src/components/Grid/GridFlex.js | lebra/lebra-components | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
const propsTypes = {
direction: PropTypes.oneOf(['row','row-reverse','column','column-reverse']),
wrap: PropTypes.oneOf(['nowrap','wrap','wrap-reverse']),
justify: PropTypes.oneOf(['start','end','center','between','around']),
align: PropTypes.oneOf(['start','center','end','baseline','stretch']),
children: PropTypes.node,
disabled: PropTypes.bool,
style: PropTypes.object,
alignContent: PropTypes.oneOf(['start','end','center','between','around','stretch']),
onClick:PropTypes.func,
prefixCls: PropTypes.string,
className: PropTypes.string,
role: PropTypes.string,
}
const defaultProps = {
prefixCls: 'lebra-flexbox',
align: 'center',
}
export default class GridFlex extends React.Component{
constructor(props){
super(props);
this.Item;
}
render() {
let {
direction, wrap, justify, align, alignContent, className, children, prefixCls, style, ...restProps,
} = this.props;
const wrapCls = classnames(prefixCls, className, {
[`${prefixCls}-dir-row`]: direction === 'row',
[`${prefixCls}-dir-row-reverse`]: direction === 'row-reverse',
[`${prefixCls}-dir-column`]: direction === 'column',
[`${prefixCls}-dir-column-reverse`]: direction === 'column-reverse',
[`${prefixCls}-nowrap`]: wrap === 'nowrap',
[`${prefixCls}-wrap`]: wrap === 'wrap',
[`${prefixCls}-wrap-reverse`]: wrap === 'wrap-reverse',
[`${prefixCls}-justify-start`]: justify === 'start',
[`${prefixCls}-justify-end`]: justify === 'end',
[`${prefixCls}-justify-center`]: justify === 'center',
[`${prefixCls}-justify-between`]: justify === 'between',
[`${prefixCls}-justify-around`]: justify === 'around',
[`${prefixCls}-align-start`]: align === 'start',
[`${prefixCls}-align-center`]: align === 'center',
[`${prefixCls}-align-end`]: align === 'end',
[`${prefixCls}-align-baseline`]: align === 'baseline',
[`${prefixCls}-align-stretch`]: align === 'stretch',
[`${prefixCls}-align-content-start`]: alignContent === 'start',
[`${prefixCls}-align-content-end`]: alignContent === 'end',
[`${prefixCls}-align-content-center`]: alignContent === 'center',
[`${prefixCls}-align-content-between`]: alignContent === 'between',
[`${prefixCls}-align-content-around`]: alignContent === 'around',
[`${prefixCls}-align-content-stretch`]: alignContent === 'stretch',
});
return (
<div className={wrapCls} style={style} {...restProps}>
{children}
</div>
);
}
}
GridFlex.propsTypes = propsTypes;
GridFlex.defaultProps = defaultProps;
|
src/Grid.js | Lucifier129/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import elementType from 'react-prop-types/lib/elementType';
const Grid = React.createClass({
propTypes: {
/**
* Turn any fixed-width grid layout into a full-width layout by this property.
*
* Adds `container-fluid` class.
*/
fluid: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
componentClass: elementType
},
getDefaultProps() {
return {
componentClass: 'div',
fluid: false
};
},
render() {
let ComponentClass = this.props.componentClass;
let className = this.props.fluid ? 'container-fluid' : 'container';
return (
<ComponentClass
{...this.props}
className={classNames(this.props.className, className)}>
{this.props.children}
</ComponentClass>
);
}
});
export default Grid;
|
public/js/components/visits/othersvisits.react.js | IsuruDilhan/Coupley | import React from 'react';
import Avatar from 'material-ui/lib/avatar';
import Card from 'material-ui/lib/card/card';
import CardActions from 'material-ui/lib/card/card-actions';
import CardHeader from 'material-ui/lib/card/card-header';
import CardMedia from 'material-ui/lib/card/card-media';
import CardTitle from 'material-ui/lib/card/card-title';
import FlatButton from 'material-ui/lib/flat-button';
import CardText from 'material-ui/lib/card/card-text';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import TextField from 'material-ui/lib/text-field';
import Divider from 'material-ui/lib/divider';
import IconButton from 'material-ui/lib/icon-button';
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';
import Colors from 'material-ui/lib/styles/colors';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import MenuItem from 'material-ui/lib/menus/menu-item';
import Tabs from 'material-ui/lib/tabs/tabs';
import Tab from 'material-ui/lib/tabs/tab';
import Dialog from 'material-ui/lib/dialog';
import ThreadActions from '../../actions/Thread/ThreadActions';
import VisitsActions from '../../actions/VisitsAction';
const iconButtonElement = (
<IconButton
touch={true}
tooltip="more"
tooltipPosition="bottom-left"
>
<MoreVertIcon color={Colors.grey400} />
</IconButton>
);
const rightIconMenu = (
<IconMenu iconButtonElement={iconButtonElement}>
<MenuItem>Block</MenuItem>
</IconMenu>
);
const othervisits = React.createClass({
handleOpen: function () {
this.setState({ open: true });
},
handleClose: function () {
this.setState({ open: false });
},
deletemyfollow:function () {
console.log('follower deleted!');
},
getInitialState: function () {
return {
open: false,
};
},
blockUser: function () {
ThreadActions.block(this.props.username, localStorage.getItem('username'));
VisitsActions.deleteUserFromOthervisit(this.props.username, localStorage.getItem('username'));
this.setState({ open: false });
},
render:function(){
const actions = [
<FlatButton
label="No"
secondary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Yes"
primary={true}
keyboardFocused={true}
onTouchTap={this.blockUser}
/>,
];
return(
<div>
<ListItem
primaryText={this.props.fistname}
leftAvatar={<Avatar src={'img/profilepics/'+this.props.username} />}
rightIconButton={ <IconMenu iconButtonElement={iconButtonElement}>
<MenuItem onTouchTap={this.handleOpen}>Block</MenuItem>
</IconMenu>}
/>
<Divider/>
<Dialog
title="Block your Followeres"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
Are you sure you want to Block this user?.
</Dialog>
</div>
);
}
});
export default othervisits;
|
app/javascript/mastodon/features/compose/components/text_icon_button.js | esetomo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class TextIconButton extends React.PureComponent {
static propTypes = {
label: PropTypes.string.isRequired,
title: PropTypes.string,
active: PropTypes.bool,
onClick: PropTypes.func.isRequired,
ariaControls: PropTypes.string,
};
handleClick = (e) => {
e.preventDefault();
this.props.onClick();
}
render () {
const { label, title, active, ariaControls } = this.props;
return (
<button title={title} aria-label={title} className={`text-icon-button ${active ? 'active' : ''}`} aria-expanded={active} onClick={this.handleClick} aria-controls={ariaControls}>
{label}
</button>
);
}
}
|
packages/yam-vr/components/Login/index.vr.js | unindented/little-yam | import React from 'react'
import {
View,
asset
} from 'react-vr'
import Button from '../Button'
export default class Login extends React.PureComponent {
static propTypes = {
login: React.PropTypes.func
}
render () {
const {login} = this.props
return (
<View
style={{
layoutOrigin: [0.5, 0.5],
position: 'absolute',
transform: [
{translateZ: -2}
]
}}
>
<Button
source={asset('lock.png')}
onClick={login}
/>
</View>
)
}
}
|
src/components/Post/CommentInput.js | thinq4yourself/simply-social-in | import React from 'react';
import api from '../../services/api';
import { connect } from 'react-redux';
import { ADD_COMMENT } from '../../constants/actionTypes';
import { Button, Form } from 'semantic-ui-react'
const mapDispatchToProps = dispatch => ({
onSubmit: payload =>
dispatch({ type: ADD_COMMENT, payload })
});
class CommentInput extends React.Component {
constructor() {
super();
this.state = {
body: ''
};
this.setBody = ev => {
this.setState({ body: ev.target.value });
};
this.createComment = ev => {
ev.preventDefault();
const payload = api.Comments.create(this.props.slug,
{ body: this.state.body });
this.setState({ body: '' });
this.props.onSubmit(payload);
};
}
render() {
return (
<Form onSubmit={this.createComment}>
<Form.TextArea
placeholder='Write your comment...'
value={this.state.body}
onChange={this.setBody}
rows='3'
/>
<Button content='Add Comment' labelPosition='left' icon='edit' color='teal' />
</Form>
);
}
}
export default connect(() => ({}), mapDispatchToProps)(CommentInput);
|
app/app.js | cbradley3/CharlieBradleyIII | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
// Import root app
import App from 'containers/App';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
/* eslint-enable import/no-unresolved, import/extensions */
// Import CSS reset and Global Styles
import './global-styles';
// Import root routes
import createRoutes from './routes';
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(),
};
const render = () => {
ReactDOM.render(
<div>
<Router history={browserHistory} routes={rootRoute} render={applyRouterMiddleware(useScroll())}/>
</div>,
document.getElementById('app')
);
};
render();
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
src/Button.js | BespokeInsights/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
import ButtonInput from './ButtonInput';
const Button = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
block: React.PropTypes.bool,
navItem: React.PropTypes.bool,
navDropdown: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType,
href: React.PropTypes.string,
target: React.PropTypes.string,
/**
* Defines HTML button type Attribute
* @type {("button"|"reset"|"submit")}
* @defaultValue 'button'
*/
type: React.PropTypes.oneOf(ButtonInput.types)
},
getDefaultProps() {
return {
active: false,
block: false,
bsClass: 'button',
bsStyle: 'default',
disabled: false,
navItem: false,
navDropdown: false
};
},
render() {
let classes = this.props.navDropdown ? {} : this.getBsClassSet();
let renderFuncName;
classes = {
active: this.props.active,
'btn-block': this.props.block,
...classes
};
if (this.props.navItem) {
return this.renderNavItem(classes);
}
renderFuncName = this.props.href || this.props.target || this.props.navDropdown ?
'renderAnchor' : 'renderButton';
return this[renderFuncName](classes);
},
renderAnchor(classes) {
let Component = this.props.componentClass || 'a';
let href = this.props.href || '#';
classes.disabled = this.props.disabled;
return (
<Component
{...this.props}
href={href}
className={classNames(this.props.className, classes)}
role="button">
{this.props.children}
</Component>
);
},
renderButton(classes) {
let Component = this.props.componentClass || 'button';
return (
<Component
{...this.props}
type={this.props.type || 'button'}
className={classNames(this.props.className, classes)}>
{this.props.children}
</Component>
);
},
renderNavItem(classes) {
let liClasses = {
active: this.props.active
};
return (
<li className={classNames(liClasses)}>
{this.renderAnchor(classes)}
</li>
);
}
});
export default Button;
|
src/components/bylocation.js | rlaakkol/hsl-stopscreen | import React from 'react'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import DepartureList from './departurelist'
const DeparturesByLocation = props => (
<DepartureList loading={props.data.loading} stops={props.data.stopsByBbox} />
)
DeparturesByLocation.propTypes = {
data: React.PropTypes.object
}
const LocationQuery = gql`
query LocationQuery($minLat: Float!, $maxLat: Float!, $minLon: Float!, $maxLon: Float!, $time: Long!, $nstoptimes: Int!){
stopsByBbox(minLat: $minLat,
maxLat: $maxLat,
minLon: $minLon,
maxLon: $maxLon,
agency: "HSL") {
gtfsId
name
lat
lon
stoptimesForPatterns(
startTime: $time,
numberOfDepartures: $nstoptimes) {
pattern {
name
route {
shortName
desc
agency {
gtfsId
name
}
}
}
stoptimes {
realtime
realtimeDeparture
scheduledDeparture
serviceDay
stop {
name
}
}
}
}
}
`
export default graphql(LocationQuery)(DeparturesByLocation)
|
src/admin/pages/Widgets/BoxItemAvailable.js | rendact/rendact | import React from 'react';
import {DragSource} from 'react-dnd';
import AddToWidgetAreaForm from './AddToWidgetAreaForm';
const dragSource = {
beginDrag(props, monitor, component){
return {widget: props.widget}
},
}
const dragCollect = (connect, monitor) => ({
connectDragToDom: connect.dragSource(),
isDragging: monitor.isDragging()
});
class BoxItemAvailable extends React.Component {
render(){
var widget = this.props.widget;
var widgetValue = JSON.parse(widget.value);
var {connectDragToDom, isDragging, widgetAreas} = this.props;
let opacity = isDragging? 0.5 : 1;
return connectDragToDom(
<div className="box box-default collapsed-box box-solid" style={{opacity, cursor: 'move'}} id={widget.item}>
<div className="box-header with-border">
<h3 className="box-title">{widgetValue.title}</h3>
<div className="box-tools pull-right">
<button type="button" className="btn btn-box-tool" disabled={this.props.selectedMenuName===""} data-widget="collapse"><i className="fa fa-plus"></i>
</button>
</div>
</div>
<div className="box-body">
<p>{widgetValue.help}</p>
</div>
<div className="box-footer text-center">
<AddToWidgetAreaForm widget={widget} widgetAreas={widgetAreas} />
</div>
</div>
)
}
}
BoxItemAvailable = DragSource('available', dragSource, dragCollect)(BoxItemAvailable);
export default BoxItemAvailable;
|
_templates/Header.js | williaumwu/mern-sample | import React from 'react';
import { Parallax } from 'react-parallax';
import styles from './Header.css';
import bgImage from '../../assets/writer.jpg';
import fbStyles from '../../../../styles/flexboxgrid.css';
const Header = () => (
<Parallax bgImage={bgImage} strength={400} >
<div style={{ position: 'relative', top: '150px', height: '482px' }}>
<div className={`${fbStyles['container-fluid']}`}>
<div className={`${fbStyles.row}`}>
<div className={styles['header-copy']}>
<h1>Magic Blog</h1>
<h2>__search_and_replace_here</h2>
</div>
</div>
</div>
</div>
</Parallax>
);
export default Header;
|
src/App.js | sparty02/react-toolbox-demo | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import theme from './toolbox/theme';
import './toolbox/theme.css';
import ThemeProvider from 'react-toolbox/lib/ThemeProvider'
import DropdownDemo from './DropdownDemo';
class App extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<div style={{ width: '300px', padding: '30px' }}>
<DropdownDemo />
</div>
</div>
</ThemeProvider>
);
}
}
export default App;
|
src/svg-icons/maps/tram.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsTram = (props) => (
<SvgIcon {...props}>
<path d="M19 16.94V8.5c0-2.79-2.61-3.4-6.01-3.49l.76-1.51H17V2H7v1.5h4.75l-.76 1.52C7.86 5.11 5 5.73 5 8.5v8.44c0 1.45 1.19 2.66 2.59 2.97L6 21.5v.5h2.23l2-2H14l2 2h2v-.5L16.5 20h-.08c1.69 0 2.58-1.37 2.58-3.06zm-7 1.56c-.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.5zm5-4.5H7V9h10v5z"/>
</SvgIcon>
);
MapsTram = pure(MapsTram);
MapsTram.displayName = 'MapsTram';
MapsTram.muiName = 'SvgIcon';
export default MapsTram;
|
src/App.js | jcampbellg/league-admin-app | import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import Navigation from './Components/Navigation';
import Header from './Components/Header';
import Share from './Components/Share';
import Dashboard from './Components/Dashboard';
import NotFound from './Components/NotFound';
class App extends Component {
logThis(data) {
console.log(data);
};
render() {
return (
<div className="App">
<Navigation />
<Route exact path="/" component={Header}></Route>
<Route exact path="/" component={Dashboard}></Route>
<Route path="/share/:token" component={Share}></Route>
</div>
);
}
}
export default App;
|
docs/app/Examples/collections/Message/Variations/MessageErrorExample.js | jcarbo/stardust | import React from 'react'
import { Message } from 'stardust'
const MessageErrorExample = () => (
<Message
error
header='There was some errors with your submission'
list={[
'You must include both a upper and lower case letters in your password.',
'You need to select your home country.',
]}
/>
)
export default MessageErrorExample
|
test/unit/client/wrapper-test.js | travi-org/admin.travi.org | /* eslint no-underscore-dangle: ["error", { "allow": ["__BOOM__"] }] */
import {parse} from 'url';
import React from 'react';
import {browserHistory} from 'react-router';
import ga from 'react-ga';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import sinon from 'sinon';
import any from '@travi/any';
import dom from '../../helpers/dom';
import * as routes from '../../../src/shared/routes';
import Wrapper from '../../../src/client/wrapper';
suite('wrapper for hot reloading', () => {
let sandbox;
const store = any.simpleObject();
const routeConfig = <div />;
const url = any.url();
const statusCode = any.integer();
setup(() => {
sandbox = sinon.createSandbox();
sandbox.stub(routes, 'getRoutes');
sandbox.stub(ga, 'pageview');
dom.reconfigure({url});
});
teardown(() => {
sandbox.restore();
window.__BOOM__ = null;
});
test('that the router is remounted', () => {
routes.getRoutes.returns(routeConfig);
const wrapper = shallow(<Wrapper store={store} />);
const root = wrapper.find('Root');
const router = root.find('Router');
assert.equal(root.prop('store'), store);
assert.equal(router.prop('history'), browserHistory);
assert.equal(router.prop('children'), routeConfig);
assert.notCalled(ga.pageview);
router.prop('onUpdate')();
assert.calledOnce(ga.pageview);
assert.calledWith(ga.pageview, parse(url).pathname);
});
test('that the error page is mounted when response was a Boom', () => {
window.__BOOM__ = {...any.simpleObject(), statusCode};
const wrapper = shallow(<Wrapper store={store} />);
const errorPage = wrapper.find('ErrorPage');
assert.equal(errorPage.prop('statusCode'), statusCode);
});
});
|
Youtuber-JS/src/components/video_list.js | victorditadi/IQApp | import React from 'react';
import VideoListItem from './video_list_item';
const VideoLista = (props) => {
const videos = props.videos;
const videoItems = videos.map((video) => {
return <VideoListItem onVideoSelect={props.onVideoSelect} key={video.etag} video={video} />
});
return(
<div className="row">
<div className="col s12 m12 l12">
<ul>
{videoItems}
</ul>
</div>
</div>
);
}
export default VideoLista;
|
app/screen/TweetList.js | shuiszhang/fanfou | /**
* Created by shuis on 2017/6/7.
*/
import React, { Component } from 'react';
import {
View,
FlatList,
} from 'react-native';
import {TweetSeparator} from '../component/base';
import Tweet from '../component/Tweet';
import {favorites, user_timeline} from '../api/api';
class TweetList extends Component{
static navigationOptions = ({ navigation }) => ({
headerTitle: navigation.state.params.title,
});
constructor(props){
super(props);
if (this.props.navigation.state.params.title === '我的消息') {
this.fetch = user_timeline;
} else if (this.props.navigation.state.params.title === '我的收藏') {
this.fetch = favorites;
} else {
this.fetch = null;
}
this.state = {
data: [],
};
}
componentDidMount(){
this._fetchData();
}
_fetchData = async () => {
try {
let res = await this.fetch();
console.log(res);
this.setState({
data: res,
});
} catch (e) {
}
};
_renderItem = ({item}) => {
return <Tweet item={item} navigation={this.props.navigation}/>;
};
_renderSeparator = () => {
return <TweetSeparator/>
};
_keyExtractor = (item, index) => index;
render(){
return (
<View>
<FlatList
data = {this.state.data}
renderItem = {this._renderItem}
initialNumToRender = {6}
keyExtractor={this._keyExtractor}
ItemSeparatorComponent={this._renderSeparator}
/>
</View>
)
}
}
export default TweetList; |
Libraries/Text/Text.js | disparu86/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Text
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const React = require('React');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheetPropType = require('StyleSheetPropType');
const TextStylePropTypes = require('TextStylePropTypes');
const Touchable = require('Touchable');
const processColor = require('processColor');
const createReactNativeComponentClass = require('createReactNativeComponentClass');
const mergeFast = require('mergeFast');
const { PropTypes } = React;
const stylePropType = StyleSheetPropType(TextStylePropTypes);
const viewConfig = {
validAttributes: mergeFast(ReactNativeViewAttributes.UIView, {
isHighlighted: true,
numberOfLines: true,
ellipsizeMode: true,
allowFontScaling: false,
selectable: true,
selectionColor: true,
adjustsFontSizeToFit: true,
minimumFontScale: true,
textBreakStrategy: true,
}),
uiViewClassName: 'RCTText',
};
/**
* A React component for displaying text.
*
* `Text` supports nesting, styling, and touch handling.
*
* In the following example, the nested title and body text will inherit the `fontFamily` from
*`styles.baseText`, but the title provides its own additional styles. The title and body will
* stack on top of each other on account of the literal newlines:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, Text, StyleSheet } from 'react-native';
*
* class TextInANest extends Component {
* constructor(props) {
* super(props);
* this.state = {
* titleText: "Bird's Nest",
* bodyText: 'This is not really a bird nest.'
* };
* }
*
* render() {
* return (
* <Text style={styles.baseText}>
* <Text style={styles.titleText} onPress={this.onPressTitle}>
* {this.state.titleText}{'\n'}{'\n'}
* </Text>
* <Text numberOfLines={5}>
* {this.state.bodyText}
* </Text>
* </Text>
* );
* }
* }
*
* const styles = StyleSheet.create({
* baseText: {
* fontFamily: 'Cochin',
* },
* titleText: {
* fontSize: 20,
* fontWeight: 'bold',
* },
* });
*
* // App registration and rendering
* AppRegistry.registerComponent('TextInANest', () => TextInANest);
* ```
*/
const Text = React.createClass({
propTypes: {
/**
* This can be one of the following values:
*
* - `head` - The line is displayed so that the end fits in the container and the missing text
* at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz"
* - `middle` - The line is displayed so that the beginning and end fit in the container and the
* missing text in the middle is indicated by an ellipsis glyph. "ab...yz"
* - `tail` - The line is displayed so that the beginning fits in the container and the
* missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..."
* - `clip` - Lines are not drawn past the edge of the text container.
*
* The default is `tail`.
*
* `numberOfLines` must be set in conjunction with this prop.
*
* > `clip` is working only for iOS
*/
ellipsizeMode: PropTypes.oneOf(['head', 'middle', 'tail', 'clip']),
/**
* Used to truncate the text with an ellipsis after computing the text
* layout, including line wrapping, such that the total number of lines
* does not exceed this number.
*
* This prop is commonly used with `ellipsizeMode`.
*/
numberOfLines: PropTypes.number,
/**
* Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced`
* The default value is `highQuality`.
* @platform android
*/
textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']),
/**
* Invoked on mount and layout changes with
*
* `{nativeEvent: {layout: {x, y, width, height}}}`
*/
onLayout: PropTypes.func,
/**
* This function is called on press.
*
* e.g., `onPress={() => console.log('1st')}``
*/
onPress: PropTypes.func,
/**
* This function is called on long press.
*
* e.g., `onLongPress={this.increaseSize}>``
*/
onLongPress: PropTypes.func,
/**
* When the scroll view is disabled, this defines how far your touch may
* move off of the button, before deactivating the button. Once deactivated,
* try moving it back and you'll see that the button is once again
* reactivated! Move it back and forth several times while the scroll view
* is disabled. Ensure you pass in a constant to reduce memory allocations.
*/
pressRetentionOffset: EdgeInsetsPropType,
/**
* Lets the user select text, to use the native copy and paste functionality.
*/
selectable: PropTypes.bool,
/**
* The highlight color of the text.
* @platform android
*/
selectionColor: ColorPropType,
/**
* When `true`, no visual change is made when text is pressed down. By
* default, a gray oval highlights the text on press down.
* @platform ios
*/
suppressHighlighting: PropTypes.bool,
style: stylePropType,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
/**
* Specifies whether fonts should scale to respect Text Size accessibility settings. The
* default is `true`.
*/
allowFontScaling: PropTypes.bool,
/**
* When set to `true`, indicates that the view is an accessibility element. The default value
* for a `Text` element is `true`.
*
* See the
* [Accessibility guide](docs/accessibility.html#accessible-ios-android)
* for more information.
*/
accessible: PropTypes.bool,
/**
* Specifies whether font should be scaled down automatically to fit given style constraints.
* @platform ios
*/
adjustsFontSizeToFit: PropTypes.bool,
/**
* Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0).
* @platform ios
*/
minimumFontScale: PropTypes.number,
},
getDefaultProps(): Object {
return {
accessible: true,
allowFontScaling: false,
ellipsizeMode: 'tail',
};
},
getInitialState: function(): Object {
return mergeFast(Touchable.Mixin.touchableGetInitialState(), {
isHighlighted: false,
});
},
mixins: [NativeMethodsMixin],
viewConfig: viewConfig,
getChildContext(): Object {
return {isInAParentText: true};
},
childContextTypes: {
isInAParentText: PropTypes.bool
},
contextTypes: {
isInAParentText: PropTypes.bool
},
/**
* Only assigned if touch is needed.
*/
_handlers: (null: ?Object),
_hasPressHandler(): boolean {
return !!this.props.onPress || !!this.props.onLongPress;
},
/**
* These are assigned lazily the first time the responder is set to make plain
* text nodes as cheap as possible.
*/
touchableHandleActivePressIn: (null: ?Function),
touchableHandleActivePressOut: (null: ?Function),
touchableHandlePress: (null: ?Function),
touchableHandleLongPress: (null: ?Function),
touchableGetPressRectOffset: (null: ?Function),
render(): React.Element<any> {
let newProps = this.props;
if (this.props.onStartShouldSetResponder || this._hasPressHandler()) {
if (!this._handlers) {
this._handlers = {
onStartShouldSetResponder: (): bool => {
const shouldSetFromProps = this.props.onStartShouldSetResponder &&
this.props.onStartShouldSetResponder();
const setResponder = shouldSetFromProps || this._hasPressHandler();
if (setResponder && !this.touchableHandleActivePressIn) {
// Attach and bind all the other handlers only the first time a touch
// actually happens.
for (const key in Touchable.Mixin) {
if (typeof Touchable.Mixin[key] === 'function') {
(this: any)[key] = Touchable.Mixin[key].bind(this);
}
}
this.touchableHandleActivePressIn = () => {
if (this.props.suppressHighlighting || !this._hasPressHandler()) {
return;
}
this.setState({
isHighlighted: true,
});
};
this.touchableHandleActivePressOut = () => {
if (this.props.suppressHighlighting || !this._hasPressHandler()) {
return;
}
this.setState({
isHighlighted: false,
});
};
this.touchableHandlePress = (e: SyntheticEvent) => {
this.props.onPress && this.props.onPress(e);
};
this.touchableHandleLongPress = (e: SyntheticEvent) => {
this.props.onLongPress && this.props.onLongPress(e);
};
this.touchableGetPressRectOffset = function(): RectOffset {
return this.props.pressRetentionOffset || PRESS_RECT_OFFSET;
};
}
return setResponder;
},
onResponderGrant: function(e: SyntheticEvent, dispatchID: string) {
this.touchableHandleResponderGrant(e, dispatchID);
this.props.onResponderGrant &&
this.props.onResponderGrant.apply(this, arguments);
}.bind(this),
onResponderMove: function(e: SyntheticEvent) {
this.touchableHandleResponderMove(e);
this.props.onResponderMove &&
this.props.onResponderMove.apply(this, arguments);
}.bind(this),
onResponderRelease: function(e: SyntheticEvent) {
this.touchableHandleResponderRelease(e);
this.props.onResponderRelease &&
this.props.onResponderRelease.apply(this, arguments);
}.bind(this),
onResponderTerminate: function(e: SyntheticEvent) {
this.touchableHandleResponderTerminate(e);
this.props.onResponderTerminate &&
this.props.onResponderTerminate.apply(this, arguments);
}.bind(this),
onResponderTerminationRequest: function(): bool {
// Allow touchable or props.onResponderTerminationRequest to deny
// the request
var allowTermination = this.touchableHandleResponderTerminationRequest();
if (allowTermination && this.props.onResponderTerminationRequest) {
allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments);
}
return allowTermination;
}.bind(this),
};
}
newProps = {
...this.props,
...this._handlers,
isHighlighted: this.state.isHighlighted,
};
}
if (newProps.selectionColor != null) {
newProps = {
...newProps,
selectionColor: processColor(newProps.selectionColor)
};
}
if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) {
newProps = {
...newProps,
style: [this.props.style, {color: 'magenta'}],
};
}
if (this.context.isInAParentText) {
return <RCTVirtualText {...newProps} />;
} else {
return <RCTText {...newProps} />;
}
},
});
type RectOffset = {
top: number,
left: number,
right: number,
bottom: number,
}
var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
var RCTText = createReactNativeComponentClass(viewConfig);
var RCTVirtualText = RCTText;
if (Platform.OS === 'android') {
RCTVirtualText = createReactNativeComponentClass({
validAttributes: mergeFast(ReactNativeViewAttributes.UIView, {
isHighlighted: true,
}),
uiViewClassName: 'RCTVirtualText',
});
}
module.exports = Text;
|
src/CarouselItem.js | brentertz/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import TransitionEvents from './utils/TransitionEvents';
const CarouselItem = React.createClass({
propTypes: {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
caption: React.PropTypes.node,
index: React.PropTypes.number
},
getInitialState() {
return {
direction: null
};
},
getDefaultProps() {
return {
animation: true
};
},
handleAnimateOutEnd() {
if (this.props.onAnimateOutEnd && this.isMounted()) {
this.props.onAnimateOutEnd(this.props.index);
}
},
componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({
direction: null
});
}
},
componentDidUpdate(prevProps) {
if (!this.props.active && prevProps.active) {
TransitionEvents.addEndEventListener(
React.findDOMNode(this),
this.handleAnimateOutEnd
);
}
if (this.props.active !== prevProps.active) {
setTimeout(this.startAnimation, 20);
}
},
startAnimation() {
if (!this.isMounted()) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ?
'right' : 'left'
});
},
render() {
let classes = {
item: true,
active: (this.props.active && !this.props.animateIn) || this.props.animateOut,
next: this.props.active && this.props.animateIn && this.props.direction === 'next',
prev: this.props.active && this.props.animateIn && this.props.direction === 'prev'
};
if (this.state.direction && (this.props.animateIn || this.props.animateOut)) {
classes[this.state.direction] = true;
}
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
{this.props.caption ? this.renderCaption() : null}
</div>
);
},
renderCaption() {
return (
<div className="carousel-caption">
{this.props.caption}
</div>
);
}
});
export default CarouselItem;
|
src/components/SecondaryButton/SecondaryButton.js | joshblack/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Button from '../Button';
const SecondaryButton = props => <Button kind="secondary" {...props} />;
export default SecondaryButton;
|
app/web/containers/Main.web.js | Nakan4u/pokemons-finder | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router-dom';
import { ActionCreators } from '../../actions';
import MainPage from '../../containers/Main';
import { responsiveStyles } from '../../native/containers/Main.css.js';
require('./Main.css');
class MainPageWeb extends MainPage {
handleChange (event) {
this.setState({
pokemonName: event.nativeEvent.target.value,
error: false
});
}
render () {
var showErr = this.state.error ? <p className="error">{this.state.error} </p> : <p></p>;
return (
<div className="mainContainer">
<h1 className="title">Welcome to Pokemons finder web app!</h1>
<form className="mainForm" name="main">
<label className="instructions" htmlFor="pokemonName">Type pokemon name or id to find them: </label>
<input id="pokemonName" className="searchInput" name="pokemonName" type="text"
value={this.state.pokemonName} onChange={this.handleChange.bind(this)} />
<button className="button" onClick={super.handleSubmit.bind(this)} disabled={!this.state.pokemonName}>
<span className="buttonText">Search</span>
</button>
<button className="button" onClick={super.getList.bind(this)}>
<span className="buttonText">Get pokemon list</span>
</button>
</form>
<span>{this.state.isLoading ? 'loading...' : ''}</span>
{showErr}
</div>
);
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
function mapStateToProps (state) {
return {
currentPokemonName: state.currentPokemonName
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(MainPageWeb));
// export default withRouter(MainPageWeb);
|
src/examples/5/RandomGif.js | low-ghost/react-rx-elm-architecture | import React from 'react';
import R from 'ramda';
import fetch from 'isomorphic-fetch';
import { dispatch, forwardTo, createReducer, Effects } from './startApp';
//init : String -> (Model, Effects Action)
export let init = topic => () => [{
gifUrl: 'assets/waiting.gif',
topic,
}, getRandomGif(topic)];
//getRandomGif : String -> Effects Action
export function getRandomGif(topic) {
const encodedTopic = encodeURIComponent(topic);
return Rx.Observable.fromPromise(
fetch(`http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=${encodedTopic}`)
.then(decodeUrl)
.then(R.merge({ type: NEW_GIF })));
};
//minor difference as json is a promise
//decodeUrl : String -> Effects Action
function decodeUrl(response) {
if (response.status >= 400) {
throw new Error("Hmm, that's not great");
}
return response.json()
.then(R.compose(R.objOf('result'), R.path(['data', 'image_url'])));
}
//type Action = RequestMore | NewGif
const REQUEST_MORE = 'REQUEST_MORE';
const NEW_GIF = 'NEW_GIF';
//update : Action -> Model -> (Model, Effects Action)
export const update = createReducer({
[REQUEST_MORE](action, model) {
return [ model, getRandomGif(model.topic) ];
},
[NEW_GIF](action, model) {
return [{
...model,
gifUrl: action.result
}, Effects.none];
},
});
//view : Signal.Address Action -> Model -> Html
export function View({ address$, model }) {
const imgStyle = {
width: 200,
height: 200,
display: "inline-block",
backgroundPosition: "center center",
backgroundSize: "cover",
backgroundImage: `url("${model.gifUrl}")`,
};
const headerStyle = {
width: 200,
textAlign: "center",
};
return (
<div style={{ width: 200 }}>
<h2 style={headerStyle}>{model.topic}</h2>
<img style={imgStyle} />
<button onClick={dispatch(address$, REQUEST_MORE)}>More Please</button>
</div>
);
}
|
node_modules/react-bootstrap/es/Accordion.js | yeshdev1/Everydays-project | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PanelGroup from './PanelGroup';
var Accordion = function (_React$Component) {
_inherits(Accordion, _React$Component);
function Accordion() {
_classCallCheck(this, Accordion);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Accordion.prototype.render = function render() {
return React.createElement(
PanelGroup,
_extends({}, this.props, { accordion: true }),
this.props.children
);
};
return Accordion;
}(React.Component);
export default Accordion; |
CompositeUi/src/views/composition/LastUpdatedProjectsDashboardWidget.js | kreta-io/kreta | /*
* This file is part of the Kreta package.
*
* (c) Beñat Espiña <[email protected]>
* (c) Gorka Laucirica <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import {Link} from 'react-router';
import React from 'react';
import {routes} from './../../Routes';
import CardExtended from './../component/CardExtended';
import DashboardWidget from './../component/DashboardWidget';
import Thumbnail from './../component/Thumbnail';
class LastUpdatedProjectsDashboardWidget extends React.Component {
static propTypes = {
projects: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
};
renderProjects() {
const {projects} = this.props;
if (projects.length === 0) {
return;
}
return projects.map((project, index) =>
<Link
key={index}
to={routes.project.show(project.organization.slug, project.slug)}
>
<CardExtended
subtitle={project.slug}
thumbnail={<Thumbnail text={`${project.name}`} />}
title={`${project.name}`}
/>
</Link>,
);
}
render() {
return (
<DashboardWidget>
{this.renderProjects()}
</DashboardWidget>
);
}
}
export default LastUpdatedProjectsDashboardWidget;
|
packages/node_modules/@webex/react-component-spaces-list/src/index.js | ciscospark/react-ciscospark | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {AutoSizer, List} from 'react-virtualized';
import {Spinner} from '@momentum-ui/react';
import SpaceItem from '@webex/react-component-space-item';
import {getBadgeState, getGlobalNotificationState, hasMentions} from '@webex/react-component-utils';
import styles from './styles.css';
import './momentum.scss';
const propTypes = {
activeSpaceId: PropTypes.string,
currentUser: PropTypes.object,
hasCalling: PropTypes.bool,
isLoadingMore: PropTypes.bool,
onCallClick: PropTypes.func,
onClick: PropTypes.func,
onScroll: PropTypes.func,
searchTerm: PropTypes.string,
spaces: PropTypes.arrayOf(
PropTypes.shape({
avatarUrl: PropTypes.string,
activityText: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]),
callStartTime: PropTypes.number,
id: PropTypes.string,
isDecrypting: PropTypes.bool,
isUnread: PropTypes.bool,
lastActivityTime: PropTypes.string,
name: PropTypes.string,
teamColor: PropTypes.string,
teamName: PropTypes.string,
type: PropTypes.string
})
),
features: PropTypes.object
};
const defaultProps = {
activeSpaceId: '',
currentUser: null,
features: null,
hasCalling: false,
isLoadingMore: false,
onCallClick: () => {},
onClick: () => {},
onScroll: () => {},
searchTerm: '',
spaces: []
};
export default function SpacesList({
activeSpaceId,
currentUser,
features,
hasCalling,
isLoadingMore,
onCallClick,
onClick,
onScroll,
searchTerm,
spaces
}) {
function rowRenderer(options) {
const {
key,
index
} = options;
let {style} = options;
if (index >= spaces.length) {
style = Object.assign({textAlign: 'center'}, style);
return (
<div key={key} style={style}>
<Spinner size={20} />
</div>
);
}
const space = spaces[index];
const hasMention = hasMentions(currentUser, space);
const unread = space.isUnread;
const globalNotificationState = getGlobalNotificationState(features);
const badge = getBadgeState({
space, unread, hasMention, globalNotificationState
});
return (
<div className={classNames(`webex-spaces-list-item-${index}`)} key={key} style={style}>
<SpaceItem
active={space.id === activeSpaceId}
badge={badge}
hasCalling={hasCalling}
key={key}
onCallClick={onCallClick}
onClick={onClick}
{...space}
searchTerm={searchTerm}
/>
</div>
);
}
const rowCount = isLoadingMore ? spaces.length + 1 : spaces.length;
return (
<div className={classNames('webex-spaces-list-container', styles.spacesListContainer)}>
<AutoSizer>
{({height, width}) => (
<List
className={classNames('webex-spaces-list', styles.spacesListDark)}
height={height}
onScroll={onScroll}
rowCount={rowCount}
rowHeight={52}
rowRenderer={rowRenderer}
width={width}
/>
)}
</AutoSizer>
</div>
);
}
SpacesList.propTypes = propTypes;
SpacesList.defaultProps = defaultProps;
|
Libraries/Image/Image.ios.js | browniefed/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Image
* @flow
*/
'use strict';
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const ImageResizeMode = require('ImageResizeMode');
const ImageSourcePropType = require('ImageSourcePropType');
const ImageStylePropTypes = require('ImageStylePropTypes');
const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
const NativeModules = require('NativeModules');
const PropTypes = require('react/lib/ReactPropTypes');
const React = require('React');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');
const flattenStyle = require('flattenStyle');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');
const ImageViewManager = NativeModules.ImageViewManager;
/**
* A React component for displaying different types of images,
* including network images, static resources, temporary local images, and
* images from local disk, such as the camera roll.
*
* This example shows both fetching and displaying an image from local storage as well as on from
* network.
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image } from 'react-native';
*
* class DisplayAnImage extends Component {
* render() {
* return (
* <View>
* <Image
* source={require('./img/favicon.png')}
* />
* <Image
* style={{width: 50, height: 50}}
* source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
* />
* </View>
* );
* }
* }
*
* // App registration and rendering
* AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);
* ```
*
* You can also add `style` to an image:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image, StyleSheet} from 'react-native';
*
* const styles = StyleSheet.create({
* stretch: {
* width: 50,
* height: 200
* }
* });
*
* class DisplayAnImageWithStyle extends Component {
* render() {
* return (
* <View>
* <Image
* style={styles.stretch}
* source={require('./img/favicon.png')}
* />
* </View>
* );
* }
* }
*
* // App registration and rendering
* AppRegistry.registerComponent(
* 'DisplayAnImageWithStyle',
* () => DisplayAnImageWithStyle
* );
* ```
*
* ### GIF and WebP support on Android
*
* By default, GIF and WebP are not supported on Android.
*
* You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app.
*
* ```
* dependencies {
* // If your app supports Android versions before Ice Cream Sandwich (API level 14)
* compile 'com.facebook.fresco:animated-base-support:0.11.0'
*
* // For animated GIF support
* compile 'com.facebook.fresco:animated-gif:0.11.0'
*
* // For WebP support, including animated WebP
* compile 'com.facebook.fresco:animated-webp:0.11.0'
* compile 'com.facebook.fresco:webpsupport:0.11.0'
*
* // For WebP support, without animations
* compile 'com.facebook.fresco:webpsupport:0.11.0'
* }
* ```
*
* Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` :
* ```
* -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl {
* public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier);
* }
* ```
*
*/
const Image = React.createClass({
propTypes: {
/**
* > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the
* > `resizeMode` style property on `Image` components. The values are `contain`, `cover`,
* > `stretch`, `center`, `repeat`.
*/
style: StyleSheetPropType(ImageStylePropTypes),
/**
* The image source (either a remote URL or a local file resource).
*
* This prop can also contain several remote URLs, specified together with
* their width and height and potentially with scale/other URI arguments.
* The native side will then choose the best `uri` to display based on the
* measured size of the image container.
*/
source: ImageSourcePropType,
/**
* A static image to display while loading the image source.
*
* - `uri` - a string representing the resource identifier for the image, which
* should be either a local file path or the name of a static image resource
* (which should be wrapped in the `require('./path/to/image.png')` function).
* - `width`, `height` - can be specified if known at build time, in which case
* these will be used to set the default `<Image/>` component dimensions.
* - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if
* unspecified, meaning that one image pixel equates to one display point / DIP.
* - `number` - Opaque type returned by something like `require('./image.jpg')`.
*
* @platform ios
*/
defaultSource: PropTypes.oneOfType([
// TODO: Tooling to support documenting these directly and having them display in the docs.
PropTypes.shape({
uri: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
scale: PropTypes.number,
}),
PropTypes.number,
]),
/**
* When true, indicates the image is an accessibility element.
* @platform ios
*/
accessible: PropTypes.bool,
/**
* The text that's read by the screen reader when the user interacts with
* the image.
* @platform ios
*/
accessibilityLabel: PropTypes.string,
/**
* blurRadius: the blur radius of the blur filter added to the image
* @platform ios
*/
blurRadius: PropTypes.number,
/**
* When the image is resized, the corners of the size specified
* by `capInsets` will stay a fixed size, but the center content and borders
* of the image will be stretched. This is useful for creating resizable
* rounded buttons, shadows, and other resizable assets. More info in the
* [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).
*
* @platform ios
*/
capInsets: EdgeInsetsPropType,
/**
* The mechanism that should be used to resize the image when the image's dimensions
* differ from the image view's dimensions. Defaults to `auto`.
*
* - `auto`: Use heuristics to pick between `resize` and `scale`.
*
* - `resize`: A software operation which changes the encoded image in memory before it
* gets decoded. This should be used instead of `scale` when the image is much larger
* than the view.
*
* - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is
* faster (usually hardware accelerated) and produces higher quality images. This
* should be used if the image is smaller than the view. It should also be used if the
* image is slightly bigger than the view.
*
* More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html.
*
* @platform android
*/
resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']),
/**
* Determines how to resize the image when the frame doesn't match the raw
* image dimensions.
*
* - `cover`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal
* to or larger than the corresponding dimension of the view (minus padding).
*
* - `contain`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal to
* or less than the corresponding dimension of the view (minus padding).
*
* - `stretch`: Scale width and height independently, This may change the
* aspect ratio of the src.
*
* - `repeat`: Repeat the image to cover the frame of the view. The
* image will keep it's size and aspect ratio. (iOS only)
*/
resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']),
/**
* A unique identifier for this element to be used in UI Automation
* testing scripts.
*/
testID: PropTypes.string,
/**
* Invoked on mount and layout changes with
* `{nativeEvent: {layout: {x, y, width, height}}}`.
*/
onLayout: PropTypes.func,
/**
* Invoked on load start.
*
* e.g., `onLoadStart={(e) => this.setState({loading: true})}`
*/
onLoadStart: PropTypes.func,
/**
* Invoked on download progress with `{nativeEvent: {loaded, total}}`.
* @platform ios
*/
onProgress: PropTypes.func,
/**
* Invoked on load error with `{nativeEvent: {error}}`.
* @platform ios
*/
onError: PropTypes.func,
/**
* Invoked when load completes successfully.
*/
onLoad: PropTypes.func,
/**
* Invoked when load either succeeds or fails.
*/
onLoadEnd: PropTypes.func,
},
statics: {
resizeMode: ImageResizeMode,
/**
* Retrieve the width and height (in pixels) of an image prior to displaying it.
* This method can fail if the image cannot be found, or fails to download.
*
* In order to retrieve the image dimensions, the image may first need to be
* loaded or downloaded, after which it will be cached. This means that in
* principle you could use this method to preload images, however it is not
* optimized for that purpose, and may in future be implemented in a way that
* does not fully load/download the image data. A proper, supported way to
* preload images will be provided as a separate API.
*
* @param uri The location of the image.
* @param success The function that will be called if the image was sucessfully found and width
* and height retrieved.
* @param failure The function that will be called if there was an error, such as failing to
* to retrieve the image.
*
* @returns void
*
* @platform ios
*/
getSize: function(
uri: string,
success: (width: number, height: number) => void,
failure: (error: any) => void,
) {
ImageViewManager.getSize(uri, success, failure || function() {
console.warn('Failed to get size for image: ' + uri);
});
},
/**
* Prefetches a remote image for later use by downloading it to the disk
* cache
*
* @param url The remote location of the image.
*
* @return The prefetched image.
*/
prefetch(url: string) {
return ImageViewManager.prefetchImage(url);
},
},
mixins: [NativeMethodsMixin],
/**
* `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
* make `this` look like an actual native component class.
*/
viewConfig: {
uiViewClassName: 'UIView',
validAttributes: ReactNativeViewAttributes.UIView
},
render: function() {
const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };
let sources;
let style;
if (Array.isArray(source)) {
style = flattenStyle([styles.base, this.props.style]) || {};
sources = source;
} else {
const {width, height, uri} = source;
style = flattenStyle([{width, height}, styles.base, this.props.style]) || {};
sources = [source];
if (uri === '') {
console.warn('source.uri should not be an empty string');
}
}
const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108
const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108
if (this.props.src) {
console.warn('The <Image> component requires a `source` property rather than `src`.');
}
return (
<RCTImageView
{...this.props}
style={style}
resizeMode={resizeMode}
tintColor={tintColor}
source={sources}
/>
);
},
});
const styles = StyleSheet.create({
base: {
overflow: 'hidden',
},
});
const RCTImageView = requireNativeComponent('RCTImageView', Image);
module.exports = Image;
|
src/app/components/FormPopup/index.js | Krekotun/seat-booking | import React, { Component } from 'react';
import connect from './connect'
import cx from 'classnames'
import Form from './Form'
class FormPopup extends Component {
constructor(props) {
super(props);
this.popupHeight = 0;
}
componentDidMount() {
this.popupHeight = this.node.getBoundingClientRect().height;
}
render() {
let { isOpened, isLoading, position } = this.props;
let klass = cx("iquiz_tables--form", "iquiz_tables--popup", {
'-show': isOpened,
'-loading': isLoading,
'-flip': position.y - (this.popupHeight + 10) <= 0
})
let style = {
top: position.y,
left: position.x
}
return (
<div
className={ klass }
style={ style }
ref={ (node) => { this.node = node } }
>
<Form />
</div>
)
}
}
export default connect(FormPopup)
|
src/svg-icons/navigation/expand-more.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationExpandMore = (props) => (
<SvgIcon {...props}>
<path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"/>
</SvgIcon>
);
NavigationExpandMore = pure(NavigationExpandMore);
NavigationExpandMore.displayName = 'NavigationExpandMore';
NavigationExpandMore.muiName = 'SvgIcon';
export default NavigationExpandMore;
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SvgInclusion.js | picter/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import logo from './assets/logo.svg';
export default () => <img id="feature-svg-inclusion" src={logo} alt="logo" />;
|
test/helpers/shallowRenderHelper.js | landerqi/gallery-by-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
examples/js/column-filter/select-filter-with-sort.js | echaouchna/react-bootstrap-tab | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
const qualityType = {
0: 'good',
1: 'bad',
2: 'unknown'
};
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
quality: i % (Object.keys(qualityType).length)
});
}
}
addProducts(15);
function enumFormatter(cell, row, enumObject) {
return enumObject[cell];
}
export default class SelectFilterWithSort extends React.Component {
render() {
const filter = {
type: 'TextFilter'
};
return (
<BootstrapTable data={ products }>
<TableHeaderColumn dataSort dataField='id' filter={ filter } isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataSort dataField='quality' filterFormatted dataFormat={ enumFormatter }
formatExtraData={ qualityType } filter={ { type: 'SelectFilter', options: qualityType, defaultValue: 1 } }>Product Quality</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
cheesecakes/plugins/content-type-builder/admin/src/containers/App/index.js | strapi/strapi-examples | /**
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
*/
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, compose } from 'redux';
// import { withRouter } from 'react-router';
import { createStructuredSelector } from 'reselect';
import { Switch, Route, withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import { pluginId } from 'app';
import HomePage from 'containers/HomePage';
import ModelPage from 'containers/ModelPage';
import NotFoundPage from 'containers/NotFoundPage';
import formSaga from 'containers/Form/sagas';
import formReducer from 'containers/Form/reducer';
// Other containers actions
import { makeSelectShouldRefetchContentType } from 'containers/Form/selectors';
// Utils
import injectSaga from 'utils/injectSaga';
import injectReducer from 'utils/injectReducer';
import { storeData } from '../../utils/storeData';
import styles from './styles.scss';
import { modelsFetch } from './actions';
import saga from './sagas';
/* eslint-disable consistent-return */
class App extends React.Component {
componentDidMount() {
this.props.modelsFetch();
}
componentWillReceiveProps(nextProps) {
if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) {
this.props.modelsFetch();
}
}
componentWillUnmount() {
// Empty the app localStorage
storeData.clearAppStorage();
}
render() {
return (
<div className={`${pluginId} ${styles.app}`}>
<Switch>
<Route exact path="/plugins/content-type-builder" component={HomePage} />
<Route exact path="/plugins/content-type-builder/models/:modelName" component={ModelPage} />
<Route path="" component={NotFoundPage} />
</Switch>
</div>
);
}
}
App.contextTypes = {
plugins: PropTypes.object,
router: PropTypes.object.isRequired,
updatePlugin: PropTypes.func,
};
App.propTypes = {
modelsFetch: PropTypes.func.isRequired,
shouldRefetchContentType: PropTypes.bool,
};
App.defaultProps = {
shouldRefetchContentType: false,
};
export function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
modelsFetch,
},
dispatch
);
}
const mapStateToProps = createStructuredSelector({
shouldRefetchContentType: makeSelectShouldRefetchContentType(),
});
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withSaga = injectSaga({ key: 'global', saga });
const withFormReducer = injectReducer({ key: 'form', reducer: formReducer });
const withFormSaga = injectSaga({ key: 'form', saga: formSaga });
export default compose(
withFormReducer,
withFormSaga,
withSaga,
withRouter,
withConnect,
)(App);
|
src/helpers/Html.js | madeagency/reactivity | // @flow
import React from 'react'
import type { Node } from 'react'
import Helmet from 'react-helmet'
import serialize from 'serialize-javascript'
type Props = {
styles: Array<string>,
cssHash: {},
js: Array<string>,
component: Node,
state: {}
}
const Html = (props: Props) => {
const { styles, cssHash, js, component, state } = props
const head = Helmet.renderStatic()
const htmlAttrs = head.htmlAttributes.toComponent()
return (
<html lang="en" {...htmlAttrs}>
<head>
{head.title.toComponent()}
{head.meta.toComponent()}
{head.link.toComponent()}
{styles.map(name => (
<link rel="stylesheet" href={`/${name}`} key={name} />
))}
</head>
<body>
<div id="root" dangerouslySetInnerHTML={{ __html: component }} />
<script
type="text/javascript"
dangerouslySetInnerHTML={{
__html: `window.__data=${serialize(state)};`
}}
charSet="UTF-8"
/>
<script
type="text/javascript"
dangerouslySetInnerHTML={{
__html: `window.__CSS_CHUNKS__=${serialize(cssHash)};`
}}
charSet="UTF-8"
/>
{js.map(name => (
<script
type="text/javascript"
src={`/${name}`}
key={name}
charSet="UTF-8"
/>
))}
</body>
</html>
)
}
export default Html
|
app/javascript/mastodon/features/ui/components/block_modal.js | musashino205/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { injectIntl, FormattedMessage } from 'react-intl';
import { makeGetAccount } from '../../../selectors';
import Button from '../../../components/button';
import { closeModal } from '../../../actions/modal';
import { blockAccount } from '../../../actions/accounts';
import { initReport } from '../../../actions/reports';
const makeMapStateToProps = () => {
const getAccount = makeGetAccount();
const mapStateToProps = state => ({
account: getAccount(state, state.getIn(['blocks', 'new', 'account_id'])),
});
return mapStateToProps;
};
const mapDispatchToProps = dispatch => {
return {
onConfirm(account) {
dispatch(blockAccount(account.get('id')));
},
onBlockAndReport(account) {
dispatch(blockAccount(account.get('id')));
dispatch(initReport(account));
},
onClose() {
dispatch(closeModal());
},
};
};
export default @connect(makeMapStateToProps, mapDispatchToProps)
@injectIntl
class BlockModal extends React.PureComponent {
static propTypes = {
account: PropTypes.object.isRequired,
onClose: PropTypes.func.isRequired,
onBlockAndReport: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
componentDidMount() {
this.button.focus();
}
handleClick = () => {
this.props.onClose();
this.props.onConfirm(this.props.account);
}
handleSecondary = () => {
this.props.onClose();
this.props.onBlockAndReport(this.props.account);
}
handleCancel = () => {
this.props.onClose();
}
setRef = (c) => {
this.button = c;
}
render () {
const { account } = this.props;
return (
<div className='modal-root__modal block-modal'>
<div className='block-modal__container'>
<p>
<FormattedMessage
id='confirmations.block.message'
defaultMessage='Are you sure you want to block {name}?'
values={{ name: <strong>@{account.get('acct')}</strong> }}
/>
</p>
</div>
<div className='block-modal__action-bar'>
<Button onClick={this.handleCancel} className='block-modal__cancel-button'>
<FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' />
</Button>
<Button onClick={this.handleSecondary} className='confirmation-modal__secondary-button'>
<FormattedMessage id='confirmations.block.block_and_report' defaultMessage='Block & Report' />
</Button>
<Button onClick={this.handleClick} ref={this.setRef}>
<FormattedMessage id='confirmations.block.confirm' defaultMessage='Block' />
</Button>
</div>
</div>
);
}
}
|
src/components/operation.js | LaserWeb/LaserWeb4 | // Copyright 2016 Todd Fleming
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React from 'react'
import { connect } from 'react-redux';
import Select from 'react-select';
import uuidv4 from 'uuid/v4';
import { removeOperation, moveOperation, setCurrentOperation, operationRemoveDocument, setOperationAttrs, clearOperations, spreadOperationField, operationLatheTurnAdd, operationLatheTurnRemove, operationLatheTurnSetAttrs } from '../actions/operation';
import { selectDocument } from '../actions/document'
import { addOperation } from '../actions/operation'
import { hasClosedRawPaths } from '../lib/mesh';
import { Input, InputRangeField } from './forms.js';
import { GetBounds, withGetBounds, withStoredBounds } from './get-bounds.js';
import { selectedDocuments } from './document'
import Toggle from 'react-toggle';
import { isObject, getDescendantProp } from '../lib/helpers';
import { MaterialPickerButton, MaterialSaveButton } from './material-database'
import { ButtonToolbar, Button, ButtonGroup } from 'react-bootstrap';
import Icon from './font-awesome'
import { Details } from './material-database'
import { confirm } from './laserweb'
import { SETTINGS_INITIALSTATE } from '../reducers/settings'
import { ContextMenu, MenuItem, ContextMenuTrigger } from "react-contextmenu";
import "../styles/context-menu.css";
function StringInput(props) {
let { op, field, operationsBounds, fillColors, strokeColors, settings, dispatch, ...rest } = props;
let value = op[field.name];
return <Input value={value !== undefined ? value : ''} {...rest } />;
}
function NumberInput(props) {
let { op, field, operationsBounds, fillColors, strokeColors, settings, dispatch, ...rest } = props;
return <Input type='number' step='any' value={op[field.name]} {...rest } />;
}
function EnumInput(opts, def) {
if (Array.isArray(opts))
opts = Object.assign(...opts.map(i => ({ [i]: i })))
return function ({ op, field, onChangeValue, operationsBounds, fillColors, strokeColors, settings, dispatch, ...rest }) {
return <select value={op[field.name]} {...rest} >
{Object.entries(opts).map((e, i) => (<option key={i} value={e[0]}>{e[1]}</option>))}
</select>
}
}
const DirectionInput = EnumInput(['Conventional', 'Climb']);
const GrayscaleInput = EnumInput(['none', 'average', 'luma', 'luma-601', 'luma-709', 'luma-240', 'desaturation', 'decomposition-min', 'decomposition-max', 'red-chanel', 'green-chanel', 'blue-chanel']);
function CheckboxInput({ op, field, onChangeValue, operationsBounds, fillColors, strokeColors, settings, dispatch, ...rest }) {
return <input {...rest} checked={op[field.name]} onChange={e => onChangeValue(e.target.checked)} type="checkbox" />
}
function ToggleInput({ op, field, onChangeValue, operationsBounds, fillColors, strokeColors, settings, className = "scale75", dispatch, ...rest }) {
return <Toggle id={"toggle_" + op.id + "_" + field} defaultChecked={op[field.name]} onChange={e => onChangeValue(e.target.checked)} className={className} />
}
function RangeInput(minValue, maxValue) {
return ({ op, field, onChangeValue, dispatch, ...rest }) => {
return <InputRangeField maxValue={maxValue} minValue={minValue} value={op[field.name]} onChangeValue={value => onChangeValue(value)} />
}
}
function TagInput(statekey, opts = { multi: true, simpleValue: true, delimiter: ',', clearable: true }, connector) {
if (!connector) connector = (state) => { return { options: Object.entries(getDescendantProp(state, statekey)).map(i => { return { label: i[1].label, value: i[0] } }) } }
return connect(connector)(React.createClass({
render: function () {
return <Select options={this.props.options} value={this.props.op[this.props.field.name]} onChange={e => this.props.onChangeValue(e)} {...{ ...opts }} />
}
}))
}
function ButtonInput(args) {
return <Button onClick={e => args.field.onClick(e, args)} bsSize="xsmall" bsStyle="info" >{args.field.buttonLabel}</Button>;
}
function TableInput({ op, field, operationsBounds, fillColors, strokeColors, settings, dispatch }) {
let { name, fields, remove } = field;
let array = op[name];
if (!array.length)
return null;
return <div style={{ display: 'inline-block' }}><table><tbody>
<tr>{Object.entries(fields).map(f => <th key={f[1].name} style={{ paddingRight: 10 }}>{f[1].label}</th>)}</tr>
{array.map((item, index) => <tr key={item.id}>
{Object.entries(fields).map(f => <td key={f[1].name}>
<Field {...{
op: item, field: f[1], operationsBounds, fillColors, strokeColors, settings,
setAttrs: operationLatheTurnSetAttrs, dispatch, justControl: true, parent: op, index,
}} />
</td>)}
<td>
<button className="btn btn-default btn-xs" onClick={e => dispatch(remove(item.id))}>
<i className="fa fa-trash"></i>
</button>
</td>
</tr>)}
</tbody></table></div>;
}
function ColorBox(v) {
let rgb = 'rgb(' + v.color[0] * 255 + ',' + v.color[1] * 255 + ',' + v.color[2] * 255 + ')';
return (
<span style={{ backgroundColor: rgb, width: 40, display: 'inline-block' }}> </span>
);
}
class FilterInput extends React.Component {
componentWillMount() {
this.onChange = this.onChange.bind(this);
}
onChange(v) {
if (v)
this.props.onChangeValue(JSON.parse(v.value));
else
this.props.onChangeValue(null);
}
render() {
let { op, field, onChange, onChangeValue, operationsBounds, fillColors, strokeColors, settings, ...rest } = this.props;
let raw = op[field.name];
let colors = field.name === 'filterFillColor' ? fillColors : strokeColors;
let value;
if (raw)
value = JSON.stringify(raw);
else
value = null;
return (
<Select
value={value} options={colors} onChange={this.onChange} searchable={false}
optionRenderer={ColorBox} valueRenderer={ColorBox} {...rest} />
);
}
}
export function Error(props) {
let { bounds, operationsBounds, message } = props;
return (
<div className="error-bubble-clip" style={{ left: operationsBounds.right, top: operationsBounds.top }}>
<div style={{ height: operationsBounds.bottom - operationsBounds.top }}>
<div className='error-bubble' style={{ top: (bounds.top + bounds.bottom) / 2 - operationsBounds.top }}>
<div className='error-bubble-arrow' />
<div className='error-bubble-message'>{message}</div>
</div>
</div>
</div>
);
}
Error = withStoredBounds(Error);
function NoOperationsError(props) {
let { documents, operations, operationsBounds } = props;
if (documents.length && !operations.length)
return <GetBounds Type="span"><Error operationsBounds={operationsBounds} message='Drag Documents(s) Here' /></GetBounds>;
else
return <span />;
}
class Field extends React.Component {
componentWillMount() {
this.onChangeValue = this.onChangeValue.bind(this);
this.onChange = this.onChange.bind(this);
this.onFocus = this.onFocus.bind(this);
}
onChangeValue(v) {
let { op, field, setAttrs } = this.props;
if (op[field.name] !== v)
this.props.dispatch(setAttrs({ [field.name]: v }, op.id));
}
onChange(e) {
this.onChangeValue(e.target.value);
}
onFocus(e) {
if (!this.props.selected)
this.props.dispatch(setCurrentOperation(this.props.op.id));
}
render() {
let { op, field, operationsBounds, fillColors, strokeColors, settings, dispatch, justControl, parent, index } = this.props;
let Input = field.input;
let { units, wide, style } = field;
let error;
if (units === 'mm/min' && settings.toolFeedUnits === 'mm/s')
units = settings.toolFeedUnits;
if (field.check && !field.check(op[field.name], settings, op, parent, index))
error = <Error operationsBounds={operationsBounds} message={(typeof field.error == 'function') ? field.error(op[field.name], settings, op, parent, index) : field.error} />;
let Ctx = field.contextMenu;
let label = (Ctx) ? (<Ctx {...{ dispatch, op, field, settings }}><span style={{ borderBottom: "2px dashed blue", cursor: "context-menu" }}>{field.label}</span></Ctx>) : field.label;
if (justControl) {
return (
<GetBounds Type="div">
<Input
{...{ op, field, operationsBounds, fillColors, strokeColors, settings, dispatch, style }}
onChange={this.onChange} onChangeValue={this.onChangeValue} onFocus={this.onFocus} />
{error}
</GetBounds>
);
}
if (wide) {
return (
<GetBounds Type="tr">
<td colSpan="3">
<Input
{...{ op, field, operationsBounds, fillColors, strokeColors, settings, dispatch, style }}
onChange={this.onChange} onChangeValue={this.onChangeValue} onFocus={this.onFocus} />
</td>
<td>{units}{error}</td>
</GetBounds>
);
}
return (
<GetBounds Type="tr">
<th width="30%">{label}</th>
<td>
<Input
{...{ op, field, operationsBounds, fillColors, strokeColors, settings, dispatch, style }}
onChange={this.onChange} onChangeValue={this.onChangeValue} onFocus={this.onFocus} />
</td>
<td>{units}{error}</td>
</GetBounds>
);
}
};
class Doc extends React.Component {
componentWillMount() {
this.remove = e => {
this.props.dispatch(operationRemoveDocument(this.props.op.id, this.props.isTab, this.props.id));
}
}
render() {
let { op, documents, id } = this.props;
return (
<tr>
<td style={{ width: '100%', whiteSpace: 'nowrap' }}>
└ <a style={{ userSelect: 'none', cursor: 'pointer', textDecoration: 'bold', color: '#FFF', paddingLeft: 5, paddingRight: 5, paddingBottom: 3, backgroundColor: '#337AB7', border: '1px solid', borderColor: '#2e6da4', borderRadius: 2 }} onClick={(e) => { this.props.dispatch(selectDocument(id)) }}>{documents.find(d => d.id === id).name}</a>
</td>
<td>
<button className="btn btn-default btn-xs" onClick={this.remove}>
<i className="fa fa-trash"></i>
</button>
</td>
<td style={{ paddingLeft: 15 }} ></td>
</tr>
);
}
}
Doc = connect()(Doc);
const checkPositive = {
check: v => v > 0,
error: 'Must be > 0',
};
const checkPositiveInt = {
check: v => v > 0 && (v | 0) === +v,
error: 'Must be integer > 0',
};
const checkGE0 = {
check: v => v >= 0,
error: 'Must be >= 0',
};
const checkGE0Int = {
check: v => v >= 0 && (v | 0) === +v,
error: 'Must be integer >= 0',
};
const checkNot0 = {
check: v => +v != 0,
error: 'Must be non-0',
};
const checkPercent = {
check: v => v >= 0 && v <= 100,
error: 'Must be in range [0, 100]',
};
const checkStepOver = {
check: v => v > 0 && v <= 100,
error: 'Must be > 0 and <= 100',
};
const checkToolAngle = {
check: v => v > 0 && v < 180,
error: 'Must be in range (0, 180)',
};
const checkToolDiameter = {
check: (v, settings, op) => v > 0 || op.type === 'Mill Cut' && v >= 0,
error: (v, settings, op) => op.type === 'Mill Cut' ? 'Must be >= 0' : 'Must be > 0',
};
function checkRange(min, max) {
return {
check: (v) => {
if (isFinite(v)) {
return v >= min && v <= max;
} else if (isObject(v) && v.hasOwnProperty('min') && v.hasOwnProperty('max')) {
return (v.min >= min && v.min <= max) && (v.max >= min && v.max <= max)
}
},
error: 'Must be in range [' + min + ' , ' + max + ']',
}
}
function checkFeedRateRange(axis) {
return {
check: (v, settings) => {
let { min, max } = Object.assign(SETTINGS_INITIALSTATE.machineFeedRange, settings.machineFeedRange)[axis];
if (isFinite(v)) {
return v >= min && v <= max;
} else if (isObject(v) && v.hasOwnProperty('min') && v.hasOwnProperty('max')) {
return (v.min >= min && v.min <= max) && (v.max >= min && v.max <= max)
}
},
error: (v, settings) => {
let { min, max } = Object.assign(SETTINGS_INITIALSTATE.machineFeedRange, settings.machineFeedRange)[axis];
if (isNaN(min) || isNaN(max))
return 'Check settings/machine first!';
return 'Must be in range [' + min + ' , ' + max + ']'
}
}
}
const ifUseA = {
condition: op => op.useA
};
const checkZHeight = {
check: (v, settings) => settings.machineZEnabled && v && !isNaN(v),
error: (v, settings, op) => {
if (!op.type.match(/^Laser/)) return false;
if (!settings.machineZEnabled) return 'Laser Z Stage must be enabled';
return 'Has to be a number'
}
}
const ifUseZ = {
condition: (op, settings) => {
if (!op.type.match(/^Laser/)) return true;
return settings.machineZEnabled
}
};
const ifUseBlower = {
condition: (op, settings) => {
if (!op.type.match(/^Laser/)) return false;
return settings.machineBlowerEnabled
}
};
const checkPassDepth = {
check: (v, settings, op) => { return (op.type.match(/^Laser/)) ? checkGE0.check(v, settings, op) : checkPositive.check(v, settings, op) },
error: (v, settings, op) => { return (op.type.match(/^Laser/)) ? checkGE0.error : checkPositive.error },
}
const checkMillStartZ = {
check: (v, settings, op) => v <= op.millRapidZ,
error: 'Must be <= Rapid Z',
};
const checkMillEndZ = {
check: (v, settings, op) => v < op.millStartZ,
error: 'Must be < Start Z',
};
const checkLatheStartZ = {
check: (v, settings, op) => v <= op.latheRapidToZ - op.latheFinishDepth,
error: 'Must be <= Rapid To Z - Finish Depth',
};
const checkLatheFaceEndDiameter = {
condition: op => op.latheFace,
check: (v, settings, op) => {
if (op.latheFaceEndDiameter >= op.latheRapidToDiameter)
return false;
if (op.latheFaceEndDiameter < -op.latheRapidToDiameter)
return false;
return true;
},
error: (v, settings, op) => {
if (op.latheFaceEndDiameter >= op.latheRapidToDiameter)
return "Must be < Rapid To Diameter";
if (op.latheFaceEndDiameter < -op.latheRapidToDiameter)
return "Must be >= -(Rapid To Diameter)";
return "I'm confused";
},
};
const latheTurnAdd = {
check: (v, settings, op) => op.latheFace || op.latheTurns.length > 0,
error: 'Need at least one turn when not facing',
onClick: (e, { op, dispatch }) => dispatch(operationLatheTurnAdd(op.id)),
};
const checkLatheTurn = {
check: (v, settings, turn, parent, index) => {
if (turn.startDiameter < 0)
return false;
if (index > 0 && turn.startDiameter < parent.latheTurns[index - 1].endDiameter)
return false;
if (turn.startDiameter >= parent.latheRapidToDiameter)
return false;
if (turn.endDiameter <= 0)
return false;
if (turn.endDiameter < turn.startDiameter)
return false;
if (turn.endDiameter >= parent.latheRapidToDiameter - parent.latheFinishDepth)
return false;
if (turn.endDiameter !== turn.startDiameter)
return false;
if (turn.length <= 0)
return false;
return true;
},
error: (v, settings, turn, parent, index) => {
if (turn.startDiameter < 0)
return 'Start Diameter must be >= 0';
if (index > 0 && turn.startDiameter < parent.latheTurns[index - 1].endDiameter)
return 'Start Diameter must be >= previous End Diameter';
if (turn.startDiameter >= parent.latheRapidToDiameter)
return 'Start Diameter must be < Rapid';
if (turn.endDiameter <= 0)
return 'End Diameter must be > 0';
if (turn.endDiameter < turn.startDiameter)
return 'End Diameter must be >= Start Diameter';
if (turn.endDiameter >= parent.latheRapidToDiameter - parent.latheFinishDepth)
return 'End Diameter must be < Rapid - Finish Depth';
if (turn.endDiameter !== turn.startDiameter)
return 'Taper not implemented yet';
if (turn.length <= 0)
return 'Length must be > 0';
return "I'm confused";
},
};
const FieldContextMenu = (id = uuidv4()) => {
return ({ children, dispatch, op, field, settings }) => {
let ctx = <ContextMenu id={id}>
<MenuItem onClick={e => dispatch(spreadOperationField(op.id, field.name))}>Copy to all Ops</MenuItem>
</ContextMenu>
return <div title="Right click or press long to popup context menu"><ContextMenuTrigger id={id} holdToDisplay={1000}>{children}</ContextMenuTrigger>{ctx}</div>
}
}
export const OPERATION_LATHE_TURN_FIELDS = {
startDiameter: { name: 'startDiameter', label: 'Start Diameter', input: NumberInput, style: { width: 80 }, ...checkLatheTurn },
endDiameter: { name: 'endDiameter', label: 'End Diameter', input: NumberInput, style: { width: 80 } },
length: { name: 'length', label: 'Length', input: NumberInput, style: { width: 80 } },
};
export const OPERATION_FIELDS = {
name: { name: 'name', label: 'Name', units: '', input: StringInput },
filterFillColor: { name: 'filterFillColor', label: 'Filter Fill', units: '', input: FilterInput },
filterStrokeColor: { name: 'filterStrokeColor', label: 'Filter Stroke', units: '', input: FilterInput },
direction: { name: 'direction', label: 'Direction', units: '', input: DirectionInput },
laserPower: { name: 'laserPower', label: 'Laser Power', units: '%', input: NumberInput, ...checkPercent, contextMenu: FieldContextMenu() },
laserPowerRange: { name: 'laserPowerRange', label: 'Laser Power Range', units: '%', input: RangeInput(0, 100), ...checkRange(0, 100) },
laserDiameter: { name: 'laserDiameter', label: 'Laser Diameter', units: 'mm', input: NumberInput, ...checkPositive, contextMenu: FieldContextMenu() },
lineDistance: { name: 'lineDistance', label: 'Line Distance', units: 'mm', input: NumberInput, ...checkPositive, contextMenu: FieldContextMenu() },
lineAngle: { name: 'lineAngle', label: 'Line Angle', units: 'deg', input: NumberInput },
toolDiameter: { name: 'toolDiameter', label: 'Tool Diameter', units: 'mm', input: NumberInput, ...checkToolDiameter },
toolAngle: { name: 'toolAngle', label: 'Tool Angle', units: 'deg', input: NumberInput, ...checkToolAngle },
margin: { name: 'margin', label: 'Margin', units: 'mm', input: NumberInput, contextMenu: FieldContextMenu() },
passes: { name: 'passes', label: 'Passes', units: '', input: NumberInput, ...checkPositiveInt, contextMenu: FieldContextMenu() },
cutWidth: { name: 'cutWidth', label: 'Final Cut Width', units: 'mm', input: NumberInput },
stepOver: { name: 'stepOver', label: 'Step Over', units: '%', input: NumberInput, ...checkStepOver },
passDepth: { name: 'passDepth', label: 'Pass Depth', units: 'mm', input: NumberInput, ...checkPassDepth, ...ifUseZ, contextMenu: FieldContextMenu() },
millRapidZ: { name: 'millRapidZ', label: 'Rapid Z', units: 'mm', input: NumberInput },
millStartZ: { name: 'millStartZ', label: 'Start Z', units: 'mm', input: NumberInput, ...checkMillStartZ },
millEndZ: { name: 'millEndZ', label: 'End Z', units: 'mm', input: NumberInput, ...checkMillEndZ },
startHeight: { name: 'startHeight', label: 'Start Height', units: 'mm', input: StringInput, contextMenu: FieldContextMenu(), ...checkZHeight, ...ifUseZ },
segmentLength: { name: 'segmentLength', label: 'Segment', units: 'mm', input: NumberInput, ...checkGE0 },
ramp: { name: 'ramp', label: 'Ramp Plunge', units: '', input: ToggleInput },
plungeRate: { name: 'plungeRate', label: 'Plunge Rate', units: 'mm/min', input: NumberInput, ...checkFeedRateRange('Z') },
cutRate: { name: 'cutRate', label: 'Cut Rate', units: 'mm/min', input: NumberInput, ...checkFeedRateRange('XY'), contextMenu: FieldContextMenu() },
toolSpeed: { name: 'toolSpeed', label: 'Tool Speed (0=Off)', units: 'rpm', input: NumberInput, ...checkFeedRateRange('S') },
useA: { name: 'useA', label: 'Use A Axis', units: '', input: ToggleInput, contextMenu: FieldContextMenu() },
aAxisDiameter: { name: 'aAxisDiameter', label: 'A Diameter', units: 'mm', input: NumberInput, ...checkPositive, ...ifUseA },
useBlower: { name: 'useBlower', label: 'Use Air Assist', units: '', input: ToggleInput, ...ifUseBlower, contextMenu: FieldContextMenu() },
smoothing: { name: 'smoothing', label: 'Smoothing', units: '', input: ToggleInput }, // lw.raster-to-gcode: Smoothing the input image ?
brightness: { name: 'brightness', label: 'Brightness', units: '', input: NumberInput, ...checkRange(-255, 255) }, // lw.raster-to-gcode: Image brightness [-255 to +255]
contrast: { name: 'contrast', label: 'Contrast', units: '', input: NumberInput, ...checkRange(-255, 255) }, // lw.raster-to-gcode: Image contrast [-255 to +255]
gamma: { name: 'gamma', label: 'Gamma', units: '', input: NumberInput, ...checkRange(0, 7.99) }, // lw.raster-to-gcode: Image gamma correction [0.01 to 7.99]
grayscale: { name: 'grayscale', label: 'Grayscale', units: '', input: GrayscaleInput }, // lw.raster-to-gcode: Graysale algorithm [none, average, luma, luma-601, luma-709, luma-240, desaturation, decomposition-[min|max], [red|green|blue]-chanel]
shadesOfGray: { name: 'shadesOfGray', label: 'Shades', units: '', input: NumberInput, ...checkRange(2, 256) }, // lw.raster-to-gcode: Number of shades of gray [2-256]
invertColor: { name: 'invertColor', label: 'Invert Color', units: '', input: ToggleInput }, // lw.raster-to-gcode
trimLine: { name: 'trimLine', label: 'Trim Pixels', units: '', input: ToggleInput }, // lw.raster-to-gcode: Trim trailing white pixels
joinPixel: { name: 'joinPixel', label: 'Join Pixels', units: '', input: ToggleInput }, // lw.raster-to-gcode: Join consecutive pixels with same intensity
burnWhite: { name: 'burnWhite', label: 'Burn White', units: '', input: ToggleInput }, // lw.raster-to-gcode: [true = G1 S0 | false = G0] on inner white pixels
verboseGcode: { name: 'verboseGcode', label: 'Verbose GCode', units: '', input: ToggleInput }, // lw.raster-to-gcode: Output verbose GCode (print each commands)
diagonal: { name: 'diagonal', label: 'Diagonal', units: '', input: ToggleInput }, // lw.raster-to-gcode: Go diagonally (increase the distance between points)
dithering: { name: 'dithering', label: 'Dithering', units: '', input: ToggleInput }, // lw.raster-to-gcode: Go diagonally (increase the distance between points)
overScan: { name: 'overScan', label: 'Over Scan', units: 'mm', input: NumberInput, ...checkGE0 }, // lw.raster-to-gcode: This feature add some extra white space before and after each line. This leaves time to reach the feed rate before starting to engrave and can prevent over burning the edges of the raster.
latheToolBackSide: { name: 'latheToolBackSide', label: 'Tool Back Side', input: ToggleInput },
latheRapidToDiameter: { name: 'latheRapidToDiameter', label: 'Rapid To Diameter', units: 'mm', input: NumberInput, ...checkPositive },
latheRapidToZ: { name: 'latheRapidToZ', label: 'Rapid To Z', units: 'mm', input: NumberInput },
latheStartZ: { name: 'latheStartZ', label: 'Start Z', units: 'mm', input: NumberInput, ...checkLatheStartZ },
latheRoughingFeed: { name: 'latheRoughingFeed', label: 'Roughing Feed', units: 'mm/min', input: NumberInput, ...checkFeedRateRange('XY') },
latheRoughingDepth: { name: 'latheRoughingDepth', label: 'Roughing Depth', units: 'mm', input: NumberInput, ...checkPositive },
latheFinishFeed: { name: 'latheFinishFeed', label: 'Finish Feed', units: 'mm/min', input: NumberInput, ...checkFeedRateRange('XY') },
latheFinishDepth: { name: 'latheFinishDepth', label: 'Finish Depth', units: 'mm', input: NumberInput, ...checkGE0 },
latheFinishExtraPasses: { name: 'latheFinishExtraPasses', label: 'Finish Extra Passes', input: NumberInput, ...checkGE0Int },
latheFace: { name: 'latheFace', label: 'Face', input: ToggleInput },
latheFaceEndDiameter: { name: 'latheFaceEndDiameter', label: 'Face End Diameter', units: 'mm', input: NumberInput, ...checkLatheFaceEndDiameter },
latheTurnAdd: { name: 'latheTurnAdd', buttonLabel: 'Add Turn', input: ButtonInput, wide: true, ...latheTurnAdd },
latheTurns: { name: 'latheTurns', input: TableInput, fields: OPERATION_LATHE_TURN_FIELDS, remove: operationLatheTurnRemove, wide: true },
hookOperationStart: { name: 'hookOperationStart', label: 'Pre Op', units: '', input: TagInput('settings.macros') },
hookOperationEnd: { name: 'hookOperationEnd', label: 'Post Op', units: '', input: TagInput('settings.macros') },
hookPassStart: { name: 'hookPassStart', label: 'Pre Pass', units: '', input: TagInput('settings.macros') },
hookPassEnd: { name: 'hookPassEnd', label: 'Post Pass', units: '', input: TagInput('settings.macros') },
};
export const OPERATION_GROUPS = {
'Filters': {
collapsible: false,
fields: ['smoothing', 'brightness', 'contrast', 'gamma', 'grayscale', 'shadesOfGray', 'invertColor', 'dithering']
},
'Macros': {
collapsible: true,
fields: ['hookOperationStart', 'hookOperationEnd', 'hookPassStart', 'hookPassEnd']
}
}
const tabFields = [
{ name: 'tabDepth', label: 'Tab Depth', units: 'mm', input: NumberInput, ...checkGE0 },
];
export const OPERATION_TYPES = {
'Laser Cut': { allowTabs: true, tabFields: false, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'laserPower', 'passes', 'passDepth', 'startHeight', 'cutRate', 'useA', 'aAxisDiameter', 'useBlower', 'segmentLength', ...OPERATION_GROUPS.Macros.fields] },
'Laser Cut Inside': { allowTabs: true, tabFields: false, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'laserDiameter', 'laserPower', 'margin', 'passes', 'passDepth', 'startHeight', 'cutRate', 'useA', 'aAxisDiameter', 'useBlower', 'segmentLength', ...OPERATION_GROUPS.Macros.fields] },
'Laser Cut Outside': { allowTabs: true, tabFields: false, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'laserDiameter', 'laserPower', 'margin', 'passes', 'passDepth', 'startHeight', 'cutRate', 'useA', 'aAxisDiameter', 'useBlower', 'segmentLength', ...OPERATION_GROUPS.Macros.fields] },
'Laser Fill Path': { allowTabs: false, tabFields: false, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'lineDistance', 'lineAngle', 'laserPower', 'margin', 'passes', 'passDepth', 'startHeight', 'cutRate', 'useA', 'aAxisDiameter', 'useBlower', ...OPERATION_GROUPS.Macros.fields] },
'Laser Raster': {
allowTabs: false, tabFields: false, fields: [
'name', 'laserPowerRange', 'laserDiameter', 'passes', 'passDepth', 'startHeight', 'cutRate', 'useBlower',
'trimLine', 'joinPixel', 'burnWhite', 'verboseGcode', 'diagonal', 'overScan', 'useA', 'aAxisDiameter',
...OPERATION_GROUPS.Filters.fields, ...OPERATION_GROUPS.Macros.fields
]
},
'Laser Raster Merge': {
allowTabs: false, tabFields: false, fields: [
'name', 'filterFillColor', 'filterStrokeColor',
'laserPowerRange', 'laserDiameter', 'passes', 'passDepth', 'startHeight', 'cutRate', 'useBlower',
'trimLine', 'joinPixel', 'burnWhite', 'verboseGcode', 'diagonal', 'overScan', 'useA', 'aAxisDiameter',
...OPERATION_GROUPS.Filters.fields, ...OPERATION_GROUPS.Macros.fields
]
},
'Mill Pocket': { allowTabs: true, tabFields: true, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'direction', 'margin', 'toolSpeed', 'millRapidZ', 'millStartZ', 'millEndZ', 'passDepth', 'toolDiameter', 'stepOver', 'segmentLength', 'plungeRate', 'cutRate', 'ramp', 'hookOperationStart', 'hookOperationEnd'] },
'Mill Cut': { allowTabs: true, tabFields: true, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'direction', 'toolSpeed', 'millRapidZ', 'millStartZ', 'millEndZ', 'passDepth', 'toolDiameter', 'segmentLength', 'plungeRate', 'cutRate', 'ramp', 'hookOperationStart', 'hookOperationEnd'] },
'Mill Cut Inside': { allowTabs: true, tabFields: true, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'direction', 'margin', 'toolSpeed', 'millRapidZ', 'millStartZ', 'millEndZ', 'passDepth', 'cutWidth', 'toolDiameter', 'stepOver', 'plungeRate', 'cutRate', 'segmentLength', 'ramp', 'hookOperationStart', 'hookOperationEnd'] },
'Mill Cut Outside': { allowTabs: true, tabFields: true, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'direction', 'margin', 'toolSpeed', 'millRapidZ', 'millStartZ', 'millEndZ', 'passDepth', 'cutWidth', 'toolDiameter', 'stepOver', 'plungeRate', 'cutRate', 'segmentLength', 'ramp', 'hookOperationStart', 'hookOperationEnd'] },
'Mill V Carve': { allowTabs: false, fields: ['name', 'filterFillColor', 'filterStrokeColor', 'direction', 'toolAngle', 'millRapidZ', 'millStartZ', 'toolSpeed', 'passDepth', 'segmentLength', 'plungeRate', 'cutRate', 'hookOperationStart', 'hookOperationEnd'] },
'Lathe Conv Face/Turn': { skipDocs: true, tabFields: false, fields: ['name', 'latheToolBackSide', 'latheRapidToDiameter', 'latheRapidToZ', 'latheStartZ', 'latheRoughingFeed', 'latheRoughingDepth', 'latheFinishFeed', 'latheFinishDepth', 'latheFinishExtraPasses', 'latheFace', 'latheFaceEndDiameter', 'latheTurnAdd', 'latheTurns', 'hookOperationStart', 'hookOperationEnd'] },
};
const groupFields = (ofields) => {
let groups = { '_default': { visible: true, collapsible: false, fields: [] } };
let fields = ofields.slice();
Object.entries(OPERATION_GROUPS).forEach(entry => {
let [key, group] = entry;
if (!groups.hasOwnProperty(key)) {
groups[key] = Object.assign({}, group)
groups[key].fields = []
}
group.fields.forEach(field => {
let index = fields.indexOf(field);
if (index > -1)
groups[key].fields.push(fields.splice(index, 1).pop())
})
})
groups['_default'].fields = fields
return groups;
}
const traverseDocumentTypes = (ids, documents) => {
let result = { images: 0, vectors: 0, other: 0 };
ids.forEach((id) => {
let item = documents.find((item) => item.id == id)
if (item) {
if (item.dataURL) {
result.images++
} else if (item.rawPaths) {
result.vectors++
} else {
result.other++
}
if (item.children.length) {
let { images, vectors, other } = traverseDocumentTypes(item.children, documents)
result.images += images;
result.vectors += vectors;
result.other += other;
}
}
})
return result;
}
class Operation extends React.Component {
componentWillMount() {
this.setType = e => this.props.dispatch(setOperationAttrs({ type: e.target.value }, this.props.op.id));
this.setTypeString = e => this.props.dispatch(setOperationAttrs({ type: e }, this.props.op.id));
this.toggleExpanded = e => this.props.dispatch(setOperationAttrs({ expanded: !this.props.op.expanded }, this.props.op.id));
this.toggleEnabled = e => this.props.dispatch(setOperationAttrs({ enabled: !this.props.op.enabled }, this.props.op.id));
this.remove = e => this.props.dispatch(removeOperation(this.props.op.id));
this.moveUp = e => this.props.dispatch(moveOperation(this.props.op.id, -1));
this.moveDn = e => this.props.dispatch(moveOperation(this.props.op.id, +1));
this.preset = (type, attrs) => this.props.dispatch(setOperationAttrs({ ...attrs,type: type }, this.props.op.id))
this.toggleDocs = e => this.props.dispatch(setOperationAttrs({ _docs_visible: !this.props.op._docs_visible }, this.props.op.id));
this.documentsCount = null;
this.documentTypes = { vectors: 0, images: 0 };
this.availableOps = Object.keys(OPERATION_TYPES);
this.operationGroups = groupFields(OPERATION_TYPES[this.props.op.type].fields)
}
componentWillReceiveProps(nextProps) {
if (nextProps.op.documents.length !== this.documentsCount) {
this.documentsCount = nextProps.op.documents.length
this.documentTypes = traverseDocumentTypes(nextProps.op.documents, nextProps.documents)
this.availableOps = Object.keys(OPERATION_TYPES);
if (nextProps.op.documents.length) {
if (!this.documentTypes.vectors) this.availableOps = this.availableOps.filter(item => item.match(/Raster/gi))
if (!this.documentTypes.images) this.availableOps = this.availableOps.filter(item => !item.match(/^Laser Raster$/gi))
if (!this.availableOps.includes(nextProps.op.type))
this.setTypeString(this.availableOps[0])
}
}
if (nextProps.op.type != this.props.op.type) {
this.operationGroups = groupFields(OPERATION_TYPES[nextProps.op.type].fields)
}
}
render() {
let { op, documents, selected, bounds, dispatch, fillColors, strokeColors, settings } = this.props;
let error;
if (!op.expanded) {
for (let fieldName of OPERATION_TYPES[op.type].fields) {
let field = OPERATION_FIELDS[fieldName];
if (field.check && !field.check(op[fieldName], settings, op) && (!field.condition || field.condition(op, settings))) {
error = <Error operationsBounds={bounds} message="Expand to setup operation" />;
break;
}
}
}
let leftStyle;
if (selected)
leftStyle = { display: 'table-cell', borderLeft: '4px solid blue', borderRight: '4px solid transparent' };
else
leftStyle = { display: 'table-cell', borderLeft: '4px solid transparent', borderRight: '4px solid transparent' };
let header;
if (op.name && op.name.length)
header = (<h5 style={{ marginTop: 0 }} onClick={this.toggleExpanded}>{op.name}</h5>)
let rows = [
<GetBounds Type="div" key="header" style={{ display: 'table-row' }} data-operation-id={op.id}>
<div style={leftStyle} />
<div style={{ display: 'table-cell', cursor: 'pointer' }}>
<i onClick={this.toggleExpanded}
className={op.expanded ? 'fa fa-fw fa-minus-circle' : 'fa fa-fw fa-plus-circle'} />
</div>
<div style={{ display: 'table-cell', width: '100%' }}>
{header}
<span style={{ display: 'flex', justifyContent: 'space-between' }}>
<div style={{ whiteSpace: 'nowrap' }}>
<select className="input-xs" value={op.type} onChange={this.setType}>{Object.keys(OPERATION_TYPES).map(type => <option key={type} disabled={!this.availableOps.includes(type)}>{type}</option>)}</select>
<MaterialPickerButton className="btn btn-success btn-xs" onApplyPreset={this.preset} operation={op} types={this.availableOps}><i className="fa fa-magic"></i></MaterialPickerButton>
<MaterialSaveButton className="btn btn-success btn-xs" onApplyPreset={this.preset} operation={op} types={this.availableOps}><i className="fa fa-floppy-o"></i></MaterialSaveButton>
</div>
<div className="btn-group">
<button className={"btn btn-warning btn-xs " + (op.enabled ? '' : 'btn-off')} onClick={this.toggleEnabled} title="Enable/Disable operation"><i className="fa fa-power-off"></i></button>
<button className="btn btn-default btn-xs " onClick={this.moveUp}><i className="fa fa-arrow-up"></i></button>
<button className="btn btn-default btn-xs" onClick={this.moveDn}><i className="fa fa-arrow-down"></i></button>
<button className="btn btn-danger btn-xs" onClick={this.remove}><i className="fa fa-times"></i></button>
</div>
</span>
{error}
</div>
</GetBounds>
];
if (op.expanded) {
if (!OPERATION_TYPES[op.type].skipDocs)
rows.push(
<div key="docs" style={{ display: 'table-row' }} data-operation-id={op.id}>
<div style={leftStyle} />
<div style={{ display: 'table-cell' }} />
<div style={{ display: 'table-cell', whiteSpace: 'normal' }}>
<table style={{ width: '100%', border: '2px dashed #ccc' }}>
<thead>
<tr><td colSpan='3'><center><small>Drag additional Document(s) here</small><br /><small>to add to existing operation</small></center></td></tr>
</thead>
<tbody style={{ display: op._docs_visible ? 'block' : 'none' }}>
{op.documents.map(id => {
return <Doc key={id} op={op} documents={documents} id={id} isTab={false} dispatch={dispatch} />
})}
</tbody>
<tfoot>
<tr><td colSpan='3' style={{ textAlign: 'right' }}><a onClick={this.toggleDocs}><small>{op._docs_visible ? 'Hide Docs' : 'Show Docs (' + op.documents.length + ')'}</small></a></td></tr>
</tfoot>
</table>
</div>
</div>
);
rows.push(
<div key="attrs" style={{ display: 'table-row' }}>
<div style={leftStyle} />
<div style={{ display: 'table-cell' }} />
<div style={{ display: 'table-cell', whiteSpace: 'normal' }}>
<table>
<tbody>
{Object.entries(this.operationGroups || {}).map((entry) => {
let [key, group] = entry;
let fields = group.fields
.filter(fieldName => { let f = OPERATION_FIELDS[fieldName]; return f && (!f.condition || f.condition(op, settings)); })
.map(fieldName => {
return <Field
key={fieldName} op={op} field={OPERATION_FIELDS[fieldName]} selected={selected}
fillColors={fillColors} strokeColors={strokeColors} settings={settings}
operationsBounds={bounds} setAttrs={setOperationAttrs} dispatch={dispatch} />
})
if (key !== '_default' && group.fields.length) {
if (group.collapsible) {
return <tr key={key}><td><Details className="operationGroup" handler={(<h4>{key}</h4>)}><table><tbody>{fields}</tbody></table> </Details></td></tr>
} else {
return <tr key={key}><td><h4>{key}</h4><table><tbody>{fields}</tbody></table></td></tr>
}
} else {
return <tr key={key}><td><table><tbody>{fields}</tbody></table></td></tr>
}
})}
</tbody>
</table>
</div>
</div>,
);
if (OPERATION_TYPES[op.type].allowTabs) {
rows.push(
<div key="space" style={{ display: 'table-row' }} data-operation-id={op.id} data-operation-tabs={true}>
<div style={leftStyle} />
<div style={{ display: 'table-cell' }}> </div>
</div>
);
if (op.tabDocuments.length) {
rows.push(
<div key="tabLabel" style={{ display: 'table-row' }} data-operation-id={op.id} data-operation-tabs={true}>
<div style={leftStyle} />
<div style={{ display: 'table-cell' }} />
<div style={{ display: 'table-cell' }}><b>Tabs</b></div>
</div>,
<div key="tabDocs" style={{ display: 'table-row' }} data-operation-id={op.id} data-operation-tabs={true}>
<div style={leftStyle} />
<div style={{ display: 'table-cell' }} />
<div style={{ display: 'table-cell', whiteSpace: 'normal' }}>
<table style={{ width: '100%', border: '2px dashed #ccc' }}>
<tbody>
{op.tabDocuments.map(id => {
return <Doc key={id} op={op} documents={documents} id={id} isTab={true} dispatch={dispatch} />
})}
<tr><td colSpan='3'><center><small>Drag additional Document(s) here</small></center></td></tr>
</tbody>
</table>
</div>
</div>,
);
if (OPERATION_TYPES[op.type].tabFields) {
rows.push(
<div key="tabattrs" style={{ display: 'table-row' }}>
<div style={leftStyle} />
<div style={{ display: 'table-cell' }} />
<div style={{ display: 'table-cell', whiteSpace: 'normal' }}>
<table>
<tbody>
{tabFields.map(field => {
return <Field key={field.name} op={op} field={field} selected={selected} operationsBounds={bounds} setAttrs={setOperationAttrs} dispatch={dispatch} />
})}
</tbody>
</table>
</div>
</div>
);
}
}
else {
rows.push(
<div key="tabLabel" style={{ display: 'table-row' }} data-operation-id={op.id} data-operation-tabs={true}>
<div style={leftStyle} />
<div style={{ display: 'table-cell' }} />
<div style={{ display: 'table-cell', border: '2px dashed #ccc' }}><b>Drag document(s) here to create tabs</b></div>
</div>,
);
}
} // types[op.type].allowTabs
} // op.expanded
return <div className={"operation-row " + (op.enabled ? "" : "disabled")} >{rows}</div>;
}
}; // Operation
Operation = withStoredBounds(Operation);
class Operations extends React.Component {
render() {
let { operations, currentOperation, documents, dispatch, bounds, settings } = this.props;
let fillColors = [];
let strokeColors = [];
let addColor = (colors, color) => {
let value = JSON.stringify(color);
if (!colors.find(c => c.value === value))
colors.push({ value: value, color: color });
}
for (let doc of documents) {
if (doc.rawPaths) {
if (hasClosedRawPaths(doc.rawPaths))
addColor(fillColors, doc.fillColor);
addColor(strokeColors, doc.strokeColor);
}
}
for (let op of operations) {
if (op.filterFillColor)
addColor(fillColors, op.filterFillColor);
if (op.filterStrokeColor)
addColor(strokeColors, op.filterStrokeColor);
}
return (
<div style={this.props.style}>
<div style={{ backgroundColor: '#eee', padding: '20px', border: '3px dashed #ccc', marginBottom: 5 }} data-operation-id="new">
<b>Drag document(s) here to add</b>
<NoOperationsError operationsBounds={bounds} documents={documents} operations={operations} />
</div>
<OperationToolbar />
<GetBounds Type={'div'} className="operations" style={{ height: "100%", overflowY: "auto" }} >
{operations.map(o =>
<Operation
key={o.id} op={o} selected={currentOperation === o.id} documents={documents}
fillColors={fillColors} strokeColors={strokeColors} settings={settings}
dispatch={dispatch} />
)}
</GetBounds>
</div >
);
}
};
Operations = connect(
({ operations, currentOperation, documents, settings }) => ({ operations, currentOperation, documents, settings }),
)(withGetBounds(Operations));
export { Operations };
class OperationToolbar extends React.Component {
constructor(props) {
super(props);
this.handleAddSingle.bind(this)
this.handleAddMultiple.bind(this)
this.handleClearAll.bind(this)
}
handleAddSingle() {
this.props.createSingle(selectedDocuments(this.props.documents));
}
handleAddMultiple() {
this.props.createMultiple(selectedDocuments(this.props.documents));
}
handleClearAll() {
this.props.clearAll();
}
render() {
let hasSelected = this.props.documents.some((item) => item.selected)
let settings = this.props.settings;
return <ButtonToolbar style={{ paddingBottom: "5px", marginBottom: "5px", borderBottom: "1px solid #eee" }}>
<Button disabled={!hasSelected && !settings.toolCreateEmptyOps} onClick={(e) => { this.handleAddSingle() }} bsSize="xsmall" bsStyle="info" title="Create a single operation with the selected documents"><Icon name="object-group" /> Create Single </Button>
<Button disabled={!hasSelected} onClick={(e) => { this.handleAddMultiple() }} bsSize="xsmall" bsStyle="info" title="Create operations with each of the selected documents"><Icon name="object-ungroup" /> Create Multiple </Button>
<Button disabled={!this.props.operations.length} onClick={e => this.handleClearAll()} bsStyle="danger" bsSize="xsmall" title="Clear all operations" >Clear All</Button>
</ButtonToolbar>
}
}
OperationToolbar = connect(
(state) => { return { documents: state.documents, operations: state.operations, settings: state.settings } },
(dispatch) => {
return {
createSingle: (documents) => { dispatch(addOperation({ documents })) },
createMultiple: (documents) => { documents.forEach((doc) => { dispatch(addOperation({ documents: [doc] })) }) },
clearAll: () => {
confirm("Are you sure?", (data) => {
if (data) dispatch(clearOperations());
})
}
}
}
)(OperationToolbar);
|
packages/cf-component-modal/src/ModalBody.js | jroyal/cf-ui | import React from 'react';
import PropTypes from 'prop-types';
class ModalBody extends React.Component {
render() {
return (
<div className="cf-modal__body">
{this.props.children}
</div>
);
}
}
ModalBody.propTypes = {
children: PropTypes.node
};
export default ModalBody;
|
lib/TextArea/stories/BasicUsage.js | folio-org/stripes-components | /**
* TextArea: Basic Usage
*/
import React from 'react';
import TextArea from '../TextArea';
const BasicUsage = () => (
<div>
<TextArea
label="Field with label"
placeholder="Placeholder Text"
required
/>
<TextArea
value="This field is disabled"
label="Disabled field"
disabled
/>
<TextArea
value="This field is read only"
label="Read only field"
readOnly
/>
<TextArea
value="This field is required"
label="Required field"
required
/>
<TextArea
validStylesEnabled
valid
dirty
label="Field with validation success"
/>
<TextArea
value="Wrong value.."
onChange={() => {}}
error="Here is an error message"
label="Field with a validation error"
/>
<TextArea
value="Not entirely valid value.."
onChange={() => {}}
warning="Here is a warning"
dirty
label="Field with validation warning"
/>
</div>
);
export default BasicUsage;
|
app/packs/src/components/structure_editor/StructureEditorContent.js | ComPlat/chemotion_ELN | import React from 'react';
import scriptLoader from 'react-async-script-loader';
class StructureEditorContent extends React.Component {
constructor(props) {
super(props);
const { completionCallback, errorCallback } = this.props;
this.state = {
completionCallback, errorCallback
}
this.attachEditor = this.attachEditor.bind(this)
}
UNSAFE_componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
if (isScriptLoaded && !this.props.isScriptLoaded) { // load finished
if (isScriptLoadSucceed) {
setTimeout(this.attachEditor, 3000);
}
}
}
componentDidMount() {
const { isScriptLoaded, isScriptLoadSucceed } = this.props
if (isScriptLoaded && isScriptLoadSucceed) {
this.attachEditor();
this.attachEditor();
}
}
attachEditor() {
const { completionCallback, errorCallback } = this.props;
perkinelmer.ChemdrawWebManager.attach({
id: 'chemdrawjs-container',
config: window.userConfiguration,
element: this.chemdrawcont,
callback: ()=> alert('done'),
errorCallback: ()=> alert('de'),
licenseUrl: 'license.xml',
// loadConfigFromUrl: 'cdjs/chemdrawweb/configuration.json',
// preservePageInfo: false,
// viewonly: true,
});
}
render() {
return (
<div
ref={(input) => {this.chemdrawcont = input }}
// id="chemdrawjs-container"
style={{ position: 'absolute', left: 0, top: 0, width: '100%', height: '70vh' }}
/>
);
}
}
export default scriptLoader(
[
"cdjs/chemdrawweb/chemdrawweb.js",
]
)(StructureEditorContent)
// export default StructureEditorContent;
|
src/header/MobileHeader.js | sk1981/react-header | import React from 'react';
import Logo from '../Logo';
import NavigationList from '../navigation/NavigationList';
import VerticalSlider from '../sliders/VerticalSlider';
import ReactHelper from '../utils/ReactHelper'
/**
* Gets the child components for Mobile Menu
*
* It iterates over all child, filters out the logo component (as Logo needs to be displayed on top)
* and adds them to the menu
*
* @param childArray
* @param sizeProps
* @returns {*}
*/
function getChildComponents(childArray, sizeProps) {
return childArray.filter(child => child.type !== Logo)
.map((child, index) => child.type === NavigationList ?
ReactHelper.getMainNav(child, sizeProps) :
React.cloneElement(child, {key: index}));
}
/**
* Gets the title component that is displayed on the vertical slider
*
* In this case we just display the Logo
*
*/
function getTitleComponent(childArray) {
const logo = childArray.filter(child => child.type === Logo);
return logo.length > 0 ? logo[0] : undefined;
}
/**
* Header element for smaller screens, usually found on mobile devices
*/
const MobileHeader = ({children, windowWidth, windowHeight, headerHeight, mode}) => {
const childArray = React.Children.toArray(children);
const titleComponent = getTitleComponent(childArray);
const sizeProps = {
windowWidth,
windowHeight,
headerHeight,
mode
};
const childComponents = getChildComponents(childArray, sizeProps);
return (
<VerticalSlider {...sizeProps} titleComponent={titleComponent}>
{childComponents}
</VerticalSlider>
);
};
MobileHeader.propTypes = {
children: React.PropTypes.oneOfType([
React.PropTypes.element,
React.PropTypes.array
]),
windowWidth: React.PropTypes.number,
windowHeight: React.PropTypes.number,
headerHeight: React.PropTypes.number,
mode: React.PropTypes.oneOf(['desktop', 'mobile'])
};
export default MobileHeader
|
apps/marketplace/components/Brief/SummaryComparison.js | AusDTO/dto-digitalmarketplace-frontend | import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
import AUheading from '@gov.au/headings/lib/js/react.js'
import PageHeader from 'marketplace/components/PageHeader/PageHeader'
import localStyles from './SummaryComparison.scss'
import styles from '../../main.scss'
const SummaryComparison = props => {
window.scrollTo(0, 0)
const { brief, previous, updated } = props
const previousSummaryIsLonger = previous.length >= updated.length
return (
<div className={localStyles.container}>
<PageHeader actions={[]} organisation={`${brief.title} (${brief.id})`} title="Summary updates" />
<div className={`row ${styles.hideMobile} ${styles.marginTop2}`}>
<div className={`col-md-6 ${localStyles.previous} ${previousSummaryIsLonger ? styles.greyBorderRight1 : ''}`}>
<AUheading level="2" size="xs">
Previous summary:
</AUheading>
<p className={styles.whiteSpacePreWrap}>{previous}</p>
</div>
<div className={`col-md-6 ${localStyles.updated} ${previousSummaryIsLonger ? '' : styles.greyBorderLeft1}`}>
<AUheading level="2" size="xs">
Updated summary:
</AUheading>
<p className={styles.whiteSpacePreWrap}>{updated}</p>
</div>
</div>
<div className={`row ${styles.hideDesktop}`}>
<div className={`col-xs-12 ${localStyles.previous}`}>
<AUheading level="2" size="md">
Previous summary:
</AUheading>
<p className={styles.whiteSpacePreWrap}>{previous}</p>
</div>
<div className={`col-xs-12 ${localStyles.updated} ${styles.greyBorderTop1}`}>
<AUheading level="2" size="md">
Updated summary:
</AUheading>
<p className={styles.whiteSpacePreWrap}>{updated}</p>
</div>
</div>
<div className={`row ${styles.marginTop2}`}>
<div className="col-xs-12">
<Link to="/" className={`au-btn au-btn--tertiary ${localStyles.inlineLink}`}>
Return to History of updates
</Link>
</div>
</div>
</div>
)
}
SummaryComparison.defaultProps = {
brief: {},
previous: '',
updated: ''
}
SummaryComparison.propTypes = {
brief: PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired
}).isRequired,
previous: PropTypes.string.isRequired,
updated: PropTypes.string.isRequired
}
export default SummaryComparison
|
components/main/SidebarContent.js | HelloTangible/Rocket-Web | import React from 'react'
import { NavItem } from 'rebass'
import { FaTasks } from 'react-icons/lib/fa'
import { MdCloud, MdCreditCard, MdPerson, MdPhonelinkSetup, MdTimeline } from 'react-icons/lib/md'
export default (
<div className='sidebar-icons'>
<style jsx global>{`
.icon {
font-size: 3em;
padding-right: 0;
}
`}</style>
<NavItem href='/devices' title='Devices'>
<MdPhonelinkSetup className='icon' />
</NavItem>
<NavItem href='/simulations' title='Simulations'>
<FaTasks className='icon' />
</NavItem>
<NavItem href='/runs' title='Runs'>
<MdCloud className='icon' />
</NavItem>
<NavItem href='/reports' title='Reports'>
<MdTimeline className='icon' />
</NavItem>
<NavItem href='/account' title='Account'>
<MdPerson className='icon' />
</NavItem>
<NavItem href='/billing' title='Billing'>
<MdCreditCard className='icon' />
</NavItem>
</div>
)
|
packages/material-ui-icons/src/PlayCircleFilled.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PlayCircleFilled = props =>
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z" />
</SvgIcon>;
PlayCircleFilled = pure(PlayCircleFilled);
PlayCircleFilled.muiName = 'SvgIcon';
export default PlayCircleFilled;
|
app/components/Console.js | dikalikatao/fil | import _ from 'underscore';
import React from 'react';
import OutputLine from 'components/OutputLine';
import ConsoleToolbar from 'components/ConsoleToolbar';
import ErrorLine from 'components/ErrorLine';
export default class Console extends React.Component {
renderLine(line, i) {
return <OutputLine
output={line}
key={i} />
}
render() {
var block = "console",
error = this.props.error;
return (
<div className={block}>
<ConsoleToolbar
className={block + "__toolbar"}
onRun={this.props.onRun} />
<div className={block + "__output"}>
{this.props.lines.map(this.renderLine.bind(this))}
</div>
{error && <ErrorLine error={error} />}
</div>
);
}
}
|
pages/404.js | ahw/superflash.cards | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { Component } from 'react';
export default class extends Component {
render() {
return (
<div>
<h1>Not Found</h1>
<p>The page you're looking for was not found.</p>
</div>
);
}
}
|
src/containers/Gridboard/Gridboard.js | petorious/dmprov-app | import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import PropTypes from 'prop-types';
import {Card, CardActions, CardHeader, CardTitle, CardText} from 'material-ui/Card';
import { setPersistentValue } from '../../store/persistentValues/actions';
import {Responsive, WidthProvider} from 'react-grid-layout';
import { onLayoutChange } from '../../store/grids/actions';
import FontIcon from 'material-ui/FontIcon';
import FlatButton from 'material-ui/FlatButton';
import {withRouter} from 'react-router-dom';
import {List, ListItem } from 'material-ui/List';
import { withFirebase } from 'firekit';
import muiThemeable from 'material-ui/styles/muiThemeable';
import { injectIntl } from 'react-intl';
const ResponsiveReactGridLayout = WidthProvider(Responsive);;
const styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
},
card:{
backgroundColor: "black",
color: 'muiTheme.palette.primaryColor',
},
gridList: {
width: 500,
height: 500,
overflowY: 'auto',
marginBottom: 24,
},
};
let layoutToSave=undefined;
class Gridboard extends Component{
constructor(props) {
super(props)
};
componentWillMount(){
}
componentDidMount() {
const { watchList, firebaseApp, styles, auth, uid, path }=this.props;
let layoutRef=firebaseApp.database().ref('campaign_layouts')
.orderByChild('currentCampaignUid')
.equalTo("-KvecdzKQJ6qlr6U79Xc")
// .limitToFirst(20);
watchList(layoutRef);
let assetRef=firebaseApp.database().ref('assets')
.orderByChild('layoutUid')
.equalTo("-L0J5Fu99MIGYopf7X78")
watchList(assetRef);
}
renderGridList(assets) {
const {history, currentCampaignUid, list, match} =this.props;
const uid=match.params.uid;
if(assets===undefined){
return <div></div>
}
return
_.map(assets, (val, i) => {
return <div key={val.key}
>
<ListItem
key={val.key}
primaryText={val.asset_name}
secondaryText={val.asset_slug}
id={val.key}
/>
</div>
});
}
render( i, keys){
function handleLayoutChange(layout){
layoutToSave=layout;
};
const { browser, firebaseApp, muiTheme, currentCampaignUid, campaign_layouts, assets, match, grids, gridboard, layoutRef, onLayoutChange} = this.props
const uid=match.params.uid;
let assetSource=[];
if(assets){
assetSource=assets
// .filter(asset=>{
// console.log("asset authorUid ", asset.val.authorUid)
// return asset.val.authorUid===uid
// })
.map(asset=>{
console.log('filtered asset', asset)
return {
id: asset.key,
key: asset.val.key,
name: asset.val.asset_name,
title: asset.val.title,
description: asset.val.description}
})
};
let layout=[];
if(campaign_layouts){
layout=campaign_layouts
this.props.campaign_layouts
.filter(campaign_layout=>{
layout=campaign_layout.val.layout1
})
// .map(
// (campaign_layout, index) => {
// return{
// val: campaign_layout.val.layout1
// }
// })
};
// const menuItems=[
// { key: 'save',
// text:messages.save||'save',
// onTouchTap: ()=>onLayoutChange(layoutToSave)
// },
// {
// key: 'reset',
// text:messages.reset||'reset',
// onTouchTap: ()=>onLayoutChange(undefined)
// }
// ];
const widgetData = [
{
img: 'static/vegetables-790022_640.jpg',
title: 'Breakfast',
author: 'jill111',
},
{
img: 'static/burger-827309_640.jpg',
title: 'Tasty burger',
author: 'pashminu',
},
{
img: 'static/honey-823614_640.jpg',
title: 'Honey',
author: 'fancycravel',
},
{
img: 'static/water-plant-821293_640.jpg',
title: 'Water plant',
author: 'BkrmadtyaKarki',
},
];
var layouts = Gridboard.layout?{lg:Gridboard.layout}:{lg:layout}
return (
<div>
<ResponsiveReactGridLayout
isDraggable={browser.greaterThan.medium}
isResizable={browser.greaterThan.medium}
onLayoutChange={handleLayoutChange}
className="layout"
rowHeight={60}
verticalCompact={false}
layouts={layouts}
style={styles}
autoSize={true}
breakpoints={{lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0}}
cols={{lg: 24, md: 20, sm: 12, xs: 8, xxs: 4}}
ref={(field) => { this.list = field; }}
>
{assetSource.map((val, index) => {
return (
<Card key={val.id} uid={match.params.uid}>
{this.renderGridList(assets)}
</Card>
)
}
)}
</ResponsiveReactGridLayout>
</div>
);
}
};
Gridboard.propTypes = {
onLayoutChange: PropTypes.func.isRequired,
gridboard: PropTypes.object,
browser: PropTypes.object.isRequired,
campaign_layouts: PropTypes.array.isRequired,
assets: PropTypes.array.isRequired,
}
function mapStateToProps(state, ownProps) {
const {browser, intl , lists, gridboard, uid, key, currentCampaignUid} = state;
const { match } = ownProps;
const layoutsPath=`campaign_layouts/${uid}/`;
const campaign_layouts=lists[layoutsPath]?lists[layoutsPath]:[];
return {
gridboard: gridboard,
browser: browser,
//this list imports into the redux logger
campaign_layouts: lists.campaign_layouts,
assets: lists.assets,
};
}
const mapDispatchToProps = (dispatch) => {
return {
onLayoutChange:(layout)=>{
dispatch(onLayoutChange(layout));
},
}
}
export default connect(
mapStateToProps, { setPersistentValue, onLayoutChange }
)(injectIntl(muiThemeable()(withRouter(withFirebase(Gridboard))))); |
src/components/Header.js | a-type/redux-data-table | import React from 'react';
import SortArrow from './SortArrow';
const Header = ({ columnKey, handleClick, sortOrder, sortable }) => (
<th style={{ cursor: sortable ? 'pointer' : 'default' }} onClick={handleClick}>
{columnKey}
{sortable ? <SortArrow order={sortOrder} /> : null}
</th>
);
export default Header; |
src/components/List/SkeletonList.js | flashrecruit/belay | import React from 'react';
import Loading from '../Loading/Loading.js';
class SkeletonList extends React.Component {
render() {
var skeletonItem = { height: '38px' };
return (
<div className="list-group">
<div className="list-group__item">
<div className="skeleton-text"/>
</div>
<div className="list-group__item">
<div className="skeleton-text"/>
</div>
<div className="list-group__item">
<div className="skeleton-text"/>
</div>
<div className="list-group__item">
<div className="skeleton-text"/>
</div>
<div className="list-group__item">
<div className="skeleton-text"/>
</div>
</div>
);
}
}
export default SkeletonList;
|
JS/Classes/Module/Navigator/NavigatorExampleWithNavigationBar1.js | joggerplus/ReactNativeRollingExamples | 'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
Navigator,
Image
} from 'react-native';
var NavigatorExampleWithThirdNavBar = require('./NavigatorExampleWithThirdNavBar');
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, navState) {
return (
<TouchableOpacity
style={{flex: 1, justifyContent: 'center',backgroundColor:'white'}}
onPress={() => navigator.parentNavigator.pop()}>
<Image
source={require('image!backArrow')}
style={{width: 30, height:30,margin:15,tintColor: 'black'}}/>
</TouchableOpacity>
);
},
RightButton(route, navigator, index, navState) {
return null;
},
Title(route, navigator, index, navState) {
return (
<Text style={{color: 'black', margin: 10, fontSize: 20}}>
NavigationBar1
</Text>
);
}
};
class NavigatorExampleWithNavigationBar1 extends Component {
constructor(props) {
super(props);
this.onPressAction = this.onPressAction.bind(this);
this.renderScene = this.renderScene.bind(this);
}
onPressAction() {
this.props.navigator.push({
title: "ThirdNavBar",
component: NavigatorExampleWithThirdNavBar,
});
}
renderScene(route, navigator) {
return (
<View style={{ flex: 1, }}>
<View style={styles.container}>
<TouchableOpacity onPress={()=>this.onPressAction()}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
Touch me to next
</Text>
</TouchableOpacity>
</View>
</View>
);
}
render() {
return (<Navigator renderScene={this.renderScene}
navigator={this.props.navigator}
navigationBar={
<Navigator.NavigationBar style={{backgroundColor: 'white'}}
routeMapper={NavigationBarRouteMapper} />
}/>);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
fontSize: 20,
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
module.exports = NavigatorExampleWithNavigationBar1; |
docs/app/Examples/elements/Segment/Types/SegmentExampleRaised.js | koenvg/Semantic-UI-React | import React from 'react'
import { Segment } from 'semantic-ui-react'
const SegmentExampleRaised = () => (
<Segment raised>
Pellentesque habitant morbi tristique senectus.
</Segment>
)
export default SegmentExampleRaised
|
client/Contests/ContestNavigator.js | rystecher/senior-design | import React from 'react';
import { Link } from 'react-router';
import './contestnavigator.css';
import { logout } from './Login/actions/authActions';
import { connect } from 'react-redux';
import { getContestInfo } from './ContestActions';
class ContestNavigator extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
logout(e) {
this.props.logout();
}
/**
* get contest name for home link
*/
componentDidMount() {
if (this.props.contestId != 'wont be used') {
getContestInfo(this.props.contestId).then(res => {
if (res.name) {
this.setState({ name: res.name });
}
});
}
}
render() {
const { contestId, page, teamId, username, userRole } = this.props;
let navLinks = null;
if ('admin' === userRole) {
navLinks = (
<ul className='nav navbar-nav navbar-toggler-left'>
<li className={'home' === page ? 'nav-item active' : 'nav-item'}>
<Link
className='nav-link'
to={`/contest/${contestId}/home`}
>{this.state.name}</Link>
</li>
<li className={'problems' === page ? 'nav-item active' : 'nav-item'}>
<Link
className='nav-link'
to={`/contest/${contestId}/problems/add`}
>Problems</Link>
</li>
<li className={'scoreboard' === page ? 'nav-item active' : 'nav-item'}>
<Link
className='nav-link'
to={`/contest/${contestId}/scoreboard`}
>ScoreBoard</Link>
</li>
<li className={'submissions' === page ? 'nav-item active' : 'nav-item'}>
<Link
className='nav-link'
to={`/contest/${contestId}/submissions`}
>Submissions</Link>
</li>
</ul>
);
} else if ('participant' === userRole) {
navLinks = (
<ul className='nav navbar-nav navbar-toggler-left'>
<li className={'home' === page ? 'nav-item active' : 'nav-item'}>
<Link
className='nav-link'
to={`/contest/${contestId}/home`}
>{this.state.name}</Link>
</li>
<li className={'problems' === page ? 'nav-item active' : 'nav-item'}>
<Link
className='nav-link'
to={`/contest/${contestId}/problems/${teamId}/1`}
>Problems</Link>
</li>
<li className={'scoreboard' === page ? 'nav-item active' : 'nav-item'}>
<Link
className='nav-link'
to={`/contest/${contestId}/scoreboard/${teamId}`}
>ScoreBoard</Link>
</li>
<li className={'submissions' === page ? 'nav-item active' : 'nav-item'}>
<Link
className='nav-link'
to={`/contest/${contestId}/submissions/${teamId}`}
>Submissions</Link>
</li>
</ul>
);
}
return (
<nav className='navbar navbar-inverse contest-navigator'>
<div className='navbar-toggleable-md'>
{navLinks}
<ul className='nav navbar-nav navbar-toggler-right'>
<li className='nav-item'>
<Link to={'/profile'} className='nav-link'>
<span className='glyphicon glyphicon-user' />{username}
</Link>
</li>
<li className='nav-item'>
<Link to={'/'} className='nav-link' onClick={this.logout.bind(this)}>
Logout
</Link>
</li>
</ul>
</div>
</nav>
);
}
}
ContestNavigator.propTypes = {
contestId: React.PropTypes.string.isRequired,
page: React.PropTypes.oneOf([
'home', 'problems', 'scoreboard', 'submissions', 'none',
]).isRequired,
teamId: React.PropTypes.string,
username: React.PropTypes.string.isRequired,
userRole: React.PropTypes.oneOf(['admin', 'participant', 'none']).isRequired,
};
function mapStateToProps(state) {
return {
auth: state.auth,
};
}
export default connect(mapStateToProps, { logout })(ContestNavigator);
|
src/Idea/ConvertIdeaDialog.js | mkermani144/wanna | import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import DatePicker from 'material-ui/DatePicker';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
import { green600, grey50 } from 'material-ui/styles/colors';
import persianUtils from 'material-ui-persian-date-picker-utils';
import { HotKeys } from 'react-hotkeys';
import {
parse,
dayStart,
todayStart,
dayEnd,
} from '../lib/date';
import './ConvertIdeaDialog.css';
class ConvertIdeaDialog extends Component {
state = {
estimationValue: 1,
repetitionValue: 1,
task: '',
start: todayStart(),
end: null,
estimation: '',
repetition: '',
};
keyMap = {
confirmConvertIdeaAndFinish: 'shift+enter',
confirmConvertIdeaAndContinue: 'enter',
};
buttonDisabled = () => !(
this.state.task
&& this.state.end
&& this.state.estimation
&& /^[0-9]*$/.test(this.state.estimation)
&& /^[0-9]*$/.test(this.state.repetition)
);
handleEstimationMenuChange = (e, i, value) => {
this.setState({
estimationValue: value,
});
}
handleRepetitionMenuChange = (e, i, value) => {
this.setState({
repetitionValue: value,
});
}
handleTaskChange = (e) => {
this.setState({
task: e.target.value,
});
}
handleStartChange = (e, start) => {
this.setState({
start: dayStart(parse(start)),
});
}
handleEndChange = (e, end) => {
this.setState({
end: dayEnd(parse(end)),
});
}
handleEstimationChange = (e) => {
this.setState({
estimation: e.target.value,
});
}
handleRepetitionChange = (e) => {
this.setState({
repetition: e.target.value,
});
}
handleRequestClose = () => {
this.setState({
estimationValue: 1,
repetitionValue: 1,
task: '',
start: todayStart(),
end: null,
estimation: '',
repetition: '',
});
this.props.onRequestClose();
}
handleRequestConvert = () => {
this.props.onRequestConvert(this.state);
this.setState({
estimationValue: 1,
repetitionValue: 1,
task: '',
start: todayStart(),
end: null,
estimation: '',
repetition: '',
});
}
handleRequestFinish = () => {
this.props.onRequestConvert && this.props.onRequestConvert(this.state);
this.props.onRequestDelete && this.props.onRequestDelete();
this.props.onRequestClose && this.props.onRequestClose();
this.setState({
estimationValue: 1,
repetitionValue: 1,
task: '',
start: todayStart(),
end: null,
estimation: '',
repetition: '',
});
}
render() {
const actions = [
<FlatButton
id="add-and-finish"
label="Add and finish"
primary
disabled={this.buttonDisabled()}
onClick={this.handleRequestFinish}
/>,
<FlatButton
id="add-and-continue"
label="Add and continue"
primary
disabled={this.buttonDisabled()}
onClick={this.handleRequestConvert}
/>,
<FlatButton
label="Cancel"
primary
onClick={this.handleRequestClose}
/>,
];
const dialogTitleStyle = {
backgroundColor: green600,
color: grey50,
cursor: 'default',
};
const textFieldStyles = {
underlineFocusStyle: {
borderColor: green600,
},
floatingLabelFocusStyle: {
color: green600,
},
};
const datePickerStyles = {
textFieldStyle: {
flex: 1,
},
};
const { DateTimeFormat } = global.Intl;
const localeProps = this.props.calendarSystem === 'fa-IR' ?
{ utils: persianUtils, DateTimeFormat } :
{};
const handlers = {
confirmConvertIdeaAndFinish: () => {
!this.buttonDisabled() && this.handleRequestFinish();
},
confirmConvertIdeaAndContinue: () => {
!this.buttonDisabled() && this.handleRequestAdd();
},
};
return (
<Dialog
className="ConvertIdeaDialog"
title="Convert idea"
actions={actions}
titleStyle={dialogTitleStyle}
open={this.props.open}
onRequestClose={this.props.onRequestClose}
>
<br />
<p>Converting idea: {this.props.idea}</p>
<br />
<div className="textfields">
<HotKeys
keyMap={this.keyMap}
handlers={handlers}
>
<TextField
floatingLabelText="Task title"
fullWidth
underlineFocusStyle={textFieldStyles.underlineFocusStyle}
floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
onChange={this.handleTaskChange}
autoFocus
value={this.state.task}
/>
<div className="datepicker" id="start">
<DatePicker
defaultDate={new Date()}
hintText="Start"
autoOk
locale={this.props.calendarSystem}
{...localeProps}
firstDayOfWeek={this.props.firstDayOfWeek}
textFieldStyle={datePickerStyles.textFieldStyle}
minDate={new Date()}
onChange={this.handleStartChange}
/>
</div>
<div className="datepicker" id="end">
<DatePicker
hintText="End"
autoOk
locale={this.props.calendarSystem}
{...localeProps}
firstDayOfWeek={this.props.firstDayOfWeek}
textFieldStyle={datePickerStyles.textFieldStyle}
minDate={new Date(this.state.start)}
onChange={this.handleEndChange}
/>
</div>
<div className="row">
<TextField
id="estimated-time"
floatingLabelText="Estimated time"
underlineFocusStyle={textFieldStyles.underlineFocusStyle}
floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
onChange={this.handleEstimationChange}
value={this.state.estimation}
errorText={
/^[0-9]*$/.test(this.state.estimation) ?
'' :
'Estimated time should be a number'
}
/>
<DropDownMenu
value={this.state.estimationValue}
onChange={this.handleEstimationMenuChange}
>
<MenuItem value={1} primaryText="Minutes" />
<MenuItem value={60} primaryText="Hours" />
</DropDownMenu>
</div>
<div className="row">
<TextField
floatingLabelText="Repetition period"
underlineFocusStyle={textFieldStyles.underlineFocusStyle}
floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
onChange={this.handleRepetitionChange}
value={this.state.repetition}
errorText={
/^[0-9]*$/.test(this.state.repetition) ?
'' :
'Repetition period should be a number'
}
/>
<DropDownMenu
value={this.state.repetitionValue}
onChange={this.handleRepetitionMenuChange}
>
<MenuItem value={1} primaryText="Days" />
<MenuItem value={7} primaryText="Weeks" />
</DropDownMenu>
</div>
</HotKeys>
</div>
</Dialog>
);
}
}
export default ConvertIdeaDialog;
|
src/svg-icons/av/closed-caption.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvClosedCaption = (props) => (
<SvgIcon {...props}>
<path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 7H9.5v-.5h-2v3h2V13H11v1c0 .55-.45 1-1 1H7c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H18v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1z"/>
</SvgIcon>
);
AvClosedCaption = pure(AvClosedCaption);
AvClosedCaption.displayName = 'AvClosedCaption';
AvClosedCaption.muiName = 'SvgIcon';
export default AvClosedCaption;
|
electron/renderer/src/components/IsOnline.js | ConorIA/wire-desktop | /*
* Wire
* Copyright (C) 2017 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
import React, { Component } from 'react';
import './IsOnline.css';
class IsOnline extends Component {
constructor(props) {
super(props);
this.state = {
isOnline: navigator.onLine,
};
}
componentDidMount() {
if (this.state.isOnline === false) {
window.addEventListener('online', (event) => {
this.setState({ isOnline: true });
}, { once: true });
}
}
render() {
return this.state.isOnline ? this.props.children : <div className="IsOnline">No Internet</div>;
}
}
export default IsOnline;
|
examples/Nav.js | ornl-sava/vis-react-components | import React from 'react'
import { NavLink } from 'react-router-dom'
// Topics need some upkeep, removing from the example until we can re-Factor
// should be to /topics
class Nav extends React.Component {
render () {
return (
<nav role='navigation'>
<ul>
<li><NavLink to='/histogram' activeClassName='active'>Histogram</NavLink></li>
<li><NavLink to='/heatmap' activeClassName='active'>Heatmap</NavLink></li>
<li><NavLink to='/scatterplot' activeClassName='active'>Scatterplot</NavLink></li>
<li><NavLink to='/choropleth' activeClassName='active'>Choropleth Map</NavLink></li>
<li><NavLink to='/scatterHeatmap' activeClassName='active'>Scatter Heatmap Hybrid</NavLink></li>
<li><NavLink to='/circumshaker' activeClassName='active'>Circumshaker</NavLink></li>
<li><NavLink to='/forceDirected' activeClassName='active'>Force-Directed</NavLink></li>
<li><NavLink to='/treemap' activeClassName='active'>Treemap</NavLink></li>
<li><NavLink to='/horizonGraph' activeClassName='active'>Horizon Graph</NavLink></li>
<li><NavLink to='/summaryTimeline' activeClassName='active'>Summary Timeline</NavLink></li>
</ul>
</nav>
)
}
}
export default Nav
|
fusion/Typing.js | pagesource/fusion | import React from 'react';
import { keyframes } from 'emotion';
import styled from 'react-emotion';
import PropTypes from 'prop-types';
import { withTheme } from 'theming';
const type = keyframes`
from { width: 0; }
`;
const TypingDiv = styled('p')`
font-family: 'Courier';
font-size: 20px;
font-weight: bold;
margin: 10px 0 0 10px;
white-space: nowrap;
overflow: hidden;
width: 30em;
animation: ${type} 4s 1s ease infinite;
`;
const Typing = ({ text }) => <TypingDiv>{text}</TypingDiv>;
/* Props Check */
Typing.propTypes = {
/**
* Typing text
*/
text: PropTypes.string,
};
/* Deafult Props */
Typing.defaultProps = {
text: 'Typing text content',
};
export default withTheme(Typing);
|
examples/popular-products/index.js | cycgit/dva | import './index.html';
import React from 'react';
import dva from '../../src/index';
import { connect } from '../../index';
import { Router, Route, useRouterHistory } from '../../router';
import fetch from '../../fetch';
import ProductList from './components/ProductList/ProductList';
import styles from './index.less';
// 1. Initialize
const app = dva();
// 2. Model
app.model({
namespace: 'products',
state: {
list: [],
loading: false,
},
subscriptions: {
setup({ dispatch }) {
dispatch({ type: 'query' });
},
},
effects: {
*query(_, { put }) {
const { success, data } = yield fetch(`/api/products`).then(res => res.json());
if (success) {
yield put({
type: 'querySuccess',
payload: data,
});
}
},
*vote({ payload }, { put}) {
const { success } = yield fetch(`/api/products/vote?id=${payload}`).then(res => res.json());
if (success) {
yield put({
type: 'voteSuccess',
payload,
});
}
},
},
reducers: {
query(state) {
return { ...state, loading: true, };
},
querySuccess(state, { payload }) {
return { ...state, loading: false, list: payload };
},
vote(state) {
return { ...state, loading: true };
},
voteSuccess(state, { payload }) {
const newList = state.list.map(product => {
if (product.id === payload) {
return { ...product, vote:product.vote + 1 };
} else {
return product;
}
});
return { ...state, list: newList, loading: false };
},
},
});
// 3. View
const App = connect(({products}) => ({
products
}))(function(props) {
return (
<div className={styles.productPage}>
<h2>Popular Products</h2>
<ProductList
data={props.products.list}
loading={props.products.loading}
dispatch={props.dispatch}
/>
</div>
);
});
// 4. Router
app.router(({ history }) =>
<Router history={history}>
<Route path="/" component={App} />
</Router>
);
// 5. Start
app.start('#root');
|
lib/next/index.js | lukemorton/republic | import React from 'react'
import wrapPage from './wrapPage'
import Link from './Link'
import createRedirectTo from './createRedirectTo'
import RepublicBase, { route } from '../republic'
export { wrapPage, Link, route }
export default class Republic extends RepublicBase {
routes () {
return this._routes.map((route) => {
return {
...route,
originalHandler: route.handler,
handler: wrapNextMagic(this, route.handler)
}
})
}
page (Component) {
return wrapPage(this, Component)
}
buildLink (props) {
return <Link {...props} />
}
}
function wrapNextMagic (app, originalHandler) {
function wrappedHandler (params, ctx = {}) {
const redirectTo = createRedirectTo(app, ctx.res)
return originalHandler(params, { ...ctx, redirectTo })
}
wrappedHandler.method = originalHandler.method
wrappedHandler.path = originalHandler.path
return wrappedHandler
}
|
src/Parser/AfflictionWarlock/Modules/Talents/DeathsEmbrace.js | Yuyz0112/WoWAnalyzer | import React from 'react';
import Module from 'Parser/Core/Module';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import { UNSTABLE_AFFLICTION_DEBUFF_IDS } from '../../Constants';
import getDamageBonus from '../WarlockCore/getDamageBonus';
const abilitiesAffected = [
SPELLS.AGONY.id,
SPELLS.CORRUPTION_DEBUFF.id,
SPELLS.PHANTOM_SINGULARITY.id,
SPELLS.SEED_OF_CORRUPTION_EXPLOSION.id,
SPELLS.DRAIN_SOUL.id,
...UNSTABLE_AFFLICTION_DEBUFF_IDS,
];
//based on the fact that it's a linear increase in damage that is +0% damage at 35% HP and +50% damage at 0% HP
const SLOPE_OF_DAMAGE_INCREASE = -50/35;
class DeathsEmbrace extends Module {
bonusDmg = 0;
getDeathEmbraceBonus(healthPercentage) {
//damageIncrease = (-50/35) * current_target_HP_percentage + 0.5
//gives 0 for healthPercentage = 0.35 and 0.5 for healthPercentage = 0
return SLOPE_OF_DAMAGE_INCREASE * healthPercentage + 0.5;
}
on_initialized() {
if (!this.owner.error) {
this.active = this.owner.selectedCombatant.hasTalent(SPELLS.DEATHS_EMBRACE_TALENT.id) || this.owner.selectedCombatant.hasFinger(ITEMS.SOUL_OF_THE_NETHERLORD.id);
}
}
on_byPlayer_damage(event) {
const targetHealthPercentage = event.hitPoints / event.maxHitPoints;
if (!targetHealthPercentage) {
//on random occasion (happened at least once), damage event doesn't have hitPoints and maxHitPoints, which results in NaN and messes up entire module, turning bonusDmg into NaN
return;
}
if (targetHealthPercentage > 0.35) {
return; //talent doesn't even do anything till 35% target HP
}
const spellId = event.ability.guid;
if (abilitiesAffected.indexOf(spellId) === -1) {
return;
}
this.bonusDmg += getDamageBonus(event, this.getDeathEmbraceBonus(targetHealthPercentage));
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.DEATHS_EMBRACE_TALENT.id} />}
value={`${formatNumber(this.bonusDmg / this.owner.fightDuration * 1000)} DPS`}
label='Damage contributed'
tooltip={`Your Death's Embrace talent contributed ${formatNumber(this.bonusDmg)} total damage (${formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.bonusDmg))} %).`}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL(3);
}
export default DeathsEmbrace;
|
src/components/Account/index.js | taiwoabegunde/developersmap | /**
* Created by Raphson on 9/28/16.
*/
import React from 'react';
import { Link, hashHistory } from 'react-router';
import NavBar from '../NavBar/index';
import Footer from '../Footer/Index';
import UserStore from '../../stores/UserStore';
import ProjectStore from '../../stores/ProjectStore';
import UserActions from '../../actions/UserActions';
import ProjectActions from '../../actions/ProjectActions';
import Auth from '../../utils/auth';
import marked from 'marked';
import moment from 'moment';
import L from 'leaflet'
import Modal from 'boron/FlyModal';
import CreateIndex from '../Project/CreateIndex';
import Alert from 'react-s-alert';
import 'react-s-alert/dist/s-alert-default.css';
import 'react-s-alert/dist/s-alert-css-effects/bouncyflip.css';
var contentStyle = {
height: '100%',
width: '600px'
};
export default class Account extends React.Component {
constructor() {
super();
L.Icon.Default.imagePath = "//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/";
this.state = {
geocoder: new google.maps.Geocoder(),
token: Auth.getToken(),
displayImage: '',
fullName: '',
hireStatus: 'No',
twitter:'',
website: '',
github: '',
bio: '',
address: '',
username: '',
registered_on: '1454521239279',
longitude: 3.540790900000047300,
latitude: 6.523276500000000000,
zoom: 12,
showModal: false
}
}
componentDidMount() {
UserActions.fetchAuthUser(this.state.token);
UserStore.addChangeListener(this.handleAuthUserFetch);
ProjectStore.addChangeListener(this.handleShareProjectResult, 'shareProject');
}
componentWillUnmount(){
UserStore.removeChangeListener(this.handleAuthUserFetch);
ProjectStore.removeChangeListener(this.handleShareProjectResult, 'shareProject');
}
handleAuthUserFetch = () => {
let authUser = UserStore.getAuthUserResult();
Auth.checkAuthRequired(authUser);
this.setState({
fullName: authUser.data.fullname,
hireStatus: authUser.data.hire_status,
twitter: authUser.data.twitter_handle,
website: authUser.data.website,
github: authUser.data.github_profile,
bio: authUser.data.bio,
address: authUser.data.address,
displayImage: authUser.data.user_avi,
registered_on: authUser.data.registered_on,
username: authUser.data.username
});
this.handleAddressResolve();
}
handleShareProjectResult = () => {
let result = ProjectStore.getShareProjectResult();
Auth.checkAuthRequired(result);
if(result.status == 500){
Alert.error(result.data.message, { position: 'top-right', effect: 'bouncyflip'});
} else {
if(result.data.success){
Alert.success(result.data.message, { position: 'top-right', effect: 'bouncyflip'});
this.refs.modal.hide();
} else {
Alert.error(result.data.message, { position: 'top-right', effect: 'bouncyflip'});
}
}
}
handleAddressResolve = () => {
this.state.geocoder.geocode({'address': this.state.address}, this.handleAddressResolveSuccess);
}
handleAddressResolveSuccess = (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
let result = results[0].geometry.location;
let map = L.map("map", {center: [this.state.latitude, this.state.longitude],zoom: this.state.zoom});
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {attribution: "OpenStreetMap"}).addTo(map);
let marker = L.marker([result.lat(), result.lng()]).addTo(map);
marker.bindPopup("<strong>You are here!</strong>").openPopup();
}
}
showModal = (e) => {
e.preventDefault();
this.refs.modal.show();
}
hideModal = (e) =>{
e.preventDefault();
this.refs.modal.hide();
}
handleProjectShare = (data) => {
console.log(JSON.stringify(data));
var projectPayLoad = {
name: data.project_name,
url: data.project_url,
description: data.project_description
};
ProjectActions.shareProject(projectPayLoad, this.state.token);
}
render(){
return (
<span>
<NavBar />
<div style={{minHeight: 580}} className="main-container">
<section className="header header-12">
<div className="container">
<div className="row">
<div className="col-sm-12 text-white">
<h4 className="text-white">{this.state.fullName}</h4>
<ul>
<li><i className="fa fa-clock-o" /> Member since
<span> { moment(this.state.registered_on, "x").format("DD MMM YYYY")} </span></li>
</ul>
</div>
</div>
</div>
</section>
<section className="faq faq-1">
<div className="container">
<div className="row">
<div className="col-sm-6">
<div className="faq">
<img width={200} height={200} src={ this.state.displayImage }
alt={this.state.fullName} className="img-rounded" />
</div>
<div className="faq">
<h5>{this.state.fullName}</h5>
<ul>
{(this.state.github != '') ?
<li><a target="_blank" href={this.state.github}>
<i className="fa fa-github" /> GitHub</a></li>
: null }
{(this.state.website != '') ?
<li><a target="_blank" href={this.state.website}>
<i className="fa fa-globe" /> Website / Blog</a></li>
: null }
</ul>
<br />
<ul>
{(this.state.hireStatus == 'yes') ?
<li ><i className="fa fa-suitcase" /> Not Available for Hire</li>
:
<li><i className="fa fa-suitcase" /> Available for Hire</li> }
<br />
</ul>
<ul>
<li><i className="fa fa-project" />
<a onClick={this.showModal}
className="btn btn-default">Share Project</a>
<Modal ref="modal" contentStyle={contentStyle}>
<CreateIndex onClose={this.hideModal}
onDataSubmit={this.handleProjectShare} />
</Modal>
</li>
<br />
</ul>
</div>
</div>
<div className="col-sm-6">
<div className="faq">
<h5>Tell Us About Yourself</h5>
<p dangerouslySetInnerHTML={{__html: marked(this.state.bio) }} />
</div>
<div className="faq">
<h5>Location</h5>
<div id="map" className="leaflet-container"></div>
</div>
</div>
</div>
</div>
</section>
</div>
<Footer />
</span>
);
}
} |
node_modules/react-bootstrap/es/ModalFooter.js | NickingMeSpace/questionnaire | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'prop-types-extra/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'div'
};
var ModalFooter = function (_React$Component) {
_inherits(ModalFooter, _React$Component);
function ModalFooter() {
_classCallCheck(this, ModalFooter);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalFooter.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ModalFooter;
}(React.Component);
ModalFooter.propTypes = propTypes;
ModalFooter.defaultProps = defaultProps;
export default bsClass('modal-footer', ModalFooter); |
react-flux-mui/js/material-ui/src/svg-icons/action/important-devices.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionImportantDevices = (props) => (
<SvgIcon {...props}>
<path d="M23 11.01L18 11c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-9c0-.55-.45-.99-1-.99zM23 20h-5v-7h5v7zM20 2H2C.89 2 0 2.89 0 4v12c0 1.1.89 2 2 2h7v2H7v2h8v-2h-2v-2h2v-2H2V4h18v5h2V4c0-1.11-.9-2-2-2zm-8.03 7L11 6l-.97 3H7l2.47 1.76-.94 2.91 2.47-1.8 2.47 1.8-.94-2.91L15 9h-3.03z"/>
</SvgIcon>
);
ActionImportantDevices = pure(ActionImportantDevices);
ActionImportantDevices.displayName = 'ActionImportantDevices';
ActionImportantDevices.muiName = 'SvgIcon';
export default ActionImportantDevices;
|
examples/js/pagination/default-pagination-table.js | opensourcegeek/react-bootstrap-table | 'use strict';
import React from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
var products = [];
function addProducts(quantity) {
var startId = products.length;
for (var i = 0; i < quantity; i++) {
var id = startId + i;
products.push({
id: id,
name: "Item name " + id,
price: 2100 + i
});
}
}
addProducts(70);
export default class DefaultPaginationTable extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<BootstrapTable
data={products}
pagination
>
<TableHeaderColumn dataField="id" isKey={true}>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField="name">Product Name</TableHeaderColumn>
<TableHeaderColumn dataField="price">Product Price</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
};
|
demos/loading/demos/indeterminate.js | isogon/styled-mdl-website | import React from 'react'
import { Progress } from 'styled-mdl'
const demo = () => <Progress indeterminate width="300px" />
const caption = 'Indeterminate Progress Bar'
const code = '<Progress indeterminate width="300px" />'
export default { demo, caption, code }
|
react_textInput/setup.js | devSC/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View
} from 'react-native';
import TextInputComponent from "./TextInputComponent";
export default class setup extends Component {
render() {
return (
<View style={styles.container}>
<TextInputComponent/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 64,
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('react_textInput', () => react_textInput);
|
src/svg-icons/image/music-note.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageMusicNote = (props) => (
<SvgIcon {...props}>
<path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/>
</SvgIcon>
);
ImageMusicNote = pure(ImageMusicNote);
ImageMusicNote.displayName = 'ImageMusicNote';
ImageMusicNote.muiName = 'SvgIcon';
export default ImageMusicNote;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.