path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
example/src/components/WidgetRenderer.js | rsamec/react-designer-core | import React from 'react';
import _ from 'lodash';
export default (properties) => {
let {node,widget,selected, current, currentChanged} = properties;
if (widget === undefined) return React.DOM.span(null, 'Component ' + node.elementName + ' is not register among widgets.');
var props = node.props || {};
//propaget specific additional properties for inline editor
var isInlineEdit = selected && node.elementName === 'Core.RichTextContent';
if (isInlineEdit) props = _.extend(props,{designer:true,current:current,currentChanged:currentChanged,node:node});
return React.createElement(widget,props,props.content !== undefined ? React.createElement("div",{ dangerouslySetInnerHTML: {__html: props.content } }) : null);
};
|
node_modules/react-native-vector-icons/RNIMigration.js | odapplications/WebView-with-Lower-Tab-Menu | import React from 'react';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import Foundation from 'react-native-vector-icons/Foundation';
import Ionicons from 'react-native-vector-icons/Ionicons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import Zocial from 'react-native-vector-icons/Zocial';
import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons';
const ICON_SET_MAP = {
fontawesome: FontAwesome,
foundation: Foundation,
ion: Ionicons,
material: MaterialIcons,
zocial: Zocial,
simpleline: SimpleLineIcons,
};
// This is a composition is a drop in replacement for users migrating from the
// react-native-icons module. Please don't use this component for new apps/views.
export default class Icon extends React.Component {
static propTypes = {
name: React.PropTypes.string.isRequired,
size: React.PropTypes.number,
color: React.PropTypes.string,
};
setNativeProps(nativeProps) {
if (this.iconRef) {
this.iconRef.setNativeProps(nativeProps);
}
}
iconRef = null;
handleComponentRef = (ref) => {
this.iconRef = ref;
};
render() {
const nameParts = this.props.name.split('|');
const setName = nameParts[0];
const name = nameParts[1];
const IconSet = ICON_SET_MAP[setName];
if (!IconSet) {
throw new Error(`Invalid icon set "${setName}"`);
}
return (
<IconSet
allowFontScaling={false}
ref={this.handleComponentRef}
{...this.props}
name={name}
/>
);
}
}
|
src/steps.js | wallat/little-test | import React from 'react'
import PropTypes from 'prop-types'
import { Header, Button, Form, Icon } from 'semantic-ui-react'
// Class for handle countdown style steps
class SecCountDownComponent extends React.Component {
static propTypes = {
secs: PropTypes.number.isRequired,
onFinished: PropTypes.func
}
constructor (props) {
super(props)
this.state = {}
}
startTick () {
this.setState({
secsToGo: this.props.secs + 1
}, () => {
this.nextTick()
})
}
nextTick () {
let nextSecsToGo = this.state.secsToGo - 1
if (nextSecsToGo) {
this.setState({secsToGo: nextSecsToGo})
this.timeoutHandler = setTimeout(() => {
this.nextTick()
}, 1000)
} else {
this.endTick()
}
}
endTick () {
if (this.timeoutHandler) {
clearTimeout(this.timeoutHandler)
}
this.props.onFinished()
}
}
class ExplainNButton extends React.Component {
static propTypes = {
pageTitle: PropTypes.string.isRequired,
buttonText: PropTypes.string,
onClick: PropTypes.func.isRequired
}
render () {
return (
<div className="text-block-wrapper">
<div className="container">
<Header size="huge">{this.props.pageTitle}</Header>
<Button
primary={true}
style={{marginTop: "20px"}}
onClick={this.props.onClick}>{this.props.buttonText || 'NEXT'}</Button>
</div>
</div>
)
}
}
class ExplainNCountDown extends SecCountDownComponent {
static propTypes = {
pageTitle: PropTypes.string.isRequired,
onFinished: PropTypes.func.isRequired,
secs: PropTypes.number,
}
componentDidMount () {
this.startTick()
}
render () {
return (
<div className="text-block-wrapper">
<div className="container">
<Header size="huge">{this.props.pageTitle}</Header>
<div>{this.state.secsToGo}</div>
</div>
</div>
)
}
}
class SlideShows extends React.Component {
static propTypes = {
tokens: PropTypes.array.isRequired,
secsForEachToken: PropTypes.number,
onFinished: PropTypes.func.isRequired
}
constructor (props) {
super(props)
this.state = {}
}
componentDidMount () {
this.startTick()
}
startTick () {
this.setState({
numTokens: this.props.tokens.length,
currTokenIdx: -1
}, () => {
this.nextTick()
})
}
nextTick () {
let tickInterval = this.props.secsForEachToken || 1
let nextTokenIdx = this.state.currTokenIdx+1
if (nextTokenIdx>=this.state.numTokens) {
this.endTick()
} else {
this.setState({
currTokenIdx: nextTokenIdx
})
setTimeout(() => {
this.nextTick()
}, tickInterval*1000)
}
}
endTick () {
this.props.onFinished()
}
render () {
const {tokens} = this.props
const {numTokens, currTokenIdx} = this.state
return (
<div className="text-block-wrapper">
<div className="container">
<div>{currTokenIdx+1}/{numTokens}</div>
<Header size="huge">{tokens[currTokenIdx]}</Header>
</div>
</div>
)
}
}
class AnswerPage extends SecCountDownComponent {
static propTypes = {
pageTitle: PropTypes.string.isRequired,
secs: PropTypes.number,
onAnswerChange: PropTypes.func.isRequired,
onFinished: PropTypes.func.isRequired
}
componentDidMount () {
this.startTick()
}
render () {
return (
<div className="text-page-wrapper">
<div className="container">
<Header>{this.props.pageTitle}</Header>
<Form className="answer-form">
<Form.TextArea
placeholder='每一行寫一個答案'
onChange={(e) => {
this.props.onAnswerChange(e.target.value)
}}/>
<Button onClick={(e) => {
e.preventDefault()
this.endTick()
}} primary={true}>Done - {this.state.secsToGo}</Button>
</Form>
</div>
</div>
)
}
}
class CountDownTimer extends SecCountDownComponent {
static propTypes = {
secs: PropTypes.number,
onFinished: PropTypes.func.isRequired
}
componentDidMount () {
this.startTick()
}
render () {
const {secsToGo} = this.state
return (
<div className="text-block-wrapper">
<div className="container">
<Header size="huge">{secsToGo}</Header>
</div>
</div>
)
}
}
class ThankYouPage extends React.Component {
static propTypes = {
saveStatus: PropTypes.string.isRequired
}
render () {
const {saveStatus} = this.props
return (
<div className="text-block-wrapper">
<div className="container">
<Header size="huge">非常謝謝你的參與!你的一小步,是我們遠離二一的一大步!</Header>
{saveStatus==='SAVING' &&
<Header className="result-message" size="medium">
<Icon name="spinner" loading={true} color="orange" size="medium"/>
<span>上傳中</span>
</Header>
}
{saveStatus==='DONE' &&
<Header className="result-message" size="medium" color="green">
<Icon name="check" color="green" size="medium"/>
<span>上傳完成!</span>
</Header>
}
{saveStatus==='ERROR' &&
<Header className="result-message" size="medium" color="red">
<Icon name="exclamation circle" color="red" size="medium"/>
<span>上傳失敗 QQ</span>
</Header>
}
</div>
</div>
)
}
}
export {ExplainNButton, ExplainNCountDown, SlideShows, AnswerPage, CountDownTimer, ThankYouPage} |
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js | webwlsong/actor-platform | import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
const {addons: { PureRenderMixin }} = addons;
import ActorClient from 'utils/ActorClient';
import { Styles, FlatButton } from 'material-ui';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
import MessageActionCreators from 'actions/MessageActionCreators';
import TypingActionCreators from 'actions/TypingActionCreators';
import DraftActionCreators from 'actions/DraftActionCreators';
import GroupStore from 'stores/GroupStore';
import DraftStore from 'stores/DraftStore';
import AvatarItem from 'components/common/AvatarItem.react';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
text: DraftStore.getDraft(),
profile: ActorClient.getUser(ActorClient.getUid())
};
};
@ReactMixin.decorate(PureRenderMixin)
class ComposeSection extends React.Component {
static propTypes = {
peer: React.PropTypes.object.isRequired
};
static childContextTypes = {
muiTheme: React.PropTypes.object
};
constructor(props) {
super(props);
this.state = getStateFromStores();
ThemeManager.setTheme(ActorTheme);
GroupStore.addChangeListener(getStateFromStores);
DraftStore.addLoadDraftListener(this.onDraftLoad);
}
componentWillUnmount() {
DraftStore.removeLoadDraftListener(this.onDraftLoad);
GroupStore.removeChangeListener(getStateFromStores);
}
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
onDraftLoad = () => {
this.setState(getStateFromStores());
};
onChange = event => {
TypingActionCreators.onTyping(this.props.peer);
this.setState({text: event.target.value});
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) {
event.preventDefault();
this.sendTextMessage();
} else if (event.keyCode === 50 && event.shiftKey) {
console.warn('Mention should show now.');
}
};
onKeyUp = () => {
DraftActionCreators.saveDraft(this.state.text);
};
sendTextMessage = () => {
const text = this.state.text;
if (text) {
MessageActionCreators.sendTextMessage(this.props.peer, text);
}
this.setState({text: ''});
DraftActionCreators.saveDraft('', true);
};
onSendFileClick = () => {
const fileInput = document.getElementById('composeFileInput');
fileInput.click();
};
onSendPhotoClick = () => {
const photoInput = document.getElementById('composePhotoInput');
photoInput.accept = 'image/*';
photoInput.click();
};
onFileInputChange = () => {
const files = document.getElementById('composeFileInput').files;
MessageActionCreators.sendFileMessage(this.props.peer, files[0]);
};
onPhotoInputChange = () => {
const photos = document.getElementById('composePhotoInput').files;
MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]);
};
onPaste = event => {
let preventDefault = false;
_.forEach(event.clipboardData.items, (item) => {
if (item.type.indexOf('image') !== -1) {
preventDefault = true;
MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile());
}
}, this);
if (preventDefault) {
event.preventDefault();
}
};
render() {
const text = this.state.text;
const profile = this.state.profile;
return (
<section className="compose" onPaste={this.onPaste}>
<AvatarItem image={profile.avatar}
placeholder={profile.placeholder}
title={profile.name}/>
<textarea className="compose__message"
onChange={this.onChange}
onKeyDown={this.onKeyDown}
onKeyUp={this.onKeyUp}
value={text}>
</textarea>
<footer className="compose__footer row">
<button className="button" onClick={this.onSendFileClick}>
<i className="material-icons">attachment</i> Send file
</button>
<button className="button" onClick={this.onSendPhotoClick}>
<i className="material-icons">photo_camera</i> Send photo
</button>
<span className="col-xs"></span>
<FlatButton label="Send" onClick={this.sendTextMessage} secondary={true}/>
</footer>
<div className="compose__hidden">
<input id="composeFileInput"
onChange={this.onFileInputChange}
type="file"/>
<input id="composePhotoInput"
onChange={this.onPhotoInputChange}
type="file"/>
</div>
</section>
);
}
}
export default ComposeSection;
|
examples/js/custom/delete-button/default-custom-delete-button.js | echaouchna/react-bootstrap-tab | /* eslint max-len: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-alert: 0 */
/* eslint no-console: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn, DeleteButton } from 'react-bootstrap-table';
const products = [];
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,
price: 2100 + i
});
}
}
addProducts(5);
export default class DefaultCustomInsertButtonTable extends React.Component {
handleDeleteButtonClick = (onClick) => {
// Custom your onClick event here,
// it's not necessary to implement this function if you have no any process before onClick
console.log('This is my custom function for DeleteButton click event');
onClick();
}
createCustomDeleteButton = (onClick) => {
return (
<DeleteButton
btnText='CustomDeleteText'
btnContextual='btn-success'
className='my-custom-class'
btnGlyphicon='glyphicon-edit'
onClick={ e => this.handleDeleteButtonClick(onClick) }/>
);
// If you want have more power to custom the child of DeleteButton,
// you can do it like following
// return (
// <DeleteButton
// btnContextual='btn-warning'
// className='my-custom-class'
// onClick={ () => this.handleDeleteButtonClick(onClick) }>
// { ... }
// </DeleteButton>
// );
}
render() {
const options = {
deleteBtn: this.createCustomDeleteButton
};
const selectRow = {
mode: 'checkbox'
};
return (
<BootstrapTable selectRow={ selectRow } data={ products } options={ options } deleteRow>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/svg-icons/file/cloud-download.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileCloudDownload = (props) => (
<SvgIcon {...props}>
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM17 13l-5 5-5-5h3V9h4v4h3z"/>
</SvgIcon>
);
FileCloudDownload = pure(FileCloudDownload);
FileCloudDownload.displayName = 'FileCloudDownload';
FileCloudDownload.muiName = 'SvgIcon';
export default FileCloudDownload;
|
src/svg-icons/places/child-care.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesChildCare = (props) => (
<SvgIcon {...props}>
<circle cx="14.5" cy="10.5" r="1.25"/><circle cx="9.5" cy="10.5" r="1.25"/><path d="M22.94 12.66c.04-.21.06-.43.06-.66s-.02-.45-.06-.66c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66s.02.45.06.66c.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2zM7.5 14c.76 1.77 2.49 3 4.5 3s3.74-1.23 4.5-3h-9z"/>
</SvgIcon>
);
PlacesChildCare = pure(PlacesChildCare);
PlacesChildCare.displayName = 'PlacesChildCare';
PlacesChildCare.muiName = 'SvgIcon';
export default PlacesChildCare;
|
client/components/App.js | caiquecaleiro/react-graphql-auth | import React from 'react';
import Header from './Header';
const App = ({ children }) => {
return (
<div className="container">
<Header />
{children}
</div>
);
};
export default App; |
src/utils/children.js | vanHeemstraSystems/components | import React from 'react';
import createFragment from 'react-addons-create-fragment';
export default {
create(fragments) {
let newFragments = {};
let validChildrenCount = 0;
let firstKey;
//Only create non-empty key fragments
for (let key in fragments) {
const currentChild = fragments[key];
if (currentChild) {
if (validChildrenCount === 0) firstKey = key;
newFragments[key] = currentChild;
validChildrenCount++;
}
}
if (validChildrenCount === 0) return undefined;
if (validChildrenCount === 1) return newFragments[firstKey];
return createFragment(newFragments);
},
extend(children, extendedProps, extendedChildren) {
return React.isValidElement(children) ?
React.Children.map(children, (child) => {
const newProps = typeof (extendedProps) === 'function' ?
extendedProps(child) : extendedProps;
const newChildren = typeof (extendedChildren) === 'function' ?
extendedChildren(child) : extendedChildren ?
extendedChildren : child.props.children;
return React.cloneElement(child, newProps, newChildren);
}) : children;
},
};
|
assets/jqwidgets/demos/react/app/treegrid/virtualmodewithajax/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxTreeGrid from '../../../jqwidgets-react/react_jqxtreegrid.js';
class App extends React.Component {
render() {
let source =
{
dataType: 'json',
dataFields: [
{ name: 'EmployeeID', type: 'number' },
{ name: 'ReportsTo', type: 'number' },
{ name: 'FirstName', type: 'string' },
{ name: 'LastName', type: 'string' },
{ name: 'Country', type: 'string' },
{ name: 'City', type: 'string' },
{ name: 'Address', type: 'string' },
{ name: 'Title', type: 'string' },
{ name: 'HireDate', type: 'date' },
{ name: 'BirthDate', type: 'date' }
],
timeout: 10000,
hierarchy:
{
keyDataField: { name: 'EmployeeID' },
parentDataField: { name: 'ReportsTo' }
},
id: 'EmployeeID',
root: 'value',
url: 'http://services.odata.org/V3/Northwind/Northwind.svc/Employees?$format=json&$callback=?'
};
let virtualModeCreateRecords = (expandedRecord, done) => {
let dataAdapter = new $.jqx.dataAdapter(source,
{
formatData: (data) => {
if (expandedRecord == null) {
data.$filter = '(ReportsTo eq null)'
}
else {
data.$filter = '(ReportsTo eq ' + expandedRecord.EmployeeID + ')'
}
return data;
},
loadComplete: () => {
done(dataAdapter.records);
},
loadError: (xhr, status, error) => {
done(false);
throw new Error('http://services.odata.org: ' + error.toString());
}
}
);
dataAdapter.dataBind();
};
let virtualModeRecordCreating = (record) => {
// record is creating.
};
let columns = [
{ text: 'FirstName', columnGroup: 'Name', dataField: 'FirstName', width: 150 },
{ text: 'LastName', columnGroup: 'Name', dataField: 'LastName', width: 150 },
{ text: 'Title', dataField: 'Title', width: 200 },
{ text: 'Birth Date', dataField: 'BirthDate', cellsFormat: 'd' }
];
return (
<div>
<h3 style={{ fontSize: 16, fontFamily: 'Verdana' }}>Data Source: 'http://services.odata.org'</h3>
<JqxTreeGrid
width={800} columns={columns}
virtualModeCreateRecords={virtualModeCreateRecords}
virtualModeRecordCreating={virtualModeRecordCreating}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/fe/components/UserAdd.js | searsaw/react-router-demo | import React from 'react';
import { post } from 'axios';
import UserForm from './UserForm';
import { Helmet } from 'react-helmet';
import Page from './Page';
class UserAdd extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
}
handleSubmit(user) {
post('/api/users', user)
.then(() => {
console.log('added:', user);
});
}
handleCancel(e) {
e.preventDefault();
console.log('you have canceled');
}
render() {
return (
<Page title="Add User" columns={3}>
<Helmet>
<title>CMS | Add User</title>
</Helmet>
<UserForm
handleSubmit={this.handleSubmit}
handleCancel={this.handleCancel}
/>
</Page>
);
}
}
export default UserAdd;
|
fields/types/markdown/MarkdownColumn.js | naustudio/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var MarkdownColumn = React.createClass({
displayName: 'MarkdownColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
return (value && Object.keys(value).length) ? value.md.substr(0, 100) : null;
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = MarkdownColumn;
|
src/assets/js/react/components/Template/TemplateSingleComponents.js | GravityPDF/gravity-forms-pdf-extended | import PropTypes from 'prop-types'
import React from 'react'
/**
* Contains stateless React components for our Single Template
*
* @package Gravity PDF
* @copyright Copyright (c) 2021, Blue Liquid Designs
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 4.1
*/
/**
* React Stateless Component
*
* Display the current template label
*
* @since 4.1
*/
export const CurrentTemplate = ({ isCurrentTemplate, label }) => {
return (isCurrentTemplate) ? (
<span
data-test='component-currentTemplate'
className='current-label'
>
{label}
</span>
) : (
<span />
)
}
CurrentTemplate.propTypes = {
isCurrentTemplate: PropTypes.bool,
label: PropTypes.string
}
/**
* React Stateless Component
*
* Display the template name and version number
*
* @since 4.1
*/
export const Name = ({ name, version, versionLabel }) => (
<h2
data-test='component-name'
className='theme-name'
>
{name}
<Version version={version} label={versionLabel} />
</h2>
)
Name.propTypes = {
name: PropTypes.string,
version: PropTypes.string,
versionLabel: PropTypes.string
}
/**
* React Stateless Component
*
* Display the template version number
*
* @since 4.1
*/
export const Version = ({ label, version }) => {
return (version) ? (
<span data-test='component-version' className='theme-version'>{label}: {version}</span>
) : (
<span />
)
}
Version.propTypes = {
label: PropTypes.string,
version: PropTypes.string
}
/**
* React Stateless Component
*
* Display the template author (and link to website, if any)
*
* @since 4.1
*/
export const Author = ({ author, uri }) => {
if (uri) {
return (
<p data-test='component-author' className='theme-author'>
<a href={uri}>
{author}
</a>
</p>
)
} else {
return (
<p data-test='component-author' className='theme-author'>
{author}
</p>
)
}
}
Author.propTypes = {
author: PropTypes.string,
uri: PropTypes.string
}
/**
* React Stateless Component
*
* Display the template group
*
* @since 4.1
*/
export const Group = ({ label, group }) => (
<p data-test='component-group' className='theme-author'>
<strong>{label}: {group}</strong>
</p>
)
Group.propTypes = {
label: PropTypes.string,
group: PropTypes.string
}
/**
* React Stateless Component
*
* Display the template description
*
* @since 4.1
*/
export const Description = ({ desc }) => (
<p data-test='component-description' className='theme-description'>
{desc}
</p>
)
Description.propTypes = {
desc: PropTypes.string
}
/**
* React Stateless Component
*
* Display the template tags
*
* @since 4.1
*/
export const Tags = ({ label, tags }) => {
return (tags) ? (
<p data-test='component-tags' className='theme-tags'>
<span>{label}:</span> {tags}
</p>
) : (
<span />
)
}
Tags.propTypes = {
label: PropTypes.string,
tags: PropTypes.string
}
|
src/routes.js | gregmalcolm/elite-engineers | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import Home from './pages/Home';
import CraftingComponents from './pages/CraftingComponents';
import Calculator from './pages/Calculator';
import TheDweller from './pages/TheDweller';
import NotFound from './pages/NotFound';
export default (
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="calculator" component={Calculator}/>
<Route path="the-dweller" component={TheDweller}/>
<Route path="components" component={CraftingComponents}/>
<Route path="*" component={NotFound}/>
</Route>
);
|
examples/browserify-gulp-example/src/app/Main.js | rscnt/material-ui | /**
* In this file, we create a React component
* which incorporates components providedby material-ui.
*/
import React from 'react';
import RaisedButton from 'material-ui/lib/raised-button';
import Dialog from 'material-ui/lib/dialog';
import {deepOrange500} from 'material-ui/lib/styles/colors';
import FlatButton from 'material-ui/lib/flat-button';
import getMuiTheme from 'material-ui/lib/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider';
const styles = {
container: {
textAlign: 'center',
paddingTop: 200,
},
};
const muiTheme = getMuiTheme({
palette: {
accent1Color: deepOrange500,
},
});
class Main extends React.Component {
constructor(props, context) {
super(props, context);
this.handleRequestClose = this.handleRequestClose.bind(this);
this.handleTouchTap = this.handleTouchTap.bind(this);
this.state = {
open: false,
};
}
handleRequestClose() {
this.setState({
open: false,
});
}
handleTouchTap() {
this.setState({
open: true,
});
}
render() {
const standardActions = (
<FlatButton
label="Ok"
secondary={true}
onTouchTap={this.handleRequestClose}
/>
);
return (
<MuiThemeProvider muiTheme={muiTheme}>
<div style={styles.container}>
<Dialog
open={this.state.open}
title="Super Secret Password"
actions={standardActions}
onRequestClose={this.handleRequestClose}
>
1-2-3-4-5
</Dialog>
<h1>material-ui</h1>
<h2>example project</h2>
<RaisedButton
label="Super Secret Password"
primary={true}
onTouchTap={this.handleTouchTap}
/>
</div>
</MuiThemeProvider>
);
}
}
export default Main;
|
techCurriculum/ui/solutions/3.2/src/components/Message.js | AnxChow/EngineeringEssentials-group | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
function Message(props) {
return (
<div className='message-text'>
<p>{props.text}</p>
</div>
);
}
export default Message;
|
src/svg-icons/hardware/smartphone.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSmartphone = (props) => (
<SvgIcon {...props}>
<path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
HardwareSmartphone = pure(HardwareSmartphone);
HardwareSmartphone.displayName = 'HardwareSmartphone';
HardwareSmartphone.muiName = 'SvgIcon';
export default HardwareSmartphone;
|
examples/src/app.js | DanielMontesDeOca/react-autosuggest | require('./app.less');
import React, { Component } from 'react';
import Badges from './Badges/Badges';
import Examples from './Examples';
import Footer from './Footer/Footer';
import ForkMeOnGitHub from './ForkMeOnGitHub/ForkMeOnGitHub';
class App extends Component {
render() {
return (
<div>
<h1>react-autosuggest</h1>
<Badges />
<Examples />
<Footer />
<ForkMeOnGitHub user="moroshko" repo="react-autosuggest" />
</div>
);
}
}
React.render(<App />, document.getElementById('app'));
|
src/components/Highlight.js | cpsubrian/redis-explorer | import React from 'react'
import autobind from 'autobind-decorator'
import hljs from 'highlight.js'
@autobind
class Highlight extends React.Component {
static propTypes = {
className: React.PropTypes.string,
innerHTML: React.PropTypes.bool,
children: React.PropTypes.node
}
static defaultProps = {
innerHTML: false,
className: ''
}
componentDidMount () {
this.highlightCode()
}
componentDidUpdate () {
this.highlightCode()
}
highlightCode () {
let nodes = React.findDOMNode(this).querySelectorAll('pre code')
if (nodes.length > 0) {
for (let i = 0; i < nodes.length; i = i + 1) {
hljs.highlightBlock(nodes[i])
}
}
}
render () {
if (this.props.innerHTML) {
return <div dangerouslySetInnerHTML={{__html: this.props.children}} className={this.props.className || null}></div>
} else {
return <pre><code className={this.props.className}>{this.props.children}</code></pre>
}
}
}
export default Highlight
|
app/components/Icons/FemaleCheckedIcon.js | Tetraib/player.rauks.org | import React from 'react'
import SvgIcon from 'material-ui/SvgIcon'
export const FemaleCheckedIcon = (props) => (
<SvgIcon {...props}>
<path d='M12,15.078c-3.667,0-6.65-2.933-6.65-6.539C5.35,4.934,8.333,2,12,2c3.667,0,6.65,2.934,6.65,6.539 C18.65,12.145,15.667,15.078,12,15.078z M12,3.727c-2.714,0-4.923,2.159-4.923,4.812c0,2.654,2.208,4.813,4.923,4.813 c2.715,0,4.924-2.159,4.924-4.813C16.924,5.886,14.715,3.727,12,3.727z'/>
<path d='M10.824,14.85v2.326h-2.66v2.11h2.66V22h2.353v-2.714h2.558v-2.11h-2.558V14.85H10.824z'/>
<circle cx='12' cy='8.55' r='2.5'/>
</SvgIcon>
)
export default FemaleCheckedIcon
|
app/components/events-search-bar.js | mario2904/ICOM5016-Project | import React, { Component } from 'react';
import {Input, Select, Grid, Form, Segment} from 'semantic-ui-react';
export default class EventsSearchBar extends Component {
render () {
return (
<Grid padded style={{padding: 40}}>
<Input action={{ icon: 'search'}} placeholder='Search by name...' />
<Form>
<Form.Group>
<Form.Field inline control={Select} label='Order by'
options={order} placeholder='i.e. Most Popular' />
<Form.Field inline control={Select} label='Categories'
options={options} placeholder='i.e. Food' />
</Form.Group>
</Form>
</Grid>
);
}
}
// Add padding to searchbar
const options = [
{ text: 'Food', value: 'Food' },
{ text: 'Music', value: 'Music' },
{ text: 'Fundraiser', value: 'Fundraiser' },
{ text: 'Arts', value: 'Arts' },
{ text: 'Social', value: 'Social' },
{ text: 'Educational', value: 'Educational' },
{ text: 'Networking', value: 'Networking' },
{ text: 'Sport', value: 'Sport' },
{ text: 'Competition', value: 'Competition' },
{ text: 'Other', value: 'Other' }];
const order = [
{ text: 'Most Popular', value: 'Most Popular' },
{ text: 'Starting Soon', value: 'Starting Soon' },
{ text: 'A - Z', value: 'A - Z' },
{ text: 'Z - A', value: 'Z - A' }];
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | flgiordano/netcash | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
src/components/views/rooms/RoomDetailRow.js | aperezdc/matrix-react-sdk | /*
Copyright 2017 New Vector Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import sdk from '../../../index';
import React from 'react';
import { _t } from '../../../languageHandler';
import * as linkify from 'linkifyjs';
import linkifyElement from 'linkifyjs/element';
import linkifyMatrix from '../../../linkify-matrix';
import { ContentRepo } from 'matrix-js-sdk';
import MatrixClientPeg from '../../../MatrixClientPeg';
import PropTypes from 'prop-types';
linkifyMatrix(linkify);
export function getDisplayAliasForRoom(room) {
return room.canonicalAlias || (room.aliases ? room.aliases[0] : "");
}
export const roomShape = PropTypes.shape({
name: PropTypes.string,
topic: PropTypes.string,
roomId: PropTypes.string,
avatarUrl: PropTypes.string,
numJoinedMembers: PropTypes.number,
canonicalAlias: PropTypes.string,
aliases: PropTypes.arrayOf(PropTypes.string),
worldReadable: PropTypes.bool,
guestCanJoin: PropTypes.bool,
});
export default React.createClass({
propTypes: {
room: roomShape,
// passes ev, room as args
onClick: PropTypes.func,
onMouseDown: PropTypes.func,
},
_linkifyTopic: function() {
if (this.refs.topic) {
linkifyElement(this.refs.topic, linkifyMatrix.options);
}
},
componentDidMount: function() {
this._linkifyTopic();
},
componentDidUpdate: function() {
this._linkifyTopic();
},
onClick: function(ev) {
ev.preventDefault();
if (this.props.onClick) {
this.props.onClick(ev, this.props.room);
}
},
onTopicClick: function(ev) {
// When clicking a link in the topic, prevent the event being propagated
// to `onClick`.
ev.stopPropagation();
},
render: function() {
const BaseAvatar = sdk.getComponent('avatars.BaseAvatar');
const room = this.props.room;
const name = room.name || getDisplayAliasForRoom(room) || _t('Unnamed room');
const guestRead = room.worldReadable ? (
<div className="mx_RoomDirectory_perm">{ _t('World readable') }</div>
) : <div />;
const guestJoin = room.guestCanJoin ? (
<div className="mx_RoomDirectory_perm">{ _t('Guests can join') }</div>
) : <div />;
const perms = (guestRead || guestJoin) ? (<div className="mx_RoomDirectory_perms">
{ guestRead }
{ guestJoin }
</div>) : <div />;
return <tr key={room.roomId} onClick={this.onClick} onMouseDown={this.props.onMouseDown}>
<td className="mx_RoomDirectory_roomAvatar">
<BaseAvatar width={24} height={24} resizeMethod='crop'
name={name} idName={name}
url={ContentRepo.getHttpUriForMxc(
MatrixClientPeg.get().getHomeserverUrl(),
room.avatarUrl, 24, 24, "crop")} />
</td>
<td className="mx_RoomDirectory_roomDescription">
<div className="mx_RoomDirectory_name">{ name }</div>
{ perms }
<div className="mx_RoomDirectory_topic" ref="topic" onClick={this.onTopicClick}>
{ room.topic }
</div>
<div className="mx_RoomDirectory_alias">{ getDisplayAliasForRoom(room) }</div>
</td>
<td className="mx_RoomDirectory_roomMemberCount">
{ room.numJoinedMembers }
</td>
</tr>;
},
});
|
src/docs/examples/TextInput/ExampleError.js | miker169/ps-react-miker169 | import React from 'react';
import TextInput from 'ps-react/TextInput';
/** Required TextBox with error */
export default class ExampleError extends React.Component {
render() {
return (
<TextInput
htmlId="example-optional"
name="firstname"
label="First Name"
onChange={() => {}}
required
error="First name is required."
/>
)
}
} |
plugins/react/frontend/components/common/RefreshButton/index.js | carteb/carte-blanche | /* eslint-disable max-len */
/**
* RefreshButton
*
* Shows a button with a refresh
*/
import React from 'react';
import styles from './styles.css';
import Button from '../Button';
const RefreshButton = (props) => (
<Button {...props} className={props.className}>
<svg
className={styles.svg}
height={(props.height) ? props.height : '24'}
width={(props.width) ? props.width : '24'}
height="24px"
width="24px"
version="1.1"
viewBox="0 0 24 24"
x="0px"
y="0px"
xmlSpace="preserve"
>
<g id="Outline_Icons_1_">
<g id="Outline_Icons">
<g>
<polyline fill="none" points="
				0.927,10.199 3.714,14.35 6.919,10.512 			" stroke="#000000" strokeLinecap="round" />
<polyline fill="none" points="
				23.5,14.5 20.714,10.35 17.508,14.188 			" stroke="#000000" strokeLinecap="round" />
<path d="M20.677,10.387
				c0.834,4.408-2.273,8.729-6.509,9.729c-2.954,0.699-5.916-0.238-7.931-2.224" fill="none" stroke="#000000" strokeLinecap="round" />
<path d="M3.719,14.325
				C2.405,9.442,5.688,4.65,10.257,3.572c3.156-0.747,6.316,0.372,8.324,2.641" fill="none" stroke="#000000" strokeLinecap="round" />
</g>
</g>
<g id="New_icons_1_" />
</g>
<g id="Invisible_Shape">
<rect height="24" width="24" fill="none" />
</g>
</svg>
</Button>
);
export default RefreshButton;
|
app/components/unfile.js | shrihari/moviemonkey |
import React from 'react'
import ReactDOM from 'react-dom'
import MovieMonkey from '../core/moviemonkey.js'
const remote = require('electron').remote;
const app = remote.app;
const path = require('path');
const shell = require('electron').shell;
export default class UnFile extends React.Component {
constructor(props) {
super(props);
this.play = this.play.bind(this);
this.add = this.add.bind(this);
this.addMovie = this.addMovie.bind(this);
this.updateStatus = this.updateStatus.bind(this);
this.state = {
add: false,
status: {
mode: 0,
message: ""
}
}
this.MM = new MovieMonkey(this.props.db, this.updateStatus);
}
updateStatus(status) {
this.setState(status);
}
play(e) {
shell.openItem(this.props.data.path);
}
add(e) {
this.setState({add: !this.state.add})
}
addMovie(e) {
if (e.key === 'Enter') {
let movie_file = {
hash: this.props.data.hash,
fileName: this.props.data.path,
bytesize: this.props.data.bytesize
}
this.MM.addMovie(e.target.value, "", movie_file, this.props.onAdded);
}
}
render() {
let unfile = this.props.data;
let unfilepath = path.parse(unfile.path);
return (
<div className={"unfile " + (this.state.add ? 'add' : '') }>
<div className="unfile-info">
<div className="unfile-actions">
<div className="unfile-add" onClick={this.add}></div>
<div className="unfile-play" onClick={this.play}></div>
</div>
<div className="unfile-path">
<div className="unfile-folder">{unfilepath.dir}</div>
<div className="unfile-name">{unfilepath.base}</div>
</div>
</div>
<div className={"unfile-add-form " + (this.state.add ? '' : 'hide') }>
<input
id=""
className={ (this.state.status.mode ? 'hide' : '') }
onKeyPress={this.addMovie}
placeholder="Type movie name and press enter ⏎"
ref={input => input && input.focus()} />
<div className={ (this.state.status.mode ? '' : 'hide') }>
{this.state.status.message}
</div>
</div>
</div>
);
}
}
|
app/components/RecipeCard.js | hippothesis/Recipezy | /*
* Copyright 2017-present, Hippothesis, 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.
*
* @flow
*/
'use strict';
import React, { Component } from 'react';
import { Image, TouchableHighLight } from 'react-native';
import { connect } from 'react-redux';
import { Card, CardItem, Text } from 'native-base';
import { selectRecipe } from '../actions/NavigationActions';
import Images from '../constants/Images';
class RecipeCard extends Component {
goToRecipeView() {
console.log("This.props");
console.log(this.props.id);
this.props.setSelectedRecipe(this.props.id);
console.log("This.props.recipe", this.props.recipe);
this.props.navigation.navigate('recipe', {recipe: this.props.recipe});
}
render() {
return (
<Card style={styles.card}>
<CardItem cardBody style={styles.imageContainer} onPress={() => this.goToRecipeView()}>
<Image style={styles.image} source={{uri: this.props.image}} />
</CardItem>
<CardItem>
<Text>{this.props.title}</Text>
</CardItem>
</Card>
);
}
}
const styles = {
imageContainer: {
flex: 1,
alignItems: 'center'
},
image: {
flex: 1,
height: 120
}
}
function mapStateToProps(state) {
return {
ingredients: state.ingredients,
recipeSearchResults: state.recipeSearchResults,
recipes: state.recipes
};
}
function mapDispatchToProps(dispatch) {
return {
setSelectedRecipe: (id) => dispatch(selectRecipe(id)),
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(RecipeCard);
|
react/js/StatelessWidget.js | quiaro/js-playground | import React from 'react';
// Stateless function component
const Widget = (props) => {
return (
<div>
<strong>{props.txt}</strong>
<input type='text' onChange={props.update}/>
</div>
)
}
export default Widget
|
src/components/app.js | hamholla/concentration | import React, { Component } from 'react';
import CardGrid from '../containers/card_grid';
import PlayerList from '../containers/player_list';
export default class App extends Component {
render() {
return (
<div>
<div className="page-header">
<h1>Concentration<small> (2 players)</small></h1>
<div className="row">
<div className="col-md-6">
<p>Take turns flipping cards over to find a match. 1 match = 10 points. If you miss a match it's the next players turn. Game ends when all cards are flipped. Refresh to restart.</p>
</div>
</div>
</div>
<div className="container">
<div className="row">
<PlayerList />
<CardGrid />
</div>
</div>
</div>
);
}
}
|
stories/Focus/SimpleFocusEditor/index.js | dagopert/draft-js-plugins | import React, { Component } from 'react';
import {
convertFromRaw,
EditorState,
} from 'draft-js';
import Editor, { composeDecorators } from 'draft-js-plugins-editor';
import createFocusPlugin from 'draft-js-focus-plugin';
import createColorBlockPlugin from './colorBlockPlugin';
import editorStyles from './editorStyles.css';
const focusPlugin = createFocusPlugin();
const decorator = composeDecorators(
focusPlugin.decorator,
);
const colorBlockPlugin = createColorBlockPlugin({ decorator });
const plugins = [focusPlugin, colorBlockPlugin];
/* eslint-disable */
const initialState = {
"entityMap": {
"0": {
"type": "colorBlock",
"mutability": "IMMUTABLE",
"data": {}
}
},
"blocks": [{
"key": "9gm3s",
"text": "This is a simple example. Click on the block to focus on it.",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [],
"entityRanges": [],
"data": {}
}, {
"key": "ov7r",
"text": " ",
"type": "atomic",
"depth": 0,
"inlineStyleRanges": [],
"entityRanges": [{
"offset": 0,
"length": 1,
"key": 0
}],
"data": {}
}, {
"key": "e23a8",
"text": "More text here to demonstrate how inline left/right alignment works …",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [],
"entityRanges": [],
"data": {}
}]
};
/* eslint-enable */
export default class CustomImageEditor extends Component {
state = {
editorState: EditorState.createWithContent(convertFromRaw(initialState)),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
focus = () => {
this.editor.focus();
};
render() {
return (
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => { this.editor = element; }}
/>
</div>
);
}
}
|
client/src/entwine/TinyMCE_ssembed.js | open-sausages/silverstripe-asset-admin | /* global tinymce, window */
import jQuery from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import { loadComponent } from 'lib/Injector';
import ShortcodeSerialiser from 'lib/ShortcodeSerialiser';
import InsertEmbedModal from 'components/InsertEmbedModal/InsertEmbedModal';
import i18n from 'i18n';
const InjectableInsertEmbedModal = loadComponent(InsertEmbedModal);
const filter = 'div[data-shortcode="embed"]';
/**
* Embed shortcodes are split into an outer <div> element and an inner <img>
* placeholder based on the thumbnail url provided by the oembed shortcode provider.
*/
(() => {
const ssembed = {
init: (editor) => {
const insertTitle = i18n._t('AssetAdmin.INSERT_VIA_URL', 'Insert media via URL');
const editTitle = i18n._t('AssetAdmin.EDIT_MEDIA', 'Edit media');
const contextTitle = i18n._t('AssetAdmin.MEDIA', 'Media');
editor.addButton('ssembed', {
title: insertTitle,
icon: 'media',
cmd: 'ssembed',
stateSelector: filter
});
editor.addMenuItem('ssembed', {
text: contextTitle,
icon: 'media',
cmd: 'ssembed',
});
editor.addButton('ssembededit', {
title: editTitle,
icon: 'editimage',
cmd: 'ssembed'
});
editor.addContextToolbar(
(embed) => editor.dom.is(embed, filter),
'alignleft aligncenter alignright | ssembededit'
);
editor.addCommand('ssembed', () => {
// See HtmlEditorField.js
jQuery(`#${editor.id}`).entwine('ss').openEmbedDialog();
});
// Replace the tinymce default media commands with the ssembed command
editor.on('BeforeExecCommand', (e) => {
const cmd = e.command;
const ui = e.ui;
const val = e.value;
if (cmd === 'mceAdvMedia' || cmd === 'mceAdvMedia') {
e.preventDefault();
editor.execCommand('ssembed', ui, val);
}
});
editor.on('SaveContent', (o) => {
const content = jQuery(`<div>${o.content}</div>`);
// Transform [embed] shortcodes
content
.find(filter)
.each(function replaceWithShortCode() {
// Note: embed <div> contains placeholder <img>, and potentially caption <p>
const embed = jQuery(this);
// If placeholder has been removed, remove data-* properties and
// convert to non-shortcode div
const placeholder = embed.find('img.placeholder');
if (placeholder.length === 0) {
embed.removeAttr('data-url');
embed.removeAttr('data-shortcode');
return;
}
// Find nested element data
const caption = embed.find('.caption').text();
const width = parseInt(placeholder.attr('width'), 10);
const height = parseInt(placeholder.attr('height'), 10);
const url = embed.data('url');
const properties = {
url,
thumbnail: placeholder.prop('src'),
class: embed.prop('class'),
width: isNaN(width) ? null : width,
height: isNaN(height) ? null : height,
caption,
};
const shortCode = ShortcodeSerialiser.serialise({
name: 'embed',
properties,
wrapped: true,
content: url
});
embed.replaceWith(shortCode);
});
// eslint-disable-next-line no-param-reassign
o.content = content.html();
});
editor.on('BeforeSetContent', (o) => {
let content = o.content;
// Transform [embed] tag
let match = ShortcodeSerialiser.match('embed', true, content);
while (match) {
const data = match.properties;
// Add base div
const base = jQuery('<div/>')
.attr('data-url', data.url || match.content)
.attr('data-shortcode', 'embed')
.addClass(data.class)
.addClass('ss-htmleditorfield-file embed');
// Add placeholder
const placeholder = jQuery('<img />')
.attr('src', data.thumbnail)
.addClass('placeholder');
// Set dimensions
if (data.width) {
placeholder.attr('width', data.width);
}
if (data.height) {
placeholder.attr('height', data.height);
}
base.append(placeholder);
// Add caption p tag
if (data.caption) {
const caption = jQuery('<p />')
.addClass('caption')
.text(data.caption);
base.append(caption);
}
// Inject into code
content = content.replace(match.original, (jQuery('<div/>').append(base).html()));
// Search for next match
match = ShortcodeSerialiser.match('embed', true, content);
}
// eslint-disable-next-line no-param-reassign
o.content = content;
});
},
};
tinymce.PluginManager.add('ssembed', (editor) => ssembed.init(editor));
})();
jQuery.entwine('ss', ($) => {
$('.js-injector-boot #insert-embed-react__dialog-wrapper').entwine({
Element: null,
Data: {},
onunmatch() {
// solves errors given by ReactDOM "no matched root found" error.
this._clearModal();
},
_clearModal() {
ReactDOM.unmountComponentAtNode(this[0]);
// this.empty();
},
open() {
this._renderModal(true);
},
close() {
this.setData({});
this._renderModal(false);
},
/**
* Renders the react modal component
*
* @param {boolean} isOpen
* @private
*/
_renderModal(isOpen) {
const handleHide = () => this.close();
// Inserts embed into page
const handleInsert = (...args) => this._handleInsert(...args);
// Create edit form from url
const handleCreate = (...args) => this._handleCreate(...args);
const handleLoadingError = (...args) => this._handleLoadingError(...args);
const attrs = this.getOriginalAttributes();
// create/update the react component
ReactDOM.render(
<InjectableInsertEmbedModal
isOpen={isOpen}
onCreate={handleCreate}
onInsert={handleInsert}
onClosed={handleHide}
onLoadingError={handleLoadingError}
bodyClassName="modal__dialog"
className="insert-embed-react__dialog-wrapper"
fileAttributes={attrs}
/>,
this[0]
);
},
_handleLoadingError() {
this.setData({});
this.open();
},
/**
* Handles inserting the selected file in the modal
*
* @param {object} data
* @returns {Promise}
* @private
*/
_handleInsert(data) {
const oldData = this.getData();
this.setData(Object.assign({ Url: oldData.Url }, data));
this.insertRemote();
this.close();
},
_handleCreate(data) {
this.setData(Object.assign({}, this.getData(), data));
this.open();
},
/**
* Find the selected node and get attributes associated to attach the data to the form
*
* @returns {object}
*/
getOriginalAttributes() {
const data = this.getData();
const $field = this.getElement();
if (!$field) {
return data;
}
const node = $($field.getEditor().getSelectedNode());
if (!node.length) {
return data;
}
// Find root embed shortcode
const element = node.closest(filter).add(node.filter(filter));
if (!element.length) {
return data;
}
const image = element.find('img.placeholder');
// If image has been removed then this shortcode is invalid
if (image.length === 0) {
return data;
}
const caption = element.find('.caption').text();
const width = parseInt(image.width(), 10);
const height = parseInt(image.height(), 10);
return {
Url: element.data('url') || data.Url,
CaptionText: caption,
PreviewUrl: image.attr('src'),
Width: isNaN(width) ? null : width,
Height: isNaN(height) ? null : height,
Placement: this.findPosition(element.prop('class')),
};
},
/**
* Calculate placement from css class
*/
findPosition(cssClass) {
const alignments = [
'leftAlone',
'center',
'rightAlone',
'left',
'right',
];
if (typeof cssClass !== 'string') {
return '';
}
const classes = cssClass.split(' ');
return alignments.find((alignment) => (
classes.indexOf(alignment) > -1
));
},
insertRemote() {
const $field = this.getElement();
if (!$field) {
return false;
}
const editor = $field.getEditor();
if (!editor) {
return false;
}
const data = this.getData();
// Add base div
const base = jQuery('<div/>')
.attr('data-url', data.Url)
.attr('data-shortcode', 'embed')
.addClass(data.Placement)
.addClass('ss-htmleditorfield-file embed');
// Add placeholder image
const placeholder = jQuery('<img />')
.attr('src', data.PreviewUrl)
.addClass('placeholder');
// Set dimensions
if (data.Width) {
placeholder.attr('width', data.Width);
}
if (data.Height) {
placeholder.attr('height', data.Height);
}
// Add to base
base.append(placeholder);
// Add caption p tag
if (data.CaptionText) {
const caption = jQuery('<p />')
.addClass('caption')
.text(data.CaptionText);
base.append(caption);
}
// Find best place to put this embed
const node = $(editor.getSelectedNode());
let replacee = $(null);
if (node.length) {
replacee = node.filter(filter);
// Find find closest existing embed
if (replacee.length === 0) {
replacee = node.closest(filter);
}
// Fail over to check if the node is an image
if (replacee.length === 0) {
replacee = node.filter('img.placeholder');
}
}
// Inject
if (replacee.length) {
replacee.replaceWith(base);
} else {
// Otherwise insert the whole HTML content
editor.repaint();
editor.insertContent($('<div />').append(base.clone()).html(), { skip_undo: 1 });
}
editor.addUndo();
editor.repaint();
return true;
},
});
});
|
src/screens/App/screens/Listing/components/Posts/Post/index.js | yanglinz/reddio | import React from 'react';
import classNames from 'classnames';
import { playCommand } from 'state/reddit/actions';
import { isYoutube } from 'services/iframe-api/youtube';
import { isSoundcloud } from 'services/iframe-api/soundcloud';
import './index.scss';
function Post(props) {
const { post, posts, dispatch } = props;
const isPlayableSource = (
isYoutube(post.url) ||
isSoundcloud(post.url)
);
const isPlayable = !post.isSelf && isPlayableSource;
const postClassName = classNames(
'Post',
{ 'is-selfPost': post.isSelf },
{ 'is-playable': isPlayable },
{ 'is-unplayable': !isPlayable },
);
const playablePost = (
<div className={postClassName}>
<button onClick={() => dispatch(playCommand(post, posts))}>
play
</button>
<div>{post.title}</div>
</div>
);
const unplayablePost = (
<div className={postClassName}>
<div>{post.title}</div>
</div>
);
return isPlayable
? playablePost
: unplayablePost;
}
Post.propTypes = {
dispatch: React.PropTypes.func,
post: React.PropTypes.shape({
data: React.PropTypes.shape({
id: React.PropTypes.string,
}),
}),
};
module.exports = Post;
|
blueocean-material-icons/src/js/components/svg-icons/notification/ondemand-video.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const NotificationOndemandVideo = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-6l-7 4V7z"/>
</SvgIcon>
);
NotificationOndemandVideo.displayName = 'NotificationOndemandVideo';
NotificationOndemandVideo.muiName = 'SvgIcon';
export default NotificationOndemandVideo;
|
src/pages/client/Products.js | gramulos/EpsilonGroups | import React, { Component } from 'react';
import { Router, Route, Link } from 'react-router';
import Avatar from 'material-ui/lib/avatar';
import Card from 'material-ui/lib/card/card';
import RaisedButton from 'material-ui/lib/raised-button';
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 './Products.less';
import './Site.less';
import vt_image from '../../images/software/vt/soldier.png';
import td_printer from '../../images/3dPrinter.png';
export default class Body extends Component {
render() {
return (
<div className="container">
<div className="row no-margin card-container">
<br />
<div className="row eg-product-container">
<div className="col-lg-7 col-md-8 col-sm-12 col-xs-12">
<div className="eg-product-information">
<h1>Military shooting simulator</h1>
<div className="eg-product-description">The code name is "VT". Virtual trainer is assigned to train people for the purpose of enhancing their military skills and musketry.</div>
<Link to="/software/vt"><RaisedButton backgroundColor="#45408e" label="View product" secondary={true} /></Link>
</div>
</div>
<div className="col-lg-5 col-md-4 col-sm-12 col-xs-12 eg-product-image">
<img src={vt_image}/>
</div>
</div>
<div className="row eg-product-container">
<div className="col-lg-5 col-md-4 col-sm-12 col-xs-12 eg-product-image">
<img src={td_printer}/>
</div>
<div className="col-lg-7 col-md-8 col-sm-12 col-xs-12">
<div className="eg-product-information">
<h1>3D printer</h1>
<div className="eg-product-description">
Our printer offers extra camera printing, built-in control panel, the new print head with larger nozzles and many other features that make the printer faster and more productive.</div>
<Link to="/hardware/3d_printer"><RaisedButton backgroundColor="#45408e" label="View product" secondary={true} /></Link>
</div>
</div>
</div>
</div>
</div>
);
}
}
|
app/components/Settings/SensorBlock.js | TheCbac/MICA-Desktop | // @flow
/* **********************************************************
* File: components/Settings/SensorBlock.js
*
* Brief: React component displaying and interacting with
* the sensors of a device. Refactor of SensorComponent
*
* Authors: Craig Cheney
*
* 2017.09.26 CC - Rename component SensorBlock
* 2017.09.12 CC - Rename component from 'senGenComponent'
* to 'SensorComponent'
* 2017.09.05 CC - Document created
*
********************************************************* */
import React, { Component } from 'react';
import { Col, Row, Collapse, Well } from 'react-bootstrap';
import FontAwesome from 'react-fontawesome';
import ChannelSelector from './ChannelSelector';
import ParamSelector from './ParamSelector';
import ZeroBtn from './ZeroBtn';
import type { idType, sensorParamType } from '../../types/paramTypes';
import type { thunkType } from '../../types/functionTypes';
import type { setSensorChannelsActionT } from '../../types/actionTypes';
type StateType = {
open: boolean,
active: boolean
};
type PropsType = {
deviceId: idType,
sensorId: idType,
sensorSettings: sensorParamType,
/* Action Functions */
setSensorActive: (
deviceId: idType,
sensorId: idType,
newState: boolean
) => thunkType,
setSensorChannels: (
deviceId: idType,
sensorId: idType,
newChannels: number[]
) => setSensorChannelsActionT,
setSensorParams: (
deviceId: idType,
sensorId: idType,
paramName: string,
paramValue: number
) => thunkType,
zeroSensor: (
deviceId: idType,
sensorId: idType
) => thunkType
};
export default class SensorBlock extends Component<PropsType, StateType> {
/* Constructor function */
constructor(props: PropsType) {
super(props);
/* set the default state */
this.state = {
open: this.props.sensorSettings.active,
active: this.props.sensorSettings.active
};
}
/* */
toggleOpen(): void {
this.setState({ open: !this.state.open });
}
/* Style for the caret */
caretStyle() {
const style = {
transition: '',
textShadow: '',
color: '',
transform: ''
};
if (this.state.open) {
style.textShadow = 'white 0 0 20px';
style.color = 'white';
style.transition = 'all 2 linear';
style.transform = 'rotate(90deg)';
}
return style;
}
/* Power button style */
powerBtnStyle() {
const style = {
transform: 'rotate(-90deg)',
fontSize: '1em',
color: 'black',
textShadow: ''
};
if (this.state.active) {
style.transform = '';
style.textShadow = 'white 0 0 20px';
style.color = 'white';
}
return style;
}
/* Style of the name */
nameStyle() {
const style = {
color: '',
textShadow: ''
};
if (this.state.active) {
style.color = 'white';
style.textShadow = 'white 0 0 20px';
}
return style;
}
/* Return a component for selecting the channels */
getChannels() {
const channelVal = this.props.sensorSettings.channels;
const { deviceId, sensorId, setSensorChannels } = this.props;
return (
<ChannelSelector
deviceId={deviceId}
sensorId={sensorId}
channels={channelVal}
setSensorChannels={setSensorChannels}
/>
);
}
/* Returns the parameter selecting component */
getParams() {
const dynamicParamsObj = this.props.sensorSettings.dynamicParams;
const dynamicParamsKeys = Object.keys(dynamicParamsObj);
/* return a list of components */
const componentArray = [];
/* Push all of the dynamic parameters */
for (let i = 0; i < dynamicParamsKeys.length; i++) {
/* Get the name (key) and value of each parameter */
const key = dynamicParamsKeys[i];
const { value } = dynamicParamsObj[key];
if (key && value != null) {
componentArray.push(
<ParamSelector
key={i}
deviceId={this.props.deviceId}
sensorId={this.props.sensorId}
paramName={key}
paramValue={value}
setSensorParams={this.props.setSensorParams}
/>
);
}
}
return componentArray;
}
/* Toggle sensor power */
toggleSensorPower() {
const newActive = !this.state.active;
this.props.setSensorActive(
this.props.deviceId,
this.props.sensorId,
newActive
);
/* Toggle the state of the component and open/close the settings list */
this.setState({ active: newActive, open: newActive });
}
zero() {
const { deviceId, sensorId, zeroSensor } = this.props;
return (
<ZeroBtn
deviceId={deviceId}
sensorId={sensorId}
zeroSensor={zeroSensor}
/>
);
}
/* Render function */
render() {
const sensorStyle = {
fontFamily: 'Franklin Gothic Book',
fontSize: '1.5em',
};
const { name } = this.props.sensorSettings;
return (
<div>
<Row />
<Col md={5} xs={5} mdOffset={0} style={sensorStyle}>
<FontAwesome className='hoverGlow' style={this.caretStyle()} name='angle-right' size='lg' onClick={() => this.toggleOpen()} />
<span style={this.nameStyle()}> {name}</span>
{/* <FontAwesome
style={{ fontSize: '14px', verticalAlign: 'middle' }}
name={'thumb-tack'} size={'lg'}
/> */}
</Col>
<Col md={6} xs={6} mdOffset={0} style={sensorStyle}>
<hr style={{ borderColor: 'black', marginTop: '15px' }} />
</Col>
<Col md={1} xs={1} mdOffset={0} style={sensorStyle}>
<span className='pull-right' style={{ verticalAlign: 'middle', marginTop: '.375em' }}>
<FontAwesome className='pull-right hoverGlow' onClick={() => this.toggleSensorPower()} style={this.powerBtnStyle()} name='power-off' size='lg' />
</span>
</Col>
<Row />
<Col md={12} xs={12}>
<Collapse in={this.state.open}>
<div>
<Well>
<div>
{ this.getChannels() }
{ this.getParams() }
{ this.zero() }
</div>
</Well>
</div>
</Collapse>
</Col>
</div>
);
}
}
/* [] - END OF FILE */
|
src/svg-icons/image/brightness-4.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrightness4 = (props) => (
<SvgIcon {...props}>
<path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6z"/>
</SvgIcon>
);
ImageBrightness4 = pure(ImageBrightness4);
ImageBrightness4.displayName = 'ImageBrightness4';
ImageBrightness4.muiName = 'SvgIcon';
export default ImageBrightness4;
|
client/page/support/index.js | johngodley/redirection | /**
* External dependencies
*/
import React from 'react';
/**
* Internal dependencies
*/
import Help from './help';
import HttpTester from './http-tester';
import Status from './status';
const Support = () => {
return (
<>
<Status />
<HttpTester />
<Help />
</>
);
};
export default Support;
|
src/containers/shop/ItemBrowser.js | visa-innovation-sf/ldn-retail-demo | import React, { Component } from 'react';
import {
View,
Image,
Modal,
Alert,
ListView,
FlatList,
ScrollView,
StyleSheet,
Platform,
Dimensions,
Animated,
Easing,
TouchableOpacity,
TouchableHighlight,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import { connect } from 'react-redux';
import Carousel from 'react-native-snap-carousel';
import Product from './Product';
import { FirebaseImgRef } from '@constants/';
import { addToCart, removeFromCart, removeFromProducts } from '@redux/products/actions';
import * as NotificationActions from '@redux/notification/actions';
import * as Q from 'q';
import timer from 'react-native-timer';
import { ProductSlide } from '@components/shop/';
import { AppColors, AppStyles, AppSizes} from '@theme/';
import {
Alerts,
Button,
Text,
Card,
Spacer,
List,
ListItem,
FormInput,
FormLabel,
} from '@components/ui/';
const Screen = Dimensions.get('window');
/* Styles ==================================================================== */
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column'
},
browserContainer: {
position: 'absolute',
top: 0,
height: AppSizes.screen.height,
width: Screen.width,
backgroundColor: AppColors.base.greyLight,
overflow: 'hidden',
zIndex: 1,
},
infoHeaderContainer: {
height: 75
},
infoHeader: {
borderBottomWidth: 1,
paddingHorizontal: AppSizes.paddingSml,
height: 60,
backgroundColor: AppColors.brand.primary
},
infoIconContainer: {
position: 'absolute',
bottom: 0,
right: AppSizes.padding,
zIndex: 1
},
infoText: {
color: AppColors.base.white,
textAlign: 'center'
},
infoIcon: {
height: 35,
width: 35,
resizeMode: 'contain'
},
emptyListIcon: {
width: 70,
height: 60,
resizeMode: 'contain'
}
});
const mapStateToProps = state => ({
products: state.products.products
});
const mapDispatchToProps = (dispatch) => {
return {
addToCart: (item) => {
dispatch(addToCart(item));
},
removeFromCart: (item) => {
dispatch(removeFromCart(item));
},
removeFromProducts: (item) => {
dispatch(removeFromProducts(item));
},
showNotification: (message, deferred, okText, cancelText) => {
NotificationActions.showNotification(dispatch, message, deferred, okText, cancelText)
}
}
};
const defaultProps = {
timeout: 3000,
animationTime: 300,
top: 0,
topCollapsed: -40
};
//TODO separate container and view
class ItemBrowser extends Component {
timerName = 'ItemBrowserTimer';
constructor(props) {
super(props);
this.toggleInfoHeader = this.toggleInfoHeader.bind(this);
this.showRemoveConfirmationDialog = this.showRemoveConfirmationDialog.bind(this);
this.showAddConfirmationDialog = this.showAddConfirmationDialog.bind(this);
this.state = {
top: new Animated.Value(this.props.topCollapsed),
isInfoHeaderCollapsed: true,
currentProductIndex: 0,
slides: this.getSlides(props.products)
};
}
showAddConfirmationDialog(product) {
const deferred = Q.defer();
const message = 'Item added to cart. Continue shopping?';
this.props.showNotification(message, deferred, 'OK', 'Checkout');
deferred.promise.then(function () {
},
function () {
timer.setTimeout(this.timerName, () => {
Actions.shoppingCartTab();
}, 1000);
})
}
showRemoveConfirmationDialog(product) {
const deferred = Q.defer();
const message = 'Remove item from list?';
this.props.showNotification(message, deferred);
const self = this;
deferred.promise.then(function () {
timer.setTimeout(this.timerName, () => {
self.props.removeFromProducts(product);
}, 700);
});
}
toggleInfoHeader = () => {
Animated.timing(this.state.top, {
duration: this.props.animationTime,
toValue: this.state.isInfoHeaderCollapsed ? this.props.top : this.props.topCollapsed,
easing: Easing.quad
}).start();
}
getSlides = (products) => products.map((item, index) => {
return (
<ProductSlide index={index}
item={item}
addToCart={this.props.addToCart}
complementaryItems= {products}
removeFromCart={this.props.removeFromCart}
removeFromList={this.props.removeFromProducts}
></ProductSlide>
);
});
render = () => {
return (
<View style={styles.container}>
{/*Item browser layer*/}
<Animated.View style={[styles.browserContainer, {top: this.state.top}]}>
<View style={styles.infoHeaderContainer}>
<View style={styles.infoHeader}>
<Text style={[styles.infoText]}>
While you are shopping, any items you pick up will be added to the list below.
</Text>
</View>
<View style={styles.infoIconContainer}>
<TouchableOpacity onPress={()=>
{
this.setState({isInfoHeaderCollapsed : !this.state.isInfoHeaderCollapsed});
this.toggleInfoHeader();
}}>
<Image
source={require('../../assets/icons/icon-info-color.png')}
style={[styles.infoIcon]}
/>
</TouchableOpacity>
</View>
</View>
<Spacer size={30}></Spacer>
{this.state.slides.length === 0 &&
<View style={{backgroundColor: AppColors.base.white}}>
<Text style={[AppStyles.h3, AppStyles.padding, {textAlign: 'center'}]}>
You currently don't have any browsed items </Text>
<View style={[AppStyles.containerCentered, AppStyles.padding]}>
<Image
source={require('../../assets/icons/icon-list-empty.png')}
style={[styles.emptyListIcon]}
/>
</View>
</View>
}
< Carousel
ref={(carousel) => { this._carousel = carousel; }}
sliderWidth={AppSizes.screen.width}
itemWidth={AppSizes.screen.widthThreeQuarters}
itemheight={AppSizes.screen.height - 250}
enableMomentum={false}
scrollEndDragDebounceValue={50}
swipeThreshold={70}
contentContainerCustomStyle={{borderRadius: 20}}
>
{ this.state.slides }
</Carousel>
</Animated.View>
</View>
);
}
componentWillReceiveProps = (nextProps) => {
if (nextProps.products) {
this.setState({slides: this.getSlides(nextProps.products)});
}
}
componentWillUnmount() {
timer.clearTimeout(this.timerName);
}
}
ItemBrowser.defaultProps = defaultProps;
export default connect(mapStateToProps, mapDispatchToProps)(ItemBrowser);
|
lib/atom/marker.js | atom/github | import React from 'react';
import PropTypes from 'prop-types';
import {CompositeDisposable, Disposable} from 'event-kit';
import {autobind, extractProps} from '../helpers';
import {RefHolderPropType, RangePropType} from '../prop-types';
import RefHolder from '../models/ref-holder';
import {TextEditorContext} from './atom-text-editor';
import {MarkerLayerContext} from './marker-layer';
const MarkablePropType = PropTypes.shape({
markBufferRange: PropTypes.func.isRequired,
});
const markerProps = {
exclusive: PropTypes.bool,
reversed: PropTypes.bool,
invalidate: PropTypes.oneOf(['never', 'surround', 'overlap', 'inside', 'touch']),
};
export const MarkerContext = React.createContext();
export const DecorableContext = React.createContext();
class BareMarker extends React.Component {
static propTypes = {
...markerProps,
id: PropTypes.number,
bufferRange: RangePropType,
markableHolder: RefHolderPropType,
children: PropTypes.node,
onDidChange: PropTypes.func,
handleID: PropTypes.func,
handleMarker: PropTypes.func,
}
static defaultProps = {
onDidChange: () => {},
handleID: () => {},
handleMarker: () => {},
}
constructor(props) {
super(props);
autobind(this, 'createMarker', 'didChange');
this.markerSubs = new CompositeDisposable();
this.subs = new CompositeDisposable();
this.markerHolder = new RefHolder();
this.markerHolder.observe(marker => {
this.props.handleMarker(marker);
});
this.decorable = {
holder: this.markerHolder,
decorateMethod: 'decorateMarker',
};
}
componentDidMount() {
this.observeMarkable();
}
render() {
return (
<MarkerContext.Provider value={this.markerHolder}>
<DecorableContext.Provider value={this.decorable}>
{this.props.children}
</DecorableContext.Provider>
</MarkerContext.Provider>
);
}
componentDidUpdate(prevProps) {
if (prevProps.markableHolder !== this.props.markableHolder) {
this.observeMarkable();
}
if (Object.keys(markerProps).some(key => prevProps[key] !== this.props[key])) {
this.markerHolder.map(marker => marker.setProperties(extractProps(this.props, markerProps)));
}
this.updateMarkerPosition();
}
componentWillUnmount() {
this.subs.dispose();
}
observeMarkable() {
this.subs.dispose();
this.subs = new CompositeDisposable();
this.subs.add(this.props.markableHolder.observe(this.createMarker));
}
createMarker() {
this.markerSubs.dispose();
this.markerSubs = new CompositeDisposable();
this.subs.add(this.markerSubs);
const options = extractProps(this.props, markerProps);
this.props.markableHolder.map(markable => {
let marker;
if (this.props.id !== undefined) {
marker = markable.getMarker(this.props.id);
if (!marker) {
throw new Error(`Invalid marker ID: ${this.props.id}`);
}
marker.setProperties(options);
} else {
marker = markable.markBufferRange(this.props.bufferRange, options);
this.markerSubs.add(new Disposable(() => marker.destroy()));
}
this.markerSubs.add(marker.onDidChange(this.didChange));
this.markerHolder.setter(marker);
this.props.handleID(marker.id);
return null;
});
}
updateMarkerPosition() {
this.markerHolder.map(marker => marker.setBufferRange(this.props.bufferRange));
}
didChange(event) {
const reversed = this.markerHolder.map(marker => marker.isReversed()).getOr(false);
const oldBufferStartPosition = reversed ? event.oldHeadBufferPosition : event.oldTailBufferPosition;
const oldBufferEndPosition = reversed ? event.oldTailBufferPosition : event.oldHeadBufferPosition;
const newBufferStartPosition = reversed ? event.newHeadBufferPosition : event.newTailBufferPosition;
const newBufferEndPosition = reversed ? event.newTailBufferPosition : event.newHeadBufferPosition;
this.props.onDidChange({
oldRange: new Range(oldBufferStartPosition, oldBufferEndPosition),
newRange: new Range(newBufferStartPosition, newBufferEndPosition),
...event,
});
}
}
export default class Marker extends React.Component {
static propTypes = {
editor: MarkablePropType,
layer: MarkablePropType,
}
constructor(props) {
super(props);
this.state = {
markableHolder: RefHolder.on(props.layer || props.editor),
};
}
static getDerivedStateFromProps(props, state) {
const markable = props.layer || props.editor;
if (state.markableHolder.map(m => m === markable).getOr(markable === undefined)) {
return {};
}
return {
markableHolder: RefHolder.on(markable),
};
}
render() {
if (!this.state.markableHolder.isEmpty()) {
return <BareMarker {...this.props} markableHolder={this.state.markableHolder} />;
}
return (
<MarkerLayerContext.Consumer>
{layerHolder => {
if (layerHolder) {
return <BareMarker {...this.props} markableHolder={layerHolder} />;
} else {
return (
<TextEditorContext.Consumer>
{editorHolder => <BareMarker {...this.props} markableHolder={editorHolder} />}
</TextEditorContext.Consumer>
);
}
}}
</MarkerLayerContext.Consumer>
);
}
}
|
src/Option.js | VanCoding/react-select | import React from 'react';
import classNames from 'classnames';
const Option = React.createClass({
propTypes: {
children: React.PropTypes.node,
className: React.PropTypes.string, // className (based on mouse position)
instancePrefix: React.PropTypes.string.isRequired, // unique prefix for the ids (used for aria)
isDisabled: React.PropTypes.bool, // the option is disabled
isFocused: React.PropTypes.bool, // the option is focused
isSelected: React.PropTypes.bool, // the option is selected
onFocus: React.PropTypes.func, // method to handle mouseEnter on option element
onSelect: React.PropTypes.func, // method to handle click on option element
onUnfocus: React.PropTypes.func, // method to handle mouseLeave on option element
option: React.PropTypes.object.isRequired, // object that is base for that option
optionIndex: React.PropTypes.number, // index of the option, used to generate unique ids for aria
},
blockEvent (event) {
event.preventDefault();
event.stopPropagation();
if ((event.target.tagName !== 'A') || !('href' in event.target)) {
return;
}
if (event.target.target) {
window.open(event.target.href, event.target.target);
} else {
window.location.href = event.target.href;
}
},
handleMouseDown (event) {
event.preventDefault();
event.stopPropagation();
this.props.onSelect(this.props.option, event);
},
handleMouseEnter (event) {
this.onFocus(event);
},
handleMouseMove (event) {
this.onFocus(event);
},
handleTouchEnd(event){
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if(this.dragging) return;
this.handleMouseDown(event);
},
handleTouchMove (event) {
// Set a flag that the view is being dragged
this.dragging = true;
},
handleTouchStart (event) {
// Set a flag that the view is not being dragged
this.dragging = false;
},
onFocus (event) {
if (!this.props.isFocused) {
this.props.onFocus(this.props.option, event);
}
},
render () {
var { option, instancePrefix, optionIndex } = this.props;
var className = classNames(this.props.className, option.className);
return option.disabled ? (
<div className={className}
onMouseDown={this.blockEvent}
onClick={this.blockEvent}>
{this.props.children}
</div>
) : (
<div className={className}
style={option.style}
role="option"
onMouseDown={this.handleMouseDown}
onMouseEnter={this.handleMouseEnter}
onMouseMove={this.handleMouseMove}
onTouchStart={this.handleTouchStart}
onTouchMove={this.handleTouchMove}
onTouchEnd={this.handleTouchEnd}
id={instancePrefix + '-option-' + optionIndex}
title={option.title}>
{this.props.children}
</div>
);
}
});
module.exports = Option;
|
src/svg-icons/action/touch-app.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionTouchApp = (props) => (
<SvgIcon {...props}>
<path d="M9 11.24V7.5C9 6.12 10.12 5 11.5 5S14 6.12 14 7.5v3.74c1.21-.81 2-2.18 2-3.74C16 5.01 13.99 3 11.5 3S7 5.01 7 7.5c0 1.56.79 2.93 2 3.74zm9.84 4.63l-4.54-2.26c-.17-.07-.35-.11-.54-.11H13v-6c0-.83-.67-1.5-1.5-1.5S10 6.67 10 7.5v10.74l-3.43-.72c-.08-.01-.15-.03-.24-.03-.31 0-.59.13-.79.33l-.79.8 4.94 4.94c.27.27.65.44 1.06.44h6.79c.75 0 1.33-.55 1.44-1.28l.75-5.27c.01-.07.02-.14.02-.2 0-.62-.38-1.16-.91-1.38z"/>
</SvgIcon>
);
ActionTouchApp = pure(ActionTouchApp);
ActionTouchApp.displayName = 'ActionTouchApp';
ActionTouchApp.muiName = 'SvgIcon';
export default ActionTouchApp;
|
app/components/Chrome.js | alexindigo/ndash | import React, { Component } from 'react';
import {
BackAndroid,
KeyboardAvoidingView,
Platform,
StatusBar,
View
} from 'react-native';
import Drawer from 'react-native-drawer';
import StatusBarSizeIOS from 'react-native-status-bar-size';
import Message from './Message';
import Navbar from './Navbar';
import styles from '../styles';
export default class Chrome extends Component {
state = {
isMenuOpen: false,
isLandscape: false,
backRoute: null,
title: '',
statusBarHeight: StatusBarSizeIOS.currentHeight,
}
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', this.onHardwareBack.bind(this));
StatusBarSizeIOS.addEventListener('willChange', this.onStatusBarSizeChange.bind(this));
}
componentWillUnmount() {
BackAndroid.removeEventListener('hardwareBackPress', this.onHardwareBack.bind(this));
StatusBarSizeIOS.removeEventListener('willChange', this.onStatusBarSizeChange.bind(this));
}
componentDidUpdate(prevProps, prevState) {
// only when side menu changed it's state
if (prevState.isMenuOpen !== this.state.isMenuOpen) {
this.finishTransition();
}
// update statusBarHeight
this.onStatusBarSizeChange(this.state.statusBarHeight);
}
onHardwareBack() {
if (this.state.isMenuOpen) {
this.setState({ isMenuOpen: false });
return true;
}
if (this.state.backRoute) {
this.state.backRoute();
return true;
}
return false;
}
onStatusBarSizeChange(statusBarHeight) {
// when landscape it's always `0`, since we hide status bar
// otherwise it's at least 20 for statusbar
// and Android isn't as flexible about it's StatusBar
statusBarHeight = this.state.isLandscape || Platform.OS == 'android'
? 0
: Math.max(20, statusBarHeight)
;
if (statusBarHeight != this.state.statusBarHeight) {
// on landscape it's always hidden
this.setState({ statusBarHeight });
}
}
onLayoutChange(e) {
const { width, height } = e.nativeEvent.layout;
// close menu on layout change
if (this.state.isLandscape != (width > height)) {
this.setState({ isMenuOpen: false });
}
this.setState({ isLandscape: width > height });
}
updateRoute(route, backRoute) {
let title = route.title;
if (typeof title == 'function') {
title = title(route);
}
requestAnimationFrame(() => {
this.setState({title, backRoute, isMenuOpen: false});
});
}
startTransition() {
this.props.onTransition(true);
}
finishTransition() {
requestAnimationFrame(() => {
this.props.onTransition(false);
});
}
renderMenu() {
return React.cloneElement(this.props.menu, {
ref : 'menu',
style : styles.menu,
isOpen: this.state.isMenuOpen,
isLandscape: this.state.isLandscape,
statusBarHeight: this.state.statusBarHeight
});
}
renderNavbar() {
return (
this.props.isSplash
? null
: <Navbar
statusBarHeight={this.state.statusBarHeight}
isLandscape={this.state.isLandscape}
isMenuOpen={this.state.isMenuOpen}
title={this.state.title}
onHomeButton={() => { this.startTransition(); this.setState({isMenuOpen: true}) }}
onBack={this.state.backRoute}
/>
);
}
renderNavigation() {
const navigation = React.cloneElement(this.props.children, {
renderHeader: this.renderNavbar.bind(this)
});
return navigation;
}
render() {
return (
<View
style={styles.base}
onLayout={this.onLayoutChange.bind(this)}
>
<StatusBar
backgroundColor={styles.statusBar.backgroundColor}
/>
<Drawer
disabled={this.props.isSplash}
open={this.state.isMenuOpen}
content={this.renderMenu()}
side="right"
type="static"
tapToClose={true}
captureGestures={true}
panOpenMask={10}
openDrawerOffset={100}
tweenHandler={Drawer.tweenPresets.parallax}
onOpen={() => this.setState({isMenuOpen: true}) }
onClose={() => this.setState({isMenuOpen: false}) }
>
<KeyboardAvoidingView
behavior="padding"
style={styles.container}
>
{this.renderNavigation()}
</KeyboardAvoidingView>
</Drawer>
{
this.props.messageToDisplay
? <Message
inProgress={this.props.inProgress}
message={this.props.messageToDisplay}
/>
: null
}
</View>
);
}
}
|
src/components/__tests__/PaginationTest.js | ttrentham/Griddle | import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import Pagination from '../Pagination';
test('renders', (t) => {
const wrapper = shallow(<Pagination />);
t.true(wrapper.matchesElement(<div />));
});
test('renders with style', (t) => {
const style = { backgroundColor: "#EDEDED" };
const wrapper = shallow(<Pagination style={style} />);
t.true(wrapper.matchesElement(<div style={{ backgroundColor: '#EDEDED'}} />));
});
test('renders with className', (t) => {
const wrapper = shallow(<Pagination className="className" />);
t.true(wrapper.matchesElement(<div className="className" />));
});
test('renders children', (t) => {
const next = () => <button>Next</button>;
const previous = () => <button>Previous</button>;
const pageDropdown = () => <div>Dropdown</div>;
const wrapper = shallow(<Pagination
Next={next}
Previous={previous}
PageDropdown={pageDropdown}
/>);
const previousRendered = wrapper.childAt(0);
t.is(previousRendered.html(), '<button>Previous</button>');
const pageDropdownRendered = wrapper.childAt(1);
t.is(pageDropdownRendered.html(), '<div>Dropdown</div>');
const nextRendered = wrapper.childAt(2);
t.is(nextRendered.html(), '<button>Next</button>');
});
|
source/patterns/react-utils/portal/docs/portal.example.js | apparena/patterns | import React from 'react';
import {Button, Portal} from 'apparena-patterns-react';
export default function PortalExample() {
return (
<Portal
attachToNode={document.getElementById('root')}
>
<div style={{position: 'fixed', top: 0, right: 0, zIndex: 200}}>
<Button
type="outline-primary"
>
My Portal Button
</Button>
</div>
</Portal>
);
} |
app/components/ThumbGrid.js | fakob/electron-test-v003 | // @flow
import React from 'react';
import PropTypes from 'prop-types';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import Thumb from './Thumb';
import ThumbGridHeader from './ThumbGridHeader';
import styles from './ThumbGrid.css';
const SortableThumb = SortableElement(Thumb);
const ThumbGrid = (
// props
{ thumbs, file, columnWidth, controlersAreVisible,
onToggleClick, onRemoveClick, onInPointClick, onOutPointClick,
onBackClick, onForwardClick,
onMouseOverResult, onMouseOutResult
}
) => {
return (
<div
className={styles.grid}
style={{
width: columnWidth,
}}
id="ThumbGrid"
>
<ThumbGridHeader
file={file}
/>
{thumbs.map(thumb =>
<SortableThumb
key={thumb.id}
indexValue={thumb.index}
width={file.width}
height={file.height}
controlersAreVisible={(thumb.id === controlersAreVisible)}
{...thumb}
onToggle={() => onToggleClick(file.id, thumb.id)}
onRemove={() => onRemoveClick(file.id, thumb.id)}
onInPoint={() => onInPointClick(file, thumbs, thumb.id, thumb.frameNumber)}
onOutPoint={() => onOutPointClick(file, thumbs, thumb.id, thumb.frameNumber)}
onBack={() => onBackClick(file.id, thumb.id, thumb.frameNumber)}
onForward={() => onForwardClick(file.id, thumb.id, thumb.frameNumber)}
onOver={() => onMouseOverResult(thumb.id)}
onOut={() => onMouseOutResult()}
/>
)}
</div>
);
};
ThumbGrid.defaultProps = {
controlersAreVisible: 'false'
};
ThumbGrid.propTypes = {
thumbs: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
index: PropTypes.number.isRequired,
hidden: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}).isRequired).isRequired,
// file: PropTypes.object,
columnWidth: PropTypes.number.isRequired,
controlersAreVisible: PropTypes.string.isRequired,
onToggleClick: PropTypes.func.isRequired,
onRemoveClick: PropTypes.func.isRequired,
onInPointClick: PropTypes.func.isRequired,
onOutPointClick: PropTypes.func.isRequired,
onBackClick: PropTypes.func.isRequired,
onForwardClick: PropTypes.func.isRequired,
onMouseOverResult: PropTypes.func.isRequired,
onMouseOutResult: PropTypes.func.isRequired,
};
const SortableThumbGrid = SortableContainer(ThumbGrid);
// export default ThumbGrid;
export default SortableThumbGrid;
|
webapp/src/widgets/PasswordInput.js | cpollet/itinerants | import React from 'react';
import styles from './PasswordInput.css';
class PasswordInput extends React.Component {
render() {
return (
<input className={styles.component}
type="password"
placeholder={this.props.placeholder}
onChange={this.props.onChange}/>
);
}
}
PasswordInput.propTypes = {
placeholder: React.PropTypes.string,
onChange: React.PropTypes.func
};
export default PasswordInput;
|
app/javascript/mastodon/features/keyboard_shortcuts/index.js | blackle/mastodon | import React from 'react';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'keyboard_shortcuts.heading', defaultMessage: 'Keyboard Shortcuts' },
});
@injectIntl
export default class KeyboardShortcuts extends ImmutablePureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
render () {
const { intl } = this.props;
return (
<Column icon='question' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<div className='keyboard-shortcuts scrollable optionally-scrollable'>
<table>
<thead>
<tr>
<th><FormattedMessage id='keyboard_shortcuts.hotkey' defaultMessage='Hotkey' /></th>
<th><FormattedMessage id='keyboard_shortcuts.description' defaultMessage='Description' /></th>
</tr>
</thead>
<tbody>
<tr>
<td><kbd>r</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.reply' defaultMessage='to reply' /></td>
</tr>
<tr>
<td><kbd>m</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.mention' defaultMessage='to mention author' /></td>
</tr>
<tr>
<td><kbd>p</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.profile' defaultMessage="to open author's profile" /></td>
</tr>
<tr>
<td><kbd>f</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.favourite' defaultMessage='to favourite' /></td>
</tr>
<tr>
<td><kbd>b</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.boost' defaultMessage='to boost' /></td>
</tr>
<tr>
<td><kbd>enter</kbd>, <kbd>o</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.enter' defaultMessage='to open status' /></td>
</tr>
<tr>
<td><kbd>x</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toggle_hidden' defaultMessage='to show/hide text behind CW' /></td>
</tr>
<tr>
<td><kbd>up</kbd>, <kbd>k</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.up' defaultMessage='to move up in the list' /></td>
</tr>
<tr>
<td><kbd>down</kbd>, <kbd>j</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.down' defaultMessage='to move down in the list' /></td>
</tr>
<tr>
<td><kbd>1</kbd>-<kbd>9</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.column' defaultMessage='to focus a status in one of the columns' /></td>
</tr>
<tr>
<td><kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.compose' defaultMessage='to focus the compose textarea' /></td>
</tr>
<tr>
<td><kbd>alt</kbd>+<kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toot' defaultMessage='to start a brand new toot' /></td>
</tr>
<tr>
<td><kbd>backspace</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.back' defaultMessage='to navigate back' /></td>
</tr>
<tr>
<td><kbd>s</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.search' defaultMessage='to focus search' /></td>
</tr>
<tr>
<td><kbd>esc</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.unfocus' defaultMessage='to un-focus compose textarea/search' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>h</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.home' defaultMessage='to open home timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.notifications' defaultMessage='to open notifications column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>l</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.local' defaultMessage='to open local timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>t</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.federated' defaultMessage='to open federated timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>d</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.direct' defaultMessage='to open direct messages column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>s</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.start' defaultMessage='to open "get started" column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>f</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.favourites' defaultMessage='to open favourites list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>p</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.pinned' defaultMessage='to open pinned toots list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>u</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.my_profile' defaultMessage='to open your profile' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>b</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.blocked' defaultMessage='to open blocked users list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>m</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.muted' defaultMessage='to open muted users list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>r</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.requests' defaultMessage='to open follow requests list' /></td>
</tr>
<tr>
<td><kbd>?</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.legend' defaultMessage='to display this legend' /></td>
</tr>
</tbody>
</table>
</div>
</Column>
);
}
}
|
src/TxRegionsInput.js | tiffon/txregions | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import MarkedRanges from './MarkedRanges';
import { markEmail, markUrls } from './markers';
import { combineValidators } from './presets';
import { foldWhitespace, KEY_CODES } from './strings';
import { filteredMap, makeSelectionRange, positiveNumericPropCheck } from './utils';
import { makeValidators, validatorDefaults, validatorsPropCheck } from './validators';
const noOp = function(){};
const warnFn = (console.error || console.warn || console.log || function(){}).bind(console);
const getPatternValidator = (function() {
const cache = {};
function getPatternValidator(value) {
if (value in cache) {
return cache[value];
}
let rx;
try {
rx = new RegExp(value);
} catch (error) {
warnFn(`Invalid pattern regex: ${error}\n${error.stack}`);
return;
}
return cache[value] = makeValidators({pattern: rx});
}
return getPatternValidator;
})();
export const classNames = {
email: 'txr-email',
nonDigits: 'txr-non-digit txr-invalid',
nonEmail: 'txr-non-email txr-invalid',
nonInt: 'txr-non-int txr-invalid',
nonNumeric: 'txr-non-numeric txr-invalid',
nonUint: 'txr-non-uint txr-invalid',
nonUrl: 'txr-non-url txr-invalid',
tooLong: 'txr-too-long txr-invalid',
url: 'txr-url'
};
export default class TxRegionsInput extends Component {
static getDerivedStateFromProps(props, state) {
if (!('value' in props) || state.raw === props.value) {
return null
}
return {raw: props.value == null ? '' : String(props.value)}
}
constructor(props) {
super(props);
const
initialValue = props.defaultValue || props.value || '',
validators = combineValidators(props.validators, props.preset);
this.state = {
clean: '',
cleanCaretPos: 0,
hasFocus: false,
raw: initialValue,
rawCaretPos: 0
};
this._valueHistory = [initialValue];
this._caretHistory = [0];
this._historyPos = 0;
this._wrapper = undefined;
this._elm = undefined;
this._input = undefined;
// for checking if the content has changed
this._txContent = undefined;
// track number of descendants bc <enter> causes <div><br></div>
// to be inserted on [contenteditable] elements but does not affect
// the `textContent` of the [contenteditable] element
this._numDescendants = undefined;
this._marker = new MarkedRanges();
this._markFn = [this._marker.markRange.bind(this._marker)];
// ux state related properties
this._uxInitialValue = initialValue;
this._uxValueChanged = false;
this._uxHadFocus = false;
// validity related
if (validators) {
this._validators = makeValidators(validators, props.invalidClassName);
} else {
this._validators = undefined;
}
this._violations = undefined;
// cache the foldWhitespace processing of state.raw
this._cleanCacheSrc = undefined;
this._cleanCacheValue = undefined;
}
get clean() {
if (this.state.raw === this._cleanCacheSrc) {
return this._cleanCacheValue;
}
this._cleanCacheSrc = this.state.raw;
return this._cleanCacheValue = foldWhitespace(this._cleanCacheSrc);
}
get raw() {
return this.state.raw;
}
_stepBackInHistory() {
const
max = this._valueHistory.length - 1,
raw = this.state.raw,
caret = this.state.rawCaretPos;
var r,
c;
while (this._historyPos < max) {
this._historyPos++;
r = this._valueHistory[this._historyPos];
c = this._caretHistory[this._historyPos];
if (r !== raw || c !== caret) {
this._setRaw(r, c, true);
return;
}
}
}
_stepForwardInHistory() {
const
raw = this.state.raw,
caret = this.state.rawCaretPos;
var r,
c;
while (this._historyPos > 0) {
this._historyPos--;
r = this._valueHistory[this._historyPos];
c = this._caretHistory[this._historyPos];
if (r !== raw || c !== caret) {
this._setRaw(r, c, true);
return;
}
}
}
_addToHistory(value, caret) {
const maxHistory = +this.props.maxHistory;
if (this._historyPos) {
// have already stepped back in history, so need to clear
// a bit of history before adding to the history
this._valueHistory.splice(0, this._historyPos);
this._caretHistory.splice(0, this._historyPos);
this._historyPos = 0;
}
this._valueHistory.unshift(value);
this._caretHistory.unshift(caret);
if (maxHistory && this._valueHistory.length > maxHistory) {
this._valueHistory.length = maxHistory;
this._caretHistory.length = maxHistory;
}
}
_updateViolations(markRange) {
const
clean = this.clean,
max = +this.props.maxLength,
min = +this.props.minLength,
pattern = this.props.pattern,
isRequired = !!this.props.required,
shouldMark = !('markInvalid' in this.props) || !!this.props.markInvalid ? true : undefined,
invalidClassName = this.props.invalidClassName || validatorDefaults.className;
let value = this._validators ? this._validators.exec(clean, shouldMark && markRange) : '';
if (max && max > 0 && clean.length > max) {
value += ' maxLength';
if (shouldMark && markRange) {
markRange(max, clean.length, invalidClassName);
}
}
if (clean.length && min && min > 0 && min > clean.length) {
value += ' minLength';
if (shouldMark && markRange) {
markRange(0, clean.length, invalidClassName);
}
}
if (pattern) {
const patternValidator = getPatternValidator(pattern);
if (patternValidator) {
const patternViolation = patternValidator.exec(clean, shouldMark && markRange);
if (patternViolation) {
value += ` ${patternViolation}`;
}
}
}
if (isRequired && !clean) {
value += ' required';
}
this._violations = value;
}
_setRaw(value, caret, focus) {
if (this.props.onRawChange) {
this.props.onRawChange({
caret: caret,
raw: value
});
}
if (!('value' in this.props)) {
this.setState({
hasFocus: focus,
raw: value,
rawCaretPos: caret
})
} else if (!('caret' in this.props)) {
this.setState({
hasFocus: focus,
rawCaretPos: caret
});
}
}
_findSelectionOffset() {
var sel = document.getSelection(),
rng = sel.rangeCount && sel.getRangeAt(0),
node = rng && rng.endContainer,
offset = rng && rng.endOffset;
if (!rng) {
return undefined;
}
if (!this._elm.contains(node)) {
return 0;
}
while (node !== this._elm) {
while (node.previousSibling) {
node = node.previousSibling;
if (node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE) {
offset += node.textContent.length;
}
}
node = node.parentNode;
}
return offset;
}
_setSelection() {
var sel = document.getSelection(),
str = this.state.raw.slice(0, this.state.rawCaretPos),
cleanCaretPos = foldWhitespace(str).length,
range = makeSelectionRange(this._elm, cleanCaretPos)
if (!range) {
range = document.createRange();
range.selectNodeContents(this._elm);
range.collapse(false);
}
sel.removeAllRanges();
sel.addRange(range);
}
_forceHtml() {
const
clean = this.clean,
markFn = this._markFn[0];
let markers = this.props.markers,
i,
ci,
rng,
tx,
span,
rngClasses;
this._elm.innerHTML = '';
if (!clean) {
this._txContent = this._elm.textContent;
this._numDescendants = this._elm.childNodes.length;
return '';
}
this._marker.reset();
if (typeof markers === 'function') {
markers = [markers];
i = 1;
} else {
i = markers ? markers.length : 0;
}
while (i--) {
markers[i](clean, markFn, this, classNames);
}
// process the violations -- pass the marker function so the validators
// can (optionally) mark the invalid text
this._updateViolations(markFn);
const
ranges = this._marker.getRanges(),
rmax = ranges.length,
frag = document.createDocumentFragment();
i = 0;
ci = 0;
for (; i < rmax; i++) {
rng = ranges[i];
if (rng.start > ci) {
tx = document.createTextNode(clean.slice(ci, rng.start));
frag.appendChild(tx);
}
span = document.createElement('span');
rngClasses = rng.classes.join(' ').split(/\s+/g);
span.classList.add.apply(span.classList, rngClasses);
span.textContent = clean.slice(rng.start, rng.end);
frag.appendChild(span);
ci = rng.end;
}
if (ci < clean.length) {
tx = document.createTextNode(clean.slice(ci));
frag.appendChild(tx);
}
this._elm.appendChild(frag);
this._txContent = this._elm.textContent;
this._numDescendants = this._elm.querySelectorAll('*').length;
// set the violations
if (this._violations) {
this._wrapper.setAttribute('data-violations', this._violations);
} else {
this._wrapper.removeAttribute('data-violations');
}
}
_emitUpdate() {
var data;
if (typeof this.props.onUpdate !== 'function') {
return;
}
data = {
clean: this.clean,
component: this,
isValid: !this._violations,
raw: this.state.raw,
violations: this._violations || undefined
};
if (this._input) {
data.input = this._input;
data.value = this._input.value;
}
this.props.onUpdate(data);
}
_handleChange() {
// if a change occurred, note the new text and caret position
const
raw = this._elm.textContent,
numDescendants = this._elm.querySelectorAll('*').length,
hasFocus = this._elm === document.activeElement,
caretPos = this._findSelectionOffset();
// if nothing changed, ignore this callback
if (raw === this._txContent && numDescendants === this._numDescendants) {
return;
}
this._uxValueChanged = true;
// reset the content back to the last known state
this._forceHtml();
if (hasFocus) {
this._setSelection();
}
this._setRaw(raw, caretPos, hasFocus);
}
_handleFocus() {
this._uxHadFocus = true;
// setting the state in the onFocus handler directly clobbers the
// initial cursor position, so set the state asynchronously
setTimeout(() => {
this.setState({
hasFocus: true,
rawCaretPos: this._findSelectionOffset()
});
}, 0)
}
_handleBlur() {
this.setState({hasFocus: false});
}
_handleKeyDown(event) {
if (event.keyCode === KEY_CODES.ENTER) {
event.preventDefault();
if (this.props.onEnterKeyDown) {
const data = {
metaKey: event.metaKey,
shiftKey: event.shiftKey,
clean: this.clean,
component: this,
isValid: !this._violations,
raw: this.state.raw,
violations: this._violations || undefined
};
if (this._input) {
data.input = this._input;
data.value = this._input.value;
}
this.props.onEnterKeyDown(data);
}
} else if (event.metaKey && event.keyCode === KEY_CODES.Z) {
event.preventDefault();
this._isUndo = true;
if (event.shiftKey) {
this._stepForwardInHistory();
} else {
this._stepBackInHistory();
}
}
}
componentDidMount() {
this._uxInitialValue = this.props.defaultValue || this.props.value || '';
this.setState({
raw: this._uxInitialValue,
rawCaretPos: 0
});
if (this._input) {
this._input.value = this._uxInitialValue;
}
this._forceHtml();
if (this._input) {
// mark the input as `:invalid` if there are violations
this._input.setCustomValidity(this._violations || '');
}
this._emitUpdate();
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextState.hasFocus !== this.state.hasFocus ||
nextState.raw !== this.state.raw ||
nextState.rawCaretPos !== this.state.rawCaretPos ||
!!this.props.dynamicMarkers && this.props.markers !== nextProps.markers
);
}
componentDidUpdate() {
this._forceHtml();
if (this.state.hasFocus && this.state.rawCaretPos != null) {
this._setSelection();
}
if (this._isUndo) {
this._isUndo = false;
} else {
this._addToHistory(this.state.raw, this.state.hasFocus ? this.state.rawCaretPos : this.state.raw.length);
}
if (this._input) {
// mark the input as `:invalid` if there are violations
this._input.setCustomValidity(this._violations || '');
}
this._emitUpdate();
}
render() {
this._updateViolations();
const
p = this.props,
clean = this.clean,
editableProps = p.setEditableProps || {},
wrapperProps = p.setWrapperProps || {},
violations = this._violations ? {'data-violations': this._violations} : {};
editableProps.contentEditable = true;
let uxFocus,
uxChanged,
input,
inputProps;
uxChanged = this._uxValueChanged ? 'changed-done' : 'changed-never';
if (this.state.hasFocus) {
uxFocus = 'focus-now ';
} else if (this._uxHadFocus) {
uxFocus = 'focus-had ';
} else {
uxFocus = 'focus-never ';
}
if (p.input) {
inputProps = p.setInputProps || {};
input = (
// Use input type="text" so can still manage the validity
// (`:invalid`) manually (type="hidden" ignore custom validity).
// The `hidden` attribute takes care of making it invisible. Use
// a `noOp` onChange handler to get rid of the react warning.
<input
ref={(elm) => this._input = elm}
hidden
type="text"
onChange={noOp}
name={typeof p.input === 'string' ? p.input : ''}
value={clean.trim()}
{...inputProps} />
);
}
return (
<div
ref={elm => this._wrapper = elm}
{...wrapperProps}
{...violations}
data-ux-state={uxFocus + uxChanged}
>
{input}
<div
ref={(elm) => this._elm = elm}
onBlur={this._handleBlur.bind(this)}
onFocus={this._handleFocus.bind(this)}
onInput={this._handleChange.bind(this)}
onKeyDown={this._handleKeyDown.bind(this)}
data-placeholder={clean ? '' : p.placeholder}
spellCheck={p.spellCheck}
{...editableProps} />
{p.children}
</div>
);
}
}
TxRegionsInput.propTypes = {
defaultValue: PropTypes.string,
dynamicMarkers: PropTypes.bool,
input: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
invalidClassName: PropTypes.string,
markers: PropTypes.oneOfType([PropTypes.func, PropTypes.array]),
markInvalid: PropTypes.bool,
maxHistory: positiveNumericPropCheck,
maxLength: positiveNumericPropCheck,
minLength: positiveNumericPropCheck,
pattern: PropTypes.string,
onEnterKeyDown: PropTypes.func,
onUpdate: PropTypes.func,
onRawChange: PropTypes.func,
placeholder: PropTypes.string,
required: PropTypes.bool,
setEditableProps: PropTypes.object,
setInputProps: PropTypes.object,
setWrapperProps: PropTypes.object,
spellCheck: PropTypes.bool,
validators: validatorsPropCheck,
value: PropTypes.string,
};
TxRegionsInput.defaultProps = {
defaultValue: '',
markers: undefined,
maxHistory: 100,
placeholder: '',
spellCheck: false
};
TxRegionsInput.defaultMarkers = TxRegionsInput.defaultProps.markers;
|
stories/enter-leave-animations.stories.js | joshwcomeau/react-flip-move | import React from 'react';
import { storiesOf } from '@storybook/react';
import FlipMoveWrapper from './helpers/FlipMoveWrapper';
import FlipMoveListItem from './helpers/FlipMoveListItem';
['div', FlipMoveListItem].forEach(type => {
const typeLabel = type === 'div' ? 'native' : 'composite';
storiesOf(`Enter/Leave Animations - ${typeLabel}`, module)
.add('default (elevator preset)', () => <FlipMoveWrapper itemType={type} />)
.add('default (elevator preset) with constantly change item', () => (
<FlipMoveWrapper itemType={type} applyContinuousItemUpdates />
))
.add('preset - fade', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: 'fade',
leaveAnimation: 'fade',
}}
/>
))
.add('preset - accordionVertical', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: 'accordionVertical',
leaveAnimation: 'accordionVertical',
}}
/>
))
.add('preset - accordionHorizontal', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: 'accordionHorizontal',
leaveAnimation: 'accordionHorizontal',
}}
flipMoveContainerStyles={{
whiteSpace: 'nowrap',
}}
listItemStyles={{
display: 'inline-block',
maxWidth: '150px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
borderRight: '1px solid #DDD',
}}
/>
))
.add('preset - mixed', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: 'fade',
leaveAnimation: 'elevator',
}}
/>
))
.add('custom Enter animation', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: {
from: {
transform: 'translateY(-100px) scaleY(0)',
},
to: {
transform: '',
},
},
}}
/>
))
.add('custom Enter and Leave animation, 2D rotate', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: {
from: { transform: 'translateY(-100px) rotate(90deg) scale(0)' },
to: { transform: '' },
},
leaveAnimation: {
from: { transform: '' },
to: { transform: 'translateY(100px) rotate(-90deg) scale(0)' },
},
}}
/>
))
.add('custom Enter and Leave animation, 3D rotate', () => (
<FlipMoveWrapper
itemType={type}
flipMoveContainerStyles={{ perspective: 500 }}
flipMoveProps={{
duration: 1000,
enterAnimation: {
from: { transform: 'rotateX(180deg)', opacity: 0 },
to: { transform: '' },
},
leaveAnimation: {
from: { transform: '' },
to: { transform: 'rotateX(180deg)', opacity: 0 },
},
}}
/>
))
.add('boolean - `false` enter (disabled enter)', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: false,
}}
/>
))
.add('boolean - `false` enter/leave (disabled enter/leave)', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: false,
leaveAnimation: false,
}}
/>
))
.add('boolean - `true` (default preset)', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: true,
leaveAnimation: true,
}}
/>
))
.add('invalid preset (default preset)', () => (
<FlipMoveWrapper
itemType={type}
flipMoveProps={{
enterAnimation: 'fsdajfsdhjhskfhas',
leaveAnimation: 'fsdifjdsoafhasfnsiubgs',
}}
/>
));
});
|
src/slides/six/arrow-functions.js | brudil/slides-es6andbeyond | import React from 'react';
import Radium from 'radium';
import Snippet from '../../Snippet';
import {bindShowHelper} from '../../utils';
const styles = {
inlinePre: {
display: 'inline'
},
slide: {
textAlign: 'center'
}
};
const sourceSteps = [
`
name => \`Hey, \${name}!\`; // implicit return
`,
`
() => console.log(this); // lexical this
`,
`
(first, second) => {
return first * second;
}
`,
`
actionName => {action: actionName} // don't even
`,
`
actionName => ({action: actionName}) // don't even
`,
`
list.map(function(item) {
return item.name;
});
`,
`
list.map(item => item.name);
`
];
@Radium
export default class ArrowFunctions extends React.Component {
static actionCount = 6;
static propTypes = {
actionIndex: React.PropTypes.number.isRequired,
style: React.PropTypes.object.isRequired
}
render() {
const {actionIndex} = this.props;
const show = bindShowHelper(actionIndex);
return (
<div style={[this.props.style, styles.slide]}>
<h1>() => 'Arrow functions!'</h1>
<Snippet source={show.withArray(sourceSteps, 0)} />
</div>
);
}
}
|
src/svg-icons/action/thumb-up.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionThumbUp = (props) => (
<SvgIcon {...props}>
<path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z"/>
</SvgIcon>
);
ActionThumbUp = pure(ActionThumbUp);
ActionThumbUp.displayName = 'ActionThumbUp';
export default ActionThumbUp;
|
web/app/pages/signup.js | bitemyapp/serials | // @flow
import React from 'react'
import {FormSection} from '../comp'
import {Users} from '../model/user'
import {makeUpdate} from '../data/update'
import {LogoPage} from './login'
import {Signup, signup, invitesFind, Invite, emptyInvite} from '../model/invite'
import {EmailLink} from '../books/support'
import {Alerts} from '../model/alert'
import {transitionTo, Routes} from '../router'
var emptySignup = function(invite):Signup {
return {
firstName: '',
lastName: '',
email: invite.email,
code: invite.code,
password: '',
passwordConfirmation: ''
}
}
type SignupProps = {
alert: any;
loaded: boolean;
invite: Invite;
}
export class SignupPage extends React.Component {
props: SignupProps;
static load(params) {
return {invite: invitesFind(params.code)}
}
onSignup(s:Signup) {
signup(s)
.then(() => Users.refresh())
.then(function() {
Alerts.update("success", 'Your account is created. Welcome!', true)
transitionTo(Routes.bookshelf, {id: Users.currentUserId()})
})
}
render():React.Element {
var content = ""
if (!this.props.loaded) {
content = ""
}
else if (!this.props.invite) {
content = <InvalidCode message="We couldn't find your beta code!"/>
}
else if (this.props.invite.signup) {
content = <InvalidCode message="This beta code has already been used"/>
}
else {
content = <SignupForm invite={this.props.invite} onSignup={this.onSignup.bind(this)}/>
}
//var signup = this.state.signup
return <LogoPage alert={this.props.alert}>
{content}
</LogoPage>
}
}
export class SignupForm extends React.Component {
constructor(props:any) {
super(props)
this.state = {signup: null}
}
componentWillMount(props:any) {
this.setState({signup: emptySignup(this.props.invite)})
}
onSubmit() {
this.props.onSignup(this.state.signup)
}
render():React.Element {
var signup = this.state.signup
var update = makeUpdate(signup, (v) => {
this.setState({signup: v})
})
return <div>
<p style={{marginTop: 30}}>Welcome to Web Fiction! Enter your information to sign up for an account</p>
<label>Email</label>
<p>{signup.email}</p>
<div className="row">
<div className="small-12 medium-6 columns">
<label>First Name</label>
<input type="text"
value={signup.firstName}
onChange={update((s, v) => s.firstName = v)}
/>
</div>
<div className="small-12 medium-6 columns">
<label>Last Name</label>
<input type="text"
value={signup.lastName}
onChange={update((s, v) => s.lastName = v)}
/>
</div>
</div>
<label>Password</label>
<input type="password"
value={signup.password}
onChange={update((s, v) => s.password = v)}
/>
<label>Password Confirmation</label>
<input type="password"
value={signup.passwordConfirmation}
onChange={update((s, v) => s.passwordConfirmation = v)}
/>
<div className="row">
<div className="columns small-12 medium-6">
<button className="expand" onClick={this.onSubmit.bind(this)}>Create My Account</button>
</div>
</div>
<div style={{marginBottom: 50}}/>
</div>
}
}
export class InvalidCode extends React.Component {
render():React.Element {
return <p style={{margin: 50}}><span>{this.props.message}</span>. Please contact support at <EmailLink /></p>
}
}
|
src/js/components/ScrollToTop.js | slavapavlutin/pavlutin-node | import React from 'react';
import { withRouter } from 'react-router-dom';
class ScrollToTop extends React.Component {
componentDidUpdate(prevProps) {
// const { hash } = this.props.location;
// if (hash.length > 0) {
// document.getElementById(hash).scrollIntoView();
// return;
// }
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0);
}
}
render() {
return this.props.children;
}
}
export default withRouter(ScrollToTop);
|
src/client/pages/tocheckitem.react.js | sljuka/portfulio | import Component from '../components/component.react';
import React from 'react';
import {FormattedHTMLMessage} from 'react-intl';
class ToCheckItem extends Component {
static propTypes = {
item: React.PropTypes.object.isRequired
};
render() {
return (
<li>
<FormattedHTMLMessage message={this.props.item.get('txt')} />
</li>
);
}
}
export default ToCheckItem;
|
docs/src/app/components/pages/components/Dialog/ExampleAlert.js | ichiohta/material-ui | import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
/**
* Alerts are urgent interruptions, requiring acknowledgement, that inform the user about a situation.
*/
export default class DialogExampleAlert extends React.Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Discard"
primary={true}
onTouchTap={this.handleClose}
/>,
];
return (
<div>
<RaisedButton label="Alert" onTouchTap={this.handleOpen} />
<Dialog
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
Discard draft?
</Dialog>
</div>
);
}
}
|
stories/Breadcrumb.stories.js | algolia/react-instantsearch | import React from 'react';
import { storiesOf } from '@storybook/react';
import { object, text } from '@storybook/addon-knobs';
import {
Breadcrumb,
HierarchicalMenu,
Panel,
connectHierarchicalMenu,
} from 'react-instantsearch-dom';
import { WrapWithHits } from './util';
const stories = storiesOf('Breadcrumb', module);
const VirtualHierarchicalMenu = connectHierarchicalMenu(() => null);
stories
.add('default', () => (
<div>
<WrapWithHits
hasPlayground={true}
linkedStoryGroup="Breadcrumb.stories.js"
>
<Breadcrumb
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
/>
<hr />
<HierarchicalMenu
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
defaultRefinement="Cameras & Camcorders > Digital Cameras"
showMoreLimit={3}
showMore={true}
/>
</WrapWithHits>
</div>
))
.add('with custom component', () => (
<WrapWithHits hasPlayground={true} linkedStoryGroup="Breadcrumb.stories.js">
<Breadcrumb
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
separator={<span> ⚡ </span>}
/>
<hr />
<VirtualHierarchicalMenu
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
defaultRefinement="Cameras & Camcorders > Digital Cameras"
/>
</WrapWithHits>
))
.add('playground', () => (
<WrapWithHits hasPlayground={true} linkedStoryGroup="Breadcrumb.stories.js">
<Breadcrumb
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
separator={text('separator', ' / ')}
translations={object('translations', {
rootLabel: 'Home',
})}
/>
<VirtualHierarchicalMenu
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
defaultRefinement="Cameras & Camcorders > Digital Cameras"
/>
</WrapWithHits>
))
.add('with Panel', () => (
<WrapWithHits hasPlayground={true} linkedStoryGroup="Breadcrumb.stories.js">
<Panel header="Breadcrumb" footer="footer">
<Breadcrumb
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
/>
</Panel>
<hr />
<HierarchicalMenu
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
defaultRefinement="Cameras & Camcorders > Digital Cameras"
/>
</WrapWithHits>
))
.add('with Panel but no refinement', () => (
<WrapWithHits hasPlayground={true} linkedStoryGroup="Breadcrumb.stories.js">
<Panel header="Breadcrumb" footer="footer">
<Breadcrumb
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
/>
</Panel>
</WrapWithHits>
));
|
node_modules/react-router/modules/TransitionHook.js | yomolify/cs-webserver | import React from 'react';
import warning from 'warning';
var { object } = React.PropTypes;
var TransitionHook = {
contextTypes: {
router: object.isRequired
},
componentDidMount() {
warning(
typeof this.routerWillLeave === 'function',
'Components that mixin TransitionHook should have a routerWillLeave method, check %s',
this.constructor.displayName || this.constructor.name
);
if (this.routerWillLeave)
this.context.router.addTransitionHook(this.routerWillLeave);
},
componentWillUnmount() {
if (this.routerWillLeave)
this.context.router.removeTransitionHook(this.routerWillLeave);
}
};
export default TransitionHook;
|
stories/GridWithCardLayout/ExampleGridStandard.js | skyiea/wix-style-react | import React from 'react';
import {Container, Row, Col, Card} from '../../src/Grid';
import styles from './ExampleGrid.scss';
import TextField from '../../src/TextField';
import Input from '../../src/Input';
import Label from '../../src/Label';
function renderStandardInput() {
return (
<TextField>
<Label
for="textField"
>
Text Field
</Label>
<Input
id="textField"
placeholder="Default text goes"
/>
</TextField>
);
}
export default () =>
<div data-hook="card-example" className={styles.exampleContainer}>
<Container>
<Row>
<Col span={8}>
<Card>
<Card.Header withoutDivider subtitle="subtitle" title="Header without Divider"/>
<Card.Content>
<Row>
<Col span={4}>
{renderStandardInput()}
</Col>
<Col span={4}>
{renderStandardInput()}
</Col>
<Col span={4}>
{renderStandardInput()}
</Col>
</Row>
<Row>
<Col span={6}>
{renderStandardInput()}
</Col>
</Row>
<Row>
<Col span={6}>
{renderStandardInput()}
</Col>
<Col span={3}>
{renderStandardInput()}
</Col>
<Col span={3}>
{renderStandardInput()}
</Col>
</Row>
</Card.Content>
</Card>
</Col>
<Col span={4}>
<Card>
<Card.Header title="Side Card"/>
<Card.Content>
<Row>
<Col span={12}>
{renderStandardInput()}
</Col>
</Row>
<Row>
<Col span={6}>
{renderStandardInput()}
</Col>
<Col span={6}>
{renderStandardInput()}
</Col>
</Row>
<Row>
<Col span={12}>
{renderStandardInput()}
</Col>
</Row>
</Card.Content>
</Card>
</Col>
</Row>
<Row>
<Col span={12}>
<Card>
<Card.Header title="Main card" subtitle="Subtitle"/>
<Card.Content>
<Row>
<Col span={4}>
{renderStandardInput()}
</Col>
<Col span={4}>
{renderStandardInput()}
</Col>
<Col span={4}>
{renderStandardInput()}
</Col>
</Row>
</Card.Content>
</Card>
</Col>
</Row>
</Container>
</div>;
|
src/svg-icons/social/location-city.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialLocationCity = (props) => (
<SvgIcon {...props}>
<path d="M15 11V5l-3-3-3 3v2H3v14h18V11h-6zm-8 8H5v-2h2v2zm0-4H5v-2h2v2zm0-4H5V9h2v2zm6 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V9h2v2zm0-4h-2V5h2v2zm6 12h-2v-2h2v2zm0-4h-2v-2h2v2z"/>
</SvgIcon>
);
SocialLocationCity = pure(SocialLocationCity);
SocialLocationCity.displayName = 'SocialLocationCity';
SocialLocationCity.muiName = 'SvgIcon';
export default SocialLocationCity;
|
src/stories/index.js | marceux/react-mcw | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { withKnobs, boolean } from '@storybook/addon-knobs';
import PermanentDrawer from '../Drawer/PermanentDrawer';
import TemporaryDrawer from '../Drawer/TemporaryDrawer';
storiesOf('PermanentDrawer', module)
.add('default view', () => (
<PermanentDrawer>
<p>Inside Drawer</p>
</PermanentDrawer>
))
.add('with spacer', () => (
<PermanentDrawer spacer={<p>Inside Spacer</p>} >
<p>Outside Spacer</p>
</PermanentDrawer>
));
storiesOf('TemporaryDrawer', module)
.addDecorator(withKnobs)
.add('default view', () => (
<TemporaryDrawer isOpen={boolean('Open', true)} >
<p>Content</p>
</TemporaryDrawer>
))
.add('with spacer', () => (
<TemporaryDrawer isOpen={boolean('Open', true)} spacer={<p>Inside Spacer</p>} >
<p>Content</p>
</TemporaryDrawer>
))
.add('with header', () => (
<TemporaryDrawer isOpen={boolean('Open', true)} header={<p>Inside Header</p>} >
<p>Content</p>
</TemporaryDrawer>
))
.add('calls action when closed', () => (
<TemporaryDrawer isOpen={boolean('Open', true)} closeDrawer={action('Closed')} >
<p>Content</p>
</TemporaryDrawer>
))
.add('calls action when opened', () => (
<TemporaryDrawer isOpen={boolean('Open', true)} openDrawer={action('Opened')} >
<p>Content</p>
</TemporaryDrawer>
));
|
examples/body-overflow.js | yiminghe/dom-align | import React from 'react';
import domAlign from 'dom-align';
import ReactDOM from 'react-dom';
import createReactClass from 'create-react-class';
const Test = createReactClass({
align() {
const ret = domAlign(this.refs.source, this.refs.target, {
points: ['tl', 'bl'],
overflow: {
adjustY: 1,
adjustX: 1,
},
});
console.log(ret);
setTimeout(() => {
document.body.style.overflow = 'hidden';
}, 1000);
},
render() {
window.align = this.align;
return (
<div style={{ height: 1000 }}>
<button
ref="target"
style={{ position: 'absolute', right: 0, top: 300 }}
>
target
</button>
<div style={{ height: 100 }} />
<button onClick={this.align}>align</button>
<div
ref="source"
style={{
position: 'absolute',
width: 100,
height: 200,
border: '1px solid red',
}}
>
oo
</div>
</div>
);
},
});
ReactDOM.render(<Test />, document.getElementById('__react-content'));
|
demo/src/components/ContainerExample/index.js | jbetancur/react-flexybox | import React from 'react';
import { Container, Row, Col } from 'react-flexybox';
import Markdown from '../Markdown';
import code from './code.md';
import codeFluid from './codeFluid.md';
const ContainerExample = props => (
<div>
<Container>
<h2>Container</h2>
<p>
Container is an optional Wrapper that centers all flex items within <code>Row</code> to a fixed width.
</p>
<Row gutter={3}>
<Col flex={6} className="demo-item" />
<Col flex={6} className="demo-item" />
<Col flex={6} className="demo-item" />
<Col flex={6} className="demo-item" />
</Row>
<Row>
<Col flex={12}>
<Markdown markdown={code} />
</Col>
</Row>
</Container>
<p>
Using the <code>fluid</code> prop makes the contents of <code>Row</code> 100% width of the browser window
</p>
<Container fluid>
<Row gutter={3}>
<Col flex={6} className="demo-item" />
<Col flex={6} className="demo-item" />
<Col flex={6} className="demo-item" />
<Col flex={6} className="demo-item" />
</Row>
</Container>
<Container>
<Row>
<Col flex={12}>
<Markdown markdown={codeFluid} />
</Col>
</Row>
</Container>
</div>
);
export default ContainerExample;
|
app/testutils.js | websash/q-and-a-react-redux-app | import React from 'react'
import {render} from 'react-dom'
import {Router, Route, browserHistory} from 'react-router'
import {renderToString} from 'react-dom/server'
function wrap(Component, props) {
return class ComponentWrapper extends React.Component {
render() {
return <Component {...props} />
}
}
}
export function intoDoc(Component, props) {
const node = document.createElement('div')
render(
<Router history={browserHistory}>
<Route path="blank" component={wrap(Component, props)} />
</Router>,
node
)
return node
}
export function intoHTML(Component, props) {
return renderToString(<Component {...props} />)
}
|
web/src/js/components/Widget/Widgets/Bookmarks/AddBookmarkForm.js | gladly-team/tab | /* eslint no-useless-escape: 0 */
import React from 'react'
import PropTypes from 'prop-types'
import EditWidgetChip from 'js/components/Widget/EditWidgetChip'
import TextField from 'material-ui/TextField'
import appTheme, { widgetEditButtonHover } from 'js/theme/default'
class AddBookmarkForm extends React.Component {
constructor(props) {
super(props)
this.state = {
open: false,
nameRequiredError: false,
urlRequiredError: false,
}
}
_handleKeyPress(e) {
if (e.key === 'Enter') {
if (!e.shiftKey) {
e.stopPropagation()
e.preventDefault()
this.create()
}
}
}
openForm() {
this.setState(
{
open: true,
},
() => {
this.focusInput()
}
)
}
closeForm() {
this.setState({
open: false,
})
}
focusInput() {
this.bookmarkNameTextField.focus()
}
onNameValChange() {
const name = this.bookmarkNameTextField.input.value
this.setState({
nameRequiredError: !name,
})
}
onURLValChange() {
const url = this.bLink.input.value
this.setState({
urlRequiredError: !url,
})
}
addProtocolToURLIfNeeded(url) {
const hasProtocol = s => {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s)
}
if (!hasProtocol(url)) {
return 'http://' + url
}
return url
}
create() {
const name = this.bookmarkNameTextField.input.value
const url = this.bLink.input.value
if (!name) {
this.setState({
nameRequiredError: true,
})
}
if (!url) {
this.setState({
urlRequiredError: true,
})
}
if (!name || !url) {
return
}
const link = this.addProtocolToURLIfNeeded(this.bLink.input.value)
this.props.addBookmark(name, link)
this.bookmarkNameTextField.input.value = ''
this.bLink.input.value = ''
this.closeForm()
}
render() {
const textField = {
underlineStyle: {
borderColor: appTheme.textField.underlineColor,
},
underlineFocusStyle: {
borderColor: widgetEditButtonHover,
},
hintStyle: {
color: appTheme.textField.underlineColor,
fontSize: 14,
},
inputStyle: {
color: '#FFF',
fontSize: 14,
},
}
return (
<EditWidgetChip
open={this.state.open}
widgetName={'Bookmarks'}
onAddItemClick={this.openForm.bind(this)}
onCancelAddItemClick={this.closeForm.bind(this)}
onItemCreatedClick={this.create.bind(this)}
showEditOption={this.props.showEditButton}
onEditModeToggle={this.props.onEditModeToggle}
editMode={this.props.editMode}
widgetAddItemForm={
<span
key={'widget-add-form-elem'}
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
paddingBottom: 20,
}}
>
<TextField
ref={input => {
this.bookmarkNameTextField = input
}}
onKeyPress={this._handleKeyPress.bind(this)}
hintText="Ex: Google"
style={textField.style}
inputStyle={textField.inputStyle}
hintStyle={textField.hintStyle}
underlineStyle={textField.underlineStyle}
underlineFocusStyle={textField.underlineFocusStyle}
onChange={this.onNameValChange.bind(this)}
errorText={this.state.nameRequiredError ? 'Enter a name' : null}
/>
<TextField
ref={input => {
this.bLink = input
}}
onKeyPress={this._handleKeyPress.bind(this)}
hintText="Ex: google.com"
style={textField.style}
inputStyle={textField.inputStyle}
hintStyle={textField.hintStyle}
underlineStyle={textField.underlineStyle}
underlineFocusStyle={textField.underlineFocusStyle}
onChange={this.onURLValChange.bind(this)}
errorText={this.state.urlRequiredError ? 'Enter a URL' : null}
/>
</span>
}
/>
)
}
}
AddBookmarkForm.propTypes = {
addBookmark: PropTypes.func.isRequired,
onEditModeToggle: PropTypes.func.isRequired,
editMode: PropTypes.bool.isRequired,
showEditButton: PropTypes.bool.isRequired,
}
AddBookmarkForm.defaultProps = {
showEditButton: true,
}
export default AddBookmarkForm
|
docs/containers/GettingStarted.js | 5rabbits/portrait | /* eslint-disable global-require, import/no-webpack-loader-syntax, react/no-danger */
import React from 'react'
import { Container } from 'shared'
import markdown from '../helpers/markdown'
const GettingStarted = () =>
<Container>
<div
dangerouslySetInnerHTML={{
__html: markdown.render(require('raw-loader!../pages/getting-started.md')),
}}
/>
</Container>
export default GettingStarted
|
app/javascript/mastodon/features/ui/components/column_subheading.js | tootsuite/mastodon | import React from 'react';
import PropTypes from 'prop-types';
const ColumnSubheading = ({ text }) => {
return (
<div className='column-subheading'>
{text}
</div>
);
};
ColumnSubheading.propTypes = {
text: PropTypes.string.isRequired,
};
export default ColumnSubheading;
|
src/svg-icons/device/brightness-medium.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBrightnessMedium = (props) => (
<SvgIcon {...props}>
<path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18V6c3.31 0 6 2.69 6 6s-2.69 6-6 6z"/>
</SvgIcon>
);
DeviceBrightnessMedium = pure(DeviceBrightnessMedium);
DeviceBrightnessMedium.displayName = 'DeviceBrightnessMedium';
DeviceBrightnessMedium.muiName = 'SvgIcon';
export default DeviceBrightnessMedium;
|
example/client/src/graphiql.js | samsarahq/thunder | import React from 'react';
import GraphiQL from 'graphiql';
import { connection, mutate } from 'thunder-react';
import '../node_modules/graphiql/graphiql.css';
function graphQLFetcher({query, variables}) {
if (query.startsWith("mutation")) {
return mutate({
query,
variables,
});
}
return {
subscribe(subscriber) {
const next = subscriber.next || subscriber;
const subscription = connection.subscribe({
query: query,
variables: {},
observer: ({state, valid, error, value}) => {
if (valid) {
next({data: value});
} else {
next({state, error});
}
}
});
return {
unsubscribe() {
return subscription.close();
}
};
}
};
}
export function GraphiQLWithFetcher() {
return <GraphiQL fetcher={graphQLFetcher} />;
}
|
src/dataTable/Head.js | iporaitech/react-to-mdl | import React from 'react';
const Head = (props) => {
const { children } = props;
return (
<thead>
<tr>
{children}
</tr>
</thead>
)
}
export { Head }
|
src/FadeMixin.js | Azerothian/react-bootstrap | import React from 'react';
import domUtils from './utils/domUtils';
// TODO: listen for onTransitionEnd to remove el
function getElementsAndSelf (root, classes){
let els = root.querySelectorAll('.' + classes.join('.'));
els = [].map.call(els, function(e){ return e; });
for(let i = 0; i < classes.length; i++){
if( !root.className.match(new RegExp('\\b' + classes[i] + '\\b'))){
return els;
}
}
els.unshift(root);
return els;
}
export default {
_fadeIn() {
let els;
if (this.isMounted()) {
els = getElementsAndSelf(React.findDOMNode(this), ['fade']);
if (els.length) {
els.forEach(function (el) {
el.className += ' in';
});
}
}
},
_fadeOut() {
let els = getElementsAndSelf(this._fadeOutEl, ['fade', 'in']);
if (els.length) {
els.forEach(function (el) {
el.className = el.className.replace(/\bin\b/, '');
});
}
setTimeout(this._handleFadeOutEnd, 300);
},
_handleFadeOutEnd() {
if (this._fadeOutEl && this._fadeOutEl.parentNode) {
this._fadeOutEl.parentNode.removeChild(this._fadeOutEl);
}
},
componentDidMount() {
if (document.querySelectorAll) {
// Firefox needs delay for transition to be triggered
setTimeout(this._fadeIn, 20);
}
},
componentWillUnmount() {
let els = getElementsAndSelf(React.findDOMNode(this), ['fade']),
container = (this.props.container && React.findDOMNode(this.props.container)) ||
domUtils.ownerDocument(this).body;
if (els.length) {
this._fadeOutEl = document.createElement('div');
container.appendChild(this._fadeOutEl);
this._fadeOutEl.appendChild(React.findDOMNode(this).cloneNode(true));
// Firefox needs delay for transition to be triggered
setTimeout(this._fadeOut, 20);
}
}
};
|
modules/Repo.js | proto2017/react-router | import React from 'react'
export default React.createClass({
render() {
const {username, repoName} = this.props.params;
return (
<div>
<h2>{username}/{repoName}/{Math.random()}</h2>
</div>
)
}
})
|
docs/app/Examples/collections/Message/Types/MessageExampleIcon.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Message, Icon } from 'semantic-ui-react'
const MessageExampleIcon = () => (
<Message icon>
<Icon name='circle notched' loading />
<Message.Content>
<Message.Header>Just one second</Message.Header>
We are fetching that content for you.
</Message.Content>
</Message>
)
export default MessageExampleIcon
|
components/GrainWeightOzField.js | sgillespie/beer-recipe-adapter | import { Input } from 'react-bootstrap';
import React from 'react';
export default React.createClass({
getValue: function () {
return this.refs.weightOz.getValue();
},
render: function () {
return (
<Input type="text"
ref="weightOz"
placeholder="Ounces"
addonAfter="oz"/>
);
},
});
|
src/components/layout/navigation/index.js | MoosemanStudios/app.moosecraft.us | import React from 'react';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import SiteLogo from 'src/components/component/siteLogo';
import { STATIC } from 'config/project';
import styles from './style.scss';
@connect(state => ({ menu: state.menu }))
class NavigationBar extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
user: null,
};
}
render() {
let menuItems;
if (this.props.menu !== undefined && Array.isArray(this.props.menu)) {
menuItems = this.props.menu.map(item => {
let inner;
if (item.children) {
const subItems = item.children.map(subItem => (
<li key={subItem.text}><NavLink to={subItem.link}>{subItem.text}</NavLink></li>
));
inner = <li key={item.text}><span className={styles.label}>{item.text}</span><ul className={styles.subNavigation}>{subItems}</ul></li>;
} else {
inner = <li key={item.text}><NavLink to={item.link}><span className={styles.label}>{item.text}</span></NavLink></li>;
}
return (
inner
);
});
}
return (
<nav id="nav">
<div className={styles.logoWrapper}>
<SiteLogo linkTo="/"><img className={styles.logo} alt="logo" src={`${STATIC.img}/logo.png`} /></SiteLogo>
</div>
<ul className={styles.topLevel}>
{menuItems}
<li><span className={styles.label}>(C)</span></li>{/* Chat popup */}
<li><span className={styles.label}>(P)</span></li>
</ul>
</nav>
);
}
}
export default NavigationBar;
|
app/routes.js | mersocarlin/react-webpack-template | import React from 'react';
import { Route } from 'react-router';
import App from './containers/app';
import About from './containers/about';
import Home from './containers/home';
import NoMatch from './containers/no-match';
export default (
<Route component={App}>
<Route path="/" component={Home} />
<Route path="about" component={About} />
<Route path="about/:param1/test/:param2" component={About} />
<Route path="*" component={NoMatch}/>
</Route>
);
|
src/components/chrome/ChromeFields.js | Scratch-it/react-color | 'use strict' /* @flow */
import React from 'react'
import ReactCSS from 'reactcss'
import color from '../../helpers/color'
import shallowCompare from 'react-addons-shallow-compare'
import { EditableInput } from '../common'
export class ChromeFields extends ReactCSS.Component {
shouldComponentUpdate = shallowCompare.bind(this, this, arguments[0], arguments[1])
state = {
view: '',
}
classes(): any {
return {
'default': {
wrap: {
paddingTop: '16px',
display: 'flex',
},
fields: {
flex: '1',
display: 'flex',
marginLeft: '-6px',
},
field: {
paddingLeft: '6px',
width: '100%',
},
toggle: {
width: '32px',
textAlign: 'right',
position: 'relative',
},
icon: {
marginRight: '-4px',
marginTop: '12px',
cursor: 'pointer',
position: 'relative'
},
iconHighlight: {
position: 'absolute',
width: '24px',
height: '28px',
background: '#eee',
borderRadius: '4px',
top: '10px',
left: '12px',
display: 'none',
},
Input: {
style: {
input: {
fontSize: '11px',
color: '#333',
width: '100%',
borderRadius: '2px',
border: 'none',
boxShadow: 'inset 0 0 0 1px #dadada',
height: '21px',
textAlign: 'center',
},
label: {
textTransform: 'uppercase',
fontSize: '11px',
lineHeight: '11px',
color: '#969696',
textAlign: 'center',
display: 'block',
marginTop: '12px',
},
},
},
},
}
}
handleChange = (data: any) => {
this.props.onChange(data)
}
componentDidMount() {
if (this.props.hsl.a === 1 && this.state.view !== 'hex') {
this.setState({ view: 'hex' })
} else if (this.state.view !== 'rgb' && this.state.view !== 'hsl') {
this.setState({ view: 'rgb' })
}
}
toggleViews = () => {
if (this.state.view === 'hex') {
this.setState({ view: 'rgb' })
} else if (this.state.view === 'rgb') {
this.setState({ view: 'hsl' })
} else if (this.state.view === 'hsl') {
if (this.props.hsl.a === 1) {
this.setState({ view: 'hex' })
} else {
this.setState({ view: 'rgb' })
}
}
}
componentWillReceiveProps(nextProps: any) {
if (nextProps.hsl.a !== 1 && this.state.view === 'hex') {
this.setState({ view: 'rgb' })
}
}
handleChange = (data: any) => {
if (data.hex) {
color.isValidHex(data.hex) && this.props.onChange({
hex: data.hex,
source: 'hex',
})
} else if (data.r || data.g || data.b) {
this.props.onChange({
r: data.r || this.props.rgb.r,
g: data.g || this.props.rgb.g,
b: data.b || this.props.rgb.b,
source: 'rgb',
})
} else if (data.a) {
if (data.a < 0) {
data.a = 0
} else if (data.a > 1) {
data.a = 1
}
this.props.onChange({
h: this.props.hsl.h,
s: this.props.hsl.s,
l: this.props.hsl.l,
a: Math.round(data.a * 100) / 100,
source: 'rgb',
})
} else if (data.h || data.s || data.l) {
this.props.onChange({
h: data.h || this.props.hsl.h,
s: data.s && (data.s).replace('%', '') || this.props.hsl.s,
l: data.l && (data.l).replace('%', '') || this.props.hsl.l,
source: 'hsl',
})
}
}
showHighlight = () => {
this.refs.iconHighlight.style.display = 'block'
}
hideHighlight = () => {
this.refs.iconHighlight.style.display = 'none'
}
render(): any {
var fields
if (this.state.view === 'hex') {
fields = <div is="fields" className="flexbox-fix">
<div is="field">
<EditableInput is="Input" label="hex" value={ '#' + this.props.hex } onChange={ this.handleChange }/>
</div>
</div>
} else if (this.state.view === 'rgb') {
fields = <div is="fields" className="flexbox-fix">
<div is="field">
<EditableInput is="Input" label="r" value={ this.props.rgb.r } onChange={ this.handleChange } />
</div>
<div is="field">
<EditableInput is="Input" label="g" value={ this.props.rgb.g } onChange={ this.handleChange } />
</div>
<div is="field">
<EditableInput is="Input" label="b" value={ this.props.rgb.b } onChange={ this.handleChange } />
</div>
<div is="field">
<EditableInput is="Input" label="a" value={ this.props.rgb.a } arrowOffset={ .01 } onChange={ this.handleChange } />
</div>
</div>
} else if (this.state.view === 'hsl') {
fields = <div is="fields" className="flexbox-fix">
<div is="field">
<EditableInput is="Input" label="h" value={ Math.round(this.props.hsl.h) } onChange={ this.handleChange } />
</div>
<div is="field">
<EditableInput is="Input" label="s" value={ Math.round(this.props.hsl.s * 100) + '%' } onChange={ this.handleChange } />
</div>
<div is="field">
<EditableInput is="Input" label="l" value={ Math.round(this.props.hsl.l * 100) + '%' } onChange={ this.handleChange } />
</div>
<div is="field">
<EditableInput is="Input" label="a" value={ this.props.hsl.a } arrowOffset={ .01 } onChange={ this.handleChange } />
</div>
</div>
}
return (
<div is="wrap" className="flexbox-fix">
{ fields }
<div is="toggle">
<div is="icon" onClick={ this.toggleViews } ref="icon">
<svg style={{ width:'24px', height:'24px', }} viewBox="0 0 24 24" onMouseOver={ this.showHighlight } onMouseEnter={ this.showHighlight } onMouseOut={ this.hideHighlight }>
<path fill="#333" d="M12,18.17L8.83,15L7.42,16.41L12,21L16.59,16.41L15.17,15M12,5.83L15.17,9L16.58,7.59L12,3L7.41,7.59L8.83,9L12,5.83Z" />
</svg>
</div>
<div is="iconHighlight" ref="iconHighlight" />
</div>
</div>
)
}
}
export default ChromeFields
|
js/jqwidgets/demos/react/app/chart/columnsrange/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxChart from '../../../jqwidgets-react/react_jqxchart.js';
class App extends React.Component {
render() {
let sampleData = [{ a: 0.35, b: 14.5, c: 0.35, d: 0.1 }, { a: 1, b: 2.5, c: 1, d: 0.2 }, { a: 10, b: 0.5, c: 10, d: 50 }, { a: 100, b: 205, c: 100, d: 40 }, { a: 1, b: 100, c: 1, d: 200 }, { a: 5.11, b: 10.13, c: 5.11, d: 0.2 }, { a: 20.13, b: 10.13, c: 20.13, d: 4 }];
let padding = { left: 5, top: 5, right: 5, bottom: 5 };
let titlePadding = { left: 0, top: 0, right: 0, bottom: 10 };
let xAxis =
{
gridLines: { dashStyle: '2,2' },
tickMarks: { dashStyle: '1,2' }
};
let valueAxis =
{
logarithmicScale: true,
logarithmicScaleBase: 2,
unitInterval: 1,
title: { text: 'Value' },
labels: {
formatSettings: { decimalPlaces: 3 },
horizontalAlignment: 'right'
},
gridLines: { dashStyle: '2,2' },
tickMarks: { dashStyle: '1,2' }
};
let seriesGroups =
[
{
type: 'rangecolumn',
series: [
{ dataFieldFrom: 'a', dataFieldTo: 'b', displayText: 'from A to B' },
{ dataFieldFrom: 'c', dataFieldTo: 'd', displayText: 'from C to D' }
]
}
];
return (
<JqxChart style={{ width: 850, height: 500 }}
title={'Logarithmic Column Range'} description={'logarithmic scale with base 2'}
enableAnimations={true} padding={padding} xAxis={xAxis}
titlePadding={titlePadding} source={sampleData}
valueAxis={valueAxis} colorScheme={'scheme07'} seriesGroups={seriesGroups}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
examples/js/remote/remote-search.js | powerhome/react-bootstrap-table | import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
export default class RemoteSearch extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<BootstrapTable data={ this.props.data }
remote={ true }
search={ true }
multiColumnSearch={ true }
options={ { onSearchChange: this.props.onSearchChange, clearSearch: true } }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
classic/src/scenes/wbfa/generated/FABApple.pro.js | wavebox/waveboxapp | import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faApple } from '@fortawesome/free-brands-svg-icons/faApple'
export default class FABApple extends React.Component {
render () {
return (<FontAwesomeIcon {...this.props} icon={faApple} />)
}
}
|
app/Entry.js | anthonychung14/mobile-1 | import React from 'react';
import { Router, Scene } from 'react-native-router-flux';
import IngestContainer from './containers/IngestContainer.js';
import SessionContainer from './containers/SessionContainer.js';
import SignUpView from './components/signup/SignUpView.js';
import NavBar from './components/NavBar.js';
export default class Entry extends React.Component {
render() {
return (
<Router>
<Scene key="root">
<Scene
key="pageOne"
component={ SessionContainer }
initial={ "true" }
title="Home"
NavBar={ NavBar }
/>
<Scene
key="pageTwo"
component={ IngestContainer }
title="Ingest"
NavBar={ NavBar }
/>
<Scene
key="pageThree"
component={ SessionContainer }
title="Digest"
NavBar={ NavBar }
/>
<Scene
key="pageFour"
component={ SessionContainer }
title="Digest"
NavBar={ NavBar }
/>
</Scene>
</Router>
);
}
}
|
geonode/contrib/monitoring/frontend/src/components/cels/frequent-layers/index.js | simod/geonode | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import styles from './styles';
import actions from './actions';
const mapStateToProps = (state) => ({
interval: state.interval.interval,
layers: state.frequentLayers.response,
timestamp: state.interval.timestamp,
});
@connect(mapStateToProps, actions)
class Alert extends React.Component {
static propTypes = {
get: PropTypes.func.isRequired,
interval: PropTypes.number,
layers: PropTypes.object,
timestamp: PropTypes.instanceOf(Date),
};
static defaultProps = {
layers: {
data: {
data: [{
data: [],
}],
},
},
}
constructor(props) {
super(props);
this.get = (interval = this.props.interval) => {
this.props.get(interval);
};
}
componentWillMount() {
this.get();
}
componentWillReceiveProps(nextProps) {
if (nextProps) {
if (nextProps.timestamp && nextProps.timestamp !== this.props.timestamp) {
this.get(nextProps.interval);
}
}
}
render() {
const layersData = this.props.layers.data.data[0].data;
const layers = layersData.map((layer, index) => (
<tr key={layer.resource.name}>
<th scope="row">{index + 1}</th>
<td>{layer.resource.name}</td>
<td>{Number(layer.val)}</td>
</tr>
));
return (
<div style={styles.root}>
<h5 style={styles.title}>Most Frequently Accessed Layers</h5>
<table style={styles.table}>
<tbody>
<tr>
<th scope="row"></th>
<td>Layer Name</td>
<td>Requests</td>
</tr>
{layers}
</tbody>
</table>
</div>
);
}
}
export default Alert;
|
src/svg-icons/image/wb-incandescent.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageWbIncandescent = (props) => (
<SvgIcon {...props}>
<path d="M3.55 18.54l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8zM11 22.45h2V19.5h-2v2.95zM4 10.5H1v2h3v-2zm11-4.19V1.5H9v4.81C7.21 7.35 6 9.28 6 11.5c0 3.31 2.69 6 6 6s6-2.69 6-6c0-2.22-1.21-4.15-3-5.19zm5 4.19v2h3v-2h-3zm-2.76 7.66l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4z"/>
</SvgIcon>
);
ImageWbIncandescent = pure(ImageWbIncandescent);
ImageWbIncandescent.displayName = 'ImageWbIncandescent';
ImageWbIncandescent.muiName = 'SvgIcon';
export default ImageWbIncandescent;
|
lib/views/timeline-items/commit-comment-view.js | atom/github | import React from 'react';
import {graphql, createFragmentContainer} from 'react-relay';
import PropTypes from 'prop-types';
import Octicon from '../../atom/octicon';
import Timeago from '../timeago';
import GithubDotcomMarkdown from '../github-dotcom-markdown';
import {GHOST_USER} from '../../helpers';
export class BareCommitCommentView extends React.Component {
static propTypes = {
item: PropTypes.object.isRequired,
isReply: PropTypes.bool.isRequired,
switchToIssueish: PropTypes.func.isRequired,
}
render() {
const comment = this.props.item;
const author = comment.author || GHOST_USER;
return (
<div className="issue">
<div className="info-row">
{this.props.isReply ? null : <Octicon className="pre-timeline-item-icon" icon="comment" />}
<img className="author-avatar"
src={author.avatarUrl} alt={author.login} title={author.login}
/>
{this.renderHeader(comment, author)}
</div>
<GithubDotcomMarkdown html={comment.bodyHTML} switchToIssueish={this.props.switchToIssueish} />
</div>
);
}
renderHeader(comment, author) {
if (this.props.isReply) {
return (
<span className="comment-message-header">
{author.login} replied <Timeago time={comment.createdAt} />
</span>
);
} else {
return (
<span className="comment-message-header">
{author.login} commented {this.renderPath()} in
{' '}{comment.commit.oid.substr(0, 7)} <Timeago time={comment.createdAt} />
</span>
);
}
}
renderPath() {
if (this.props.item.path) {
return <span>on <code>{this.props.item.path}</code></span>;
} else {
return null;
}
}
}
export default createFragmentContainer(BareCommitCommentView, {
item: graphql`
fragment commitCommentView_item on CommitComment {
author {
login avatarUrl
}
commit { oid }
bodyHTML createdAt path position
}
`,
});
|
internals/templates/app.js | dvm4078/dvm-blog | /**
* 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 { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./images/favicon.ico';
import '!file-loader?name=[name].[ext]!./images/icon-72x72.png';
import '!file-loader?name=[name].[ext]!./images/icon-96x96.png';
import '!file-loader?name=[name].[ext]!./images/icon-128x128.png';
import '!file-loader?name=[name].[ext]!./images/icon-144x144.png';
import '!file-loader?name=[name].[ext]!./images/icon-152x152.png';
import '!file-loader?name=[name].[ext]!./images/icon-192x192.png';
import '!file-loader?name=[name].[ext]!./images/icon-384x384.png';
import '!file-loader?name=[name].[ext]!./images/icon-512x512.png';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import configureStore from './configureStore';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Create redux store with history
const initialState = {};
const history = createHistory();
const store = configureStore(initialState, history);
const MOUNT_NODE = document.getElementById('app');
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</LanguageProvider>
</Provider>,
MOUNT_NODE
);
};
if (module.hot) {
// Hot reloadable React components and translation json files
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept(['./i18n', 'containers/App'], () => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// 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
}
|
examples/05 Customize/Drop Effects/Container.js | wagonhq/react-dnd | import React, { Component } from 'react';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd/modules/backends/HTML5';
import SourceBox from './SourceBox';
import TargetBox from './TargetBox';
@DragDropContext(HTML5Backend)
export default class Container extends Component {
render() {
return (
<div style={{ overflow: 'hidden', clear: 'both', marginTop: '1.5rem' }}>
<div style={{ float: 'left' }}>
<SourceBox showCopyIcon />
<SourceBox />
</div>
<div style={{ float: 'left' }}>
<TargetBox />
</div>
</div>
);
}
} |
js/Chord.js | nico1000/chord-trainer | import React from 'react';
import drawChords from './drawChords';
export default class Chord extends React.Component {
constructor(props) {
super(props);
}
render() {
var chordImage = (
<div
className='chord__image'
ref={ this.drawChord }
data-chord-name=''
data-positions={ Chord.allChords()[this.props.chordName].positions }
data-fingers={ Chord.allChords()[this.props.chordName].fingers }
data-size="4"
/>
);
return (
<div className={ 'chord ' + this.props.className} data-chord-name={ this.props.chordName } >
<div>{ Chord.nicePrint(this.props.chordName) }</div>
{ chordImage }
</div>
);
}
drawChord(element) {
if (element) {
drawChords.replace(element);
}
}
static allChords() {
// thanks to
// https://www.justinguitar.com/en/CH-000-Chords.php
return {
// beginner open chords
'D': { positions: 'xx0232', fingers: '---132' },
'A': { positions: 'x02220', fingers: '--213-' },
'E': { positions: '022100', fingers: '-231--' },
'G': { positions: '320003', fingers: '21---3' },
'C': { positions: 'x32010', fingers: '-32-1-' },
'Am': { positions: 'x02210', fingers: '--321-' },
'Em': { positions: '022000', fingers: '-23---' },
'Dm': { positions: 'xx0231', fingers: '---231' },
// dominant 7th open chords
'G_7': { positions: '320001', fingers: '32---1' },
'C_7': { positions: 'x32310', fingers: '-3241-' },
'B_7': { positions: 'x21202', fingers: '-213-4' },
'A_7': { positions: 'x02020', fingers: '--1-2-' },
'D_7': { positions: 'xx0212', fingers: '---213' },
'E_7': { positions: '020100', fingers: '-2-1--' },
'F': { positions: '133211', fingers: '134211' },
'Fmaj_7': { positions: 'xx3210', fingers: '--321-' },
// suspended open chords
'Asus2': { positions: 'x02200', fingers: '--12--' },
'Asus4': { positions: 'x02230', fingers: '--124-' },
'Dsus2': { positions: 'xx0230', fingers: '---13-' },
'Dsus4': { positions: 'xx0233', fingers: '---134' },
'Esus2': { positions: '024400', fingers: '-134--' },
'Esus4': { positions: '022200', fingers: '-234--' },
// slash chords
'D/F#': { positions: '2x0232', fingers: '---132' },
'G/B': { positions: 'x20003', fingers: '-2---4' },
'C/G': { positions: '332010', fingers: '342010' },
'Fmaj_7_/C': { positions: 'x33210', fingers: '-3421-' },
}
}
static allChordNames() {
let allChords = this.allChords();
return Object.keys(allChords);
}
static chordsColumn(props) {
let chords = props.chords.map((chord, index) => {
return (
<Chord
key={ index + '_' + chord }
chordName={ chord }
className={ props.selectedChord == chord ? 'chord--selected' : '' } />
);
});
return (
<div className='chords-column' onClick={ props.chordSelectedFn } data-display-position={ props.displayPosition }>
{ chords }
</div>
);
}
static nicePrint(chordName) {
var splitted = chordName.split('_');
if (splitted.length == 1) {
return <span>{ chordName }</span>;
} else if (splitted.length == 2) {
return <span>{ splitted[0] }<sup>{ splitted[1] }</sup></span>
} else {
return <span>{ splitted[0] }<sup>{ splitted[1] }</sup>{ splitted[2] }</span>
}
}
}
|
packages/mineral-ui-icons/src/IconClass.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconClass(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 4h5v8l-2.5-1.5L6 12V4z"/>
</g>
</Icon>
);
}
IconClass.displayName = 'IconClass';
IconClass.category = 'action';
|
src/components/Loading.js | JoJoChilly/joexp-react | import React from 'react';
import { Dimmer, Loader, Segment } from 'semantic-ui-react';
const loading = () => (
<div>
<Segment>
<Dimmer active inverted>
<Loader inverted>Loading</Loader>
</Dimmer>
</Segment>
</div>
);
export default loading;
|
packages/material-ui-icons/src/SignalCellular0BarRounded.js | lgollut/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path fillOpacity=".3" d="M4.41 22H20c1.1 0 2-.9 2-2V4.41c0-.89-1.08-1.34-1.71-.71L3.71 20.29c-.63.63-.19 1.71.7 1.71z" />
, 'SignalCellular0BarRounded');
|
Tutorial/js/project/2.MeiTuan/Component/Home/XMGShopCenterDetail.js | onezens/react-native-repo | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Platform,
TouchableOpacity,
Image,
WebView
} from 'react-native';
var Shop = React.createClass({
getInitialState(){
return{
detailUrl: this.props.url + '?uuid=5C7B6342814C7B496D836A69C872202B5DE8DB689A2D777DFC717E10FC0B4271&utm_term=6.6&utm_source=AppStore&utm_content=5C7B6342814C7B496D836A69C872202B5DE8DB689A2D777DFC717E10FC0B4271&version_name=6.6&userid=160495643&utm_medium=iphone&lat=23.134709&utm_campaign=AgroupBgroupD100Ghomepage_shoppingmall_detailH0&token=b81UqRVf6pTL4UPLLBU7onkvyQoAAAAAAQIAACQVmmlv_Qf_xR-hBJVMtIlq7nYgStcvRiK_CHFmZ5Gf70DR47KP2VSP1Fu5Fc1ndA&lng=113.373890&f=iphone&ci=20&msid=0FA91DDF-BF5B-4DA2-B05D-FA2032F30C6C2016-04-04-08-38594'
}
},
render() {
// alert(this.props.url);
return (
<View style={styles.container}>
{/*导航*/}
{this.renderNavBar()}
<WebView
automaticallyAdjustContentInsets={true}
source={{uri: this.state.detailUrl}}
javaScriptEnabled={true}
domStorageEnabled={true}
decelerationRate="normal"
startInLoadingState={true}
/>
</View>
);
},
// 导航条
renderNavBar(){
return(
<View style={styles.navOutViewStyle}>
<TouchableOpacity onPress={()=>{this.props.navigator.pop()}} style={styles.leftViewStyle}>
<Image source={{uri: 'icon_camera_back_normal'}} style={styles.navImageStyle}/>
</TouchableOpacity>
<Text style={{color:'white', fontSize:16, fontWeight:'bold'}}>购物中心详情</Text>
<TouchableOpacity onPress={()=>{alert('点了!')}} style={styles.rightViewStyle}>
<Image source={{uri: 'icon_mine_setting'}} style={styles.navImageStyle}/>
</TouchableOpacity>
</View>
)
}
});
const styles = StyleSheet.create({
container: {
flex:1
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
navImageStyle:{
width:Platform.OS == 'ios' ? 28: 24,
height:Platform.OS == 'ios' ? 28: 24,
},
leftViewStyle:{
// 绝对定位
position:'absolute',
left:10,
bottom:Platform.OS == 'ios' ? 15:13
},
rightViewStyle:{
// 绝对定位
position:'absolute',
right:10,
bottom:Platform.OS == 'ios' ? 15:13
},
navOutViewStyle:{
height: Platform.OS == 'ios' ? 64 : 44,
backgroundColor:'rgba(255,96,0,1.0)',
// 设置主轴的方向
flexDirection:'row',
// 垂直居中 ---> 设置侧轴的对齐方式
alignItems:'center',
// 主轴方向居中
justifyContent:'center'
},
});
// 输出组件类
module.exports = Shop;
|
app/javascript/mastodon/features/account_gallery/components/media_item.js | kagucho/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Permalink from '../../../components/permalink';
export default class MediaItem extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
};
render () {
const { media } = this.props;
const status = media.get('status');
let content, style;
if (media.get('type') === 'gifv') {
content = <span className='media-gallery__gifv__label'>GIF</span>;
}
if (!status.get('sensitive')) {
style = { backgroundImage: `url(${media.get('preview_url')})` };
}
return (
<div className='account-gallery__item'>
<Permalink
to={`/statuses/${status.get('id')}`}
href={status.get('url')}
style={style}
>
{content}
</Permalink>
</div>
);
}
}
|
src/components/users/UserFollowing.js | mg4tv/mg4tv-web | import PropTypes from 'prop-types'
import React from 'react'
import {compose, getContext} from 'recompose'
const enhanceSubs = compose(
getContext({
baseUrl: PropTypes.string.isRequired
}),
)
const UserFollowing = ({baseUrl}) => (
<div>
</div>
)
export default enhanceSubs(UserFollowing)
|
src/components/App.js | anitailieva/fullstack-javascript | import React from 'react';
import Header from './Header';
import ContestList from './ContestList';
import Contest from './Contest';
import * as api from '../api';
const pushState = (obj, url) =>
window.history.pushState(obj, '', url);
const onPopState = handler => {
window.onpopstate = handler;
};
class App extends React.Component {
static propTypes = {
initialData: React.PropTypes.object.isRequired
};
state = this.props.initialData;
componentDidMount() {
onPopState((event) => {
this.setState({
currentContestId: (event.state || {}).currentContestId
});
});
}
componentWillUnmount() {
onPopState(null);
}
fetchContest = (contestId) => {
pushState(
{ currentContestId: contestId },
`/contest/${contestId}`
);
api.fetchContest(contestId).then(contest => {
this.setState({
currentContestId: contest._id,
contests: {
...this.state.contests,
[contest._id]: contest
}
});
});
};
fetchContestList = () => {
pushState(
{ currentContestId: null },
'/'
);
api.fetchContestList().then(contests => {
this.setState({
currentContestId: null,
contests
});
});
};
fetchNames = (nameIds) => {
if (nameIds.length === 0) {
return;
}
api.fetchNames(nameIds).then(names => {
this.setState({
names
});
});
};
currentContest() {
return this.state.contests[this.state.currentContestId];
}
pageHeader() {
if (this.state.currentContestId) {
return this.currentContest().contestName;
}
return 'Naming Contests';
}
lookupName = (nameId) => {
if (!this.state.names || !this.state.names[nameId]) {
return {
name: '...'
};
}
return this.state.names[nameId];
};
addName = (newName, contestId) => {
api.addName(newName, contestId).then(resp =>
this.setState({
contests: {
...this.state.contests,
[resp.updatedContest._id]: resp.updatedContest
},
names: {
...this.state.names,
[resp.newName._id]: resp.newName
}
})
)
.catch(console.error);
};
currentContent() {
if (this.state.currentContestId) {
return <Contest
contestListClick={this.fetchContestList}
fetchNames={this.fetchNames}
lookupName={this.lookupName}
addName={this.addName}
{...this.currentContest()} />;
}
return <ContestList
onContestClick={this.fetchContest}
contests={this.state.contests} />;
}
render() {
return (
<div className="App">
<Header message={this.pageHeader()} />
{this.currentContent()}
</div>
);
}
}
export default App;
|
src/components/docs/flex-video.js | nordsoftware/react-foundation-docs | import React from 'react';
import Playground from 'component-playground';
import {
Grid,
Cell,
FlexVideo,
} from 'react-foundation';
export const FlexVideoDocs = () => (
<section className="flex-video-docs">
<Grid>
<Cell large={12}>
<h2>Flex Video</h2>
<Playground codeText={require('raw-loader!../examples/flex-video/basics').default}
scope={{ React, FlexVideo }}
theme="eiffel"/>
</Cell>
</Grid>
</section>
);
export default FlexVideoDocs;
|
packages/web/examples/ssr/pages/reactivelist.js | appbaseio/reactivesearch | /* eslint-disable */
import React, { Component } from 'react';
import { ReactiveBase, SingleList, SelectedFilters, ReactiveList } from '@appbaseio/reactivesearch';
import initReactivesearch from '@appbaseio/reactivesearch/lib/server';
import Layout from '../components/Layout';
import BookCard from '../components/BookCard';
const settings = {
app: 'good-books-ds',
url: 'https://a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61@appbase-demo-ansible-abxiydt-arc.searchbase.io',
enableAppbase: true,
};
const singleListProps = {
componentId: 'BookSensor',
dataField: 'original_series.keyword',
defaultValue: 'In Death',
size: 100,
};
const reactiveListProps = {
componentId: 'SearchResult',
dataField: 'original_title',
className: 'result-list-container',
from: 0,
size: 5,
renderItem: data => <BookCard key={data._id} data={data} />,
defaultQuery: () => ({
query: {
exists: {
field: 'original_title',
},
},
}),
react: {
and: ['BookSensor'],
},
};
export default class Main extends Component {
static async getInitialProps() {
return {
store: await initReactivesearch(
[
{
...singleListProps,
source: SingleList,
},
{
...reactiveListProps,
source: ReactiveList,
},
],
null,
settings,
),
};
}
render() {
return (
<Layout title="SSR | SingleList">
<ReactiveBase {...settings} initialState={this.props.store}>
<div className="row">
<div className="col">
<SingleList {...singleListProps} />
</div>
<div className="col">
<SelectedFilters />
<ReactiveList {...reactiveListProps} />
</div>
</div>
</ReactiveBase>
</Layout>
);
}
}
|
app/desktop/Loaders/index.js | christianalfoni/webpack-bin | import React from 'react';
import {Decorator as Cerebral} from 'cerebral-view-react';
import styles from './styles.css';
import BabelConfig from './BabelConfig';
import CssConfig from './CssConfig';
import TypescriptConfig from './TypescriptConfig';
import CoffeescriptConfig from './CoffeescriptConfig';
import RawConfig from './RawConfig';
import JsonConfig from './JsonConfig';
import JadeConfig from './JadeConfig';
import HandlebarsConfig from './HandlebarsConfig';
import VueConfig from './VueConfig';
const loaders = {
babel: BabelConfig,
css: CssConfig,
typescript: TypescriptConfig,
coffeescript: CoffeescriptConfig,
raw: RawConfig,
json: JsonConfig,
jade: JadeConfig,
handlebars: HandlebarsConfig,
vue: VueConfig
};
@Cerebral({
currentLoaders: 'bin.currentBin.loaders',
currentLoader: 'bin.currentLoader'
})
class Loaders extends React.Component {
onLoaderToggle(e, name) {
e.stopPropagation();
this.props.signals.bin.loaderToggled({name});
}
onLoaderClick(name) {
this.props.signals.bin.loaderClicked({name});
}
render() {
const CurrentConfig = loaders[this.props.currentLoader];
const {currentLoader, currentLoaders} = this.props;
return (
<div className={styles.wrapper}>
<div className={styles.loadersList}>
{Object.keys(loaders).map((loaderName, index) => {
return (
<div
key={index}
className={currentLoader === loaderName ? styles.activeLoader : styles.loader}
onClick={() => this.onLoaderClick(loaderName)}>
<input
type="checkbox"
onChange={(e) => this.onLoaderToggle(e, loaderName)}
checked={loaderName in currentLoaders}/>
{loaderName}
</div>
);
})}
</div>
<div className={styles.loaderConfig}>
<CurrentConfig/>
</div>
</div>
);
}
}
export default Loaders;
|
docs/app/Views/Usage.js | mohammed88/Semantic-UI-React | import React from 'react'
import pkg from 'package.json'
import {
Container,
Header,
Segment,
} from 'src'
import Logo from '../Components/Logo/Logo'
import { semanticUIDocsURL, semanticUIRepoURL, semanticUICSSRepoURL } from 'docs/app/utils'
const suiCSSVersion = pkg.devDependencies['semantic-ui-css'].replace(/[~^]/, '')
const Usage = () => (
<Container id='usage-page'>
<Segment basic textAlign='center'>
<Logo centered size='small' />
<Header as='h1' textAlign='center'>
Semantic-UI-React
<Header.Subheader>
{pkg.description}
</Header.Subheader>
</Header>
</Segment>
<Segment basic padded>
<Header as='h2' dividing>JavaScript</Header>
<p>
The Semantic UI React package can be installed via NPM:
</p>
<Segment>
<pre>$ npm install {pkg.name} --save</pre>
</Segment>
<p>
Installing Semantic UI React provides the JavaScript for your components.
You'll also need to include a stylesheet to provide the styling for your components.
This is the typical pattern for component frameworks, such as Semantic UI or Bootstrap.
</p>
<p>
The method you choose to include the stylesheet in your project will depend on the level
of customisation you require.
</p>
</Segment>
<Segment basic padded>
<Header as='h2' dividing>CSS</Header>
{/* ----------------------------------------
* Content Delivery Network (CDN)
* -------------------------------------- */}
<Header as='h3'>Content Delivery Network (CDN)</Header>
<p>
You can use the default Semantic UI stylesheet by including a Semantic UI CDN link in your
<em>index.html</em> file.
</p>
<p>
This is the quickest way to get started with Semantic UI React. You won't be able to use
custom themes with this method.
</p>
<Segment>
<pre>
{'<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/'}
{suiCSSVersion}
{'/semantic.min.css"></link>'}
</pre>
</Segment>
{/* ----------------------------------------
* Semantic-UI-CSS package
* -------------------------------------- */}
<Header as='h3'>Semantic UI CSS package</Header>
<p>
The <a href={semanticUICSSRepoURL}>Semantic UI CSS package</a> is automatically synced with the
main Semantic UI repository to provide a lightweight CSS only version of Semantic UI.
</p>
<p>
Semantic UI CSS can be installed as a package in your project using NPM. You won't be able to
use custom themes with this method.
</p>
<Segment>
<pre>
$ npm install semantic-ui-css --save
</pre>
</Segment>
{/* ----------------------------------------
* Semantic-UI package
* -------------------------------------- */}
<Header as='h3'>Semantic UI package</Header>
<p>
Install the full <a href={semanticUIRepoURL}>Semantic UI package</a>.
</p>
<p>
Semantic UI includes Gulp build tools so your project can preserve its own theme changes,
allowing you to customise the style variables.
</p>
<p>
Detailed documentation on theming in Semantic UI is
provided <a href={`${semanticUIDocsURL}usage/theming.html`}>here</a>.
</p>
<Segment>
<pre>
$ npm install semantic-ui --save-dev
</pre>
</Segment>
<p>
After building the project with Gulp, you'll need to include the minified CSS file
in your <em>index.js</em> file:
</p>
<Segment>
<pre>
import '../semantic/dist/semantic.min.css';
</pre>
</Segment>
</Segment>
</Container>
)
export default Usage
|
examples/real-world/index.js | alantrrs/redux | import 'babel-core/polyfill';
import React from 'react';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import { Provider } from 'react-redux';
import { Router, Route } from 'react-router';
import configureStore from './store/configureStore';
import App from './containers/App';
import UserPage from './containers/UserPage';
import RepoPage from './containers/RepoPage';
const history = new BrowserHistory();
const store = configureStore();
React.render(
<Provider store={store}>
{() =>
<Router history={history}>
<Route path="/" component={App}>
<Route path="/:login/:name"
component={RepoPage} />
<Route path="/:login"
component={UserPage} />
</Route>
</Router>
}
</Provider>,
document.getElementById('root')
);
|
src/components/Dashboard.js | jojoee/whitt | import React from 'react';
const Dashboard = () => {
return (
<div>
<h2>Dashboard</h2>
</div>
);
};
export default Dashboard;
|
react-router-tutorial/index.js | Zyst/learning-react | import React from 'react'
import { render } from 'react-dom'
import App from './modules/App'
import { Router, Route, browserHistory, IndexRoute } from 'react-router'
import About from './modules/About';
import Repos from './modules/Repos';
import Repo from './modules/Repo';
import Home from './modules/Home';
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo} />
</Route>
<Route path="/about" component={About} />
</Route>
</Router>
),
document.getElementById('app'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.