path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/index.js
ryan-shaw/react-survey
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import Root from './containers/Root'; import injectTapEventPlugin from 'react-tap-event-plugin'; // import localforage from 'localforage'; injectTapEventPlugin(); // const store = configureStore(JSON.parse(localStorage.getItem('state') || '{}')); // store.subscribe(() => { // localStorage.setItem('state', JSON.stringify(store.getState())); // }); // const history = syncHistoryWithStore(browserHistory, store); render( <AppContainer> <Root history={browserHistory} /> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept('./containers/Root', () => { const NewRoot = require('./containers/Root').default; render( <AppContainer> <NewRoot history={history} /> </AppContainer>, document.getElementById('root') ); }); }
src/svg-icons/maps/flight.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsFlight = (props) => ( <SvgIcon {...props}> <path d="M10.18 9"/><path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/> </SvgIcon> ); MapsFlight = pure(MapsFlight); MapsFlight.displayName = 'MapsFlight'; export default MapsFlight;
frontend/statements/Container.js
datoszs/czech-lawyers
import React from 'react'; import {RichText, Anchor, Msg, DefaultPageTitle} from '../containers'; import {StatementHeading} from '../components/statement'; import {STATEMENTS_ADVOCATES, STATEMENTS_PROCEEDINGS, STATEMENTS_CASES} from '../routes'; const params = { ending: '.', }; export default () => ( <section> <DefaultPageTitle /> <Anchor anchor={STATEMENTS_CASES} /> <StatementHeading><RichText msg="statement.cases" {...params} /></StatementHeading> <RichText msg="statement.cases.long" /> <Anchor anchor={STATEMENTS_PROCEEDINGS} /> <StatementHeading><Msg msg="statement.proceedings" {...params} /></StatementHeading> <RichText msg="statement.proceedings.long" /> <Anchor anchor={STATEMENTS_ADVOCATES} /> <StatementHeading><Msg msg="statement.advocates" {...params} /></StatementHeading> <RichText msg="statement.advocates.long" /> </section> );
src/app/components/item/ItemsList.js
mazahell/eve-react-app
import React from 'react' import ReactTooltip from 'react-tooltip' const ItemsList = ({item, clickItem}) => { let randId = 'id-' + Math.ceil(Math.random() * 1000000000) return ( <div onClick={() => clickItem(item)} className='inline user_img' data-tip data-for={randId}> <img alt={item.item_name} src={'https://image.eveonline.com/Type/' + item.item_id + '_32.png'} /> <ReactTooltip class='reactToolTip' delayHide={0} id={randId} type='dark' effect='solid'> <div className='b'> <div>{item.item_name}</div> <div><small>{item.count}</small> items</div> </div> </ReactTooltip> </div> ) } export default ItemsList
packages/containers/src/Form/Form.container.js
Talend/ui
import React from 'react'; import PropTypes from 'prop-types'; import Immutable from 'immutable'; import { cmfConnect } from '@talend/react-cmf'; import BaseForm from '@talend/react-forms'; import classnames from 'classnames'; let DefaultArrayFieldTemplate = () => null; if (process.env.FORM_MOZ) { DefaultArrayFieldTemplate = BaseForm.deprecated.templates.ArrayFieldTemplate; } export const DEFAULT_STATE = new Immutable.Map({}); /** * Because we don't want to loose form input * This Component bind onChange to store the formData in it's state. * <Form jsonSchema={} uiSchema={} data={} /> */ class Form extends React.Component { static displayName = 'Container(Form)'; static propTypes = { ...cmfConnect.propTypes, formId: PropTypes.string.isRequired, data: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), }; static defaultProps = { data: {}, }; /** * return the form data in redux state * usefull in mapStateToProps of your component * @example const FORM_ID = 'add-datastore-form'; * * @param {[type]} state [description] * @param {[type]} formId [description] * @return {[type]} [description] */ static getFormData(state, formId) { return state.cmf.components.getIn(['Container(Form)', formId, 'data'], new Immutable.Map()); } static getDerivedStateFromProps(nextProps, prevState) { if (!prevState) { nextProps.initState(); return null; } if (!nextProps.state && nextProps.formId !== prevState.formId) { nextProps.deleteState(); return null; } if (nextProps.data !== prevState.data) { return { data: nextProps.data }; } return null; } constructor(props) { super(props); this.state = DEFAULT_STATE.toJS(); this.formActions = this.formActions.bind(this); this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); this.onErrors = this.onErrors.bind(this); this.jsonSchema = this.jsonSchema.bind(this); this.uiSchema = this.uiSchema.bind(this); this.data = this.data.bind(this); } componentDidUpdate(prevProps, prevState) { if (prevState.data !== this.state.data) { this.props.setState({ data: this.state.data }); } } onChange(event, form) { this.props.setState({ data: form.formData, dirty: true }); if (this.props.onChange) { this.props.onChange(form); } } onErrors(event, errors) { this.props.setState({ errors }); if (this.props.onErrors) { this.props.onErrors(event, errors); } } onSubmit(event, formData) { if (this.props.onSubmit) { this.props.onSubmit(formData); } if (this.props.onSubmitActionCreator) { this.props.dispatchActionCreator(this.props.onSubmitActionCreator, null, { props: this.props, formData, }); } } jsonSchema() { const state = (this.props.state || DEFAULT_STATE).toJS(); if (typeof this.props.jsonSchema === 'function') { return this.props.jsonSchema(state.data); } return this.props.jsonSchema; } uiSchema() { const state = (this.props.state || DEFAULT_STATE).toJS(); if (typeof this.props.uiSchema === 'function') { return this.props.uiSchema(state.data); } return this.props.uiSchema; } data() { const state = (this.props.state || DEFAULT_STATE).toJS(); if (typeof this.props.data === 'function') { return this.props.data(state.data); } return { ...this.props.data, ...state.data }; } errors() { const state = (this.props.state || DEFAULT_STATE).toJS(); if (typeof this.props.errors === 'function') { return this.props.errors(state.errors); } return { ...this.props.errors, ...state.errors }; } formActions() { if (typeof this.props.actions === 'function') { const state = (this.props.state || DEFAULT_STATE).toJS(); return this.props.actions(state.data || this.props.data); } return this.props.actions; } render() { const state = (this.props.state || DEFAULT_STATE).toJS(); const props = { data: { jsonSchema: this.jsonSchema(), uiSchema: this.uiSchema(), properties: this.data(), errors: this.errors(), }, className: classnames('tc-form', 'rjsf', this.props.className, { dirty: state.dirty, pristine: !state.dirty, }), ArrayFieldTemplate: this.props.ArrayFieldTemplate || DefaultArrayFieldTemplate, actions: this.formActions(), fields: this.props.fields, onChange: this.onChange, onTrigger: this.props.onTrigger, onSubmit: this.onSubmit, onErrors: this.onErrors, customFormats: this.props.customFormats, customValidation: this.props.customValidation, buttonBlockClass: this.props.buttonBlockClass, children: this.props.children, uiform: this.props.uiform, language: this.props.language, widgets: this.props.widgets, getComponent: this.props.getComponent, loading: this.props.loading, ...this.props.formProps, }; return <BaseForm {...props}>{this.props.children}</BaseForm>; } } export default Form;
admin/client/components/ItemsTable/ItemsTableDragDropZone.js
tony2cssc/keystone
import React from 'react'; import CurrentListStore from '../../stores/CurrentListStore'; import DropZoneTarget from './ItemsTableDragDropZoneTarget'; import classnames from 'classnames'; var ItemsTableDragDropZone = React.createClass({ displayName: 'ItemsTableDragDropZone', propTypes: { columns: React.PropTypes.array, connectDropTarget: React.PropTypes.func, items: React.PropTypes.object, list: React.PropTypes.object, }, renderPageDrops () { const { items } = this.props; const currentPage = CurrentListStore.getCurrentPage(); const pageSize = CurrentListStore.getPageSize(); const totalPages = Math.ceil(items.count / pageSize); const style = { display: totalPages > 1 ? null : 'none' }; const pages = []; for (let i = 0; i < totalPages; i++) { const page = i + 1; const pageItems = '' + (page * pageSize - (pageSize - 1)) + ' - ' + (page * pageSize); const current = (page === currentPage); const className = classnames('ItemList__dropzone--page', { 'is-active': current, }); /* eslint-disable no-loop-func */ pages.push(<DropZoneTarget key={'page_' + page} page={page} className={className} pageItems={pageItems} />); /* eslint-enable */ } let cols = this.props.columns.length; if (this.props.list.sortable) cols++; if (!this.props.list.nodelete) cols++; return ( <tr style={style}> <td colSpan={cols} > <div className="ItemList__dropzone" > {pages} <div className="clearfix" /> </div> </td> </tr> ); }, render () { return this.renderPageDrops(); }, }); module.exports = ItemsTableDragDropZone;
node_modules/reflexbox/docs/components/Readme.js
HasanSa/hackathon
import React from 'react' import cxs from 'cxs' import readme from '../../README.md' import { Box } from '../..' import { colors } from './style' const Readme = () => { const cx = cxs({ maxWidth: 640, h1: { margin: 0 }, h2: { marginTop: 32, marginBottom: 0 }, h3: { marginTop: 32, marginBottom: 0 }, h4: { marginTop: 32, marginBottom: 0 }, ul: { marginTop: 0 }, p: { marginTop: 0, ':first-of-type': { fontSize: 20, fontWeight: 600 }, ':last-of-type': { display: 'none' } }, a: { color: 'inherit', fontWeight: 600 }, 'code:not(pre code)': { fontFamily: 'Menlo, monospace', fontSize: 14, fontWeight: 600 }, pre: { fontFamily: 'Menlo, monospace', fontSize: 14, overflowX: 'scroll', padding: 16, backgroundColor: colors.gray, borderRadius: 1 }, img: { WebkitFilter: 'hue-rotate(100deg)', filter: 'hue-rotate(100deg)' } }) return ( <Box p={3}> <div className={cx} dangerouslySetInnerHTML={{ __html: readme }} /> </Box> ) } export default Readme
client/app/components/NewTopic.js
ParadeTo/dataguru-nodejs
import React from 'react'; import $ from 'jquery'; import {addTopic} from '../lib/client'; import {redirectURL} from '../lib/utils'; import TopicEditor from './TopicEditor.js'; export default class NewTopic extends React.Component { constructor(props) { super(props); this.state = {}; } render() { return ( <TopicEditor title={'发表新主题'} topic={null} onSave={(topic, done) => { addTopic({title: topic.title, tags: topic.tags, content: topic.content}) .then(ret => { done(); redirectURL(`/topic/${ret._id}`); }) .catch(err => { done(); }); }}/> ); } }
packages/material-ui-icons/src/CallMade.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5z" /></g> , 'CallMade');
Components/NewResourceMixin.js
tradle/tim
import React from 'react' import { // Text, View, TouchableOpacity, Image, DatePickerAndroid, Switch } from 'react-native' import SwitchSelector from 'react-native-switch-selector' import format from 'string-template' import t from 'tcomb-form-native' import _ from 'lodash' import dateformat from 'dateformat' import FloatLabel from 'react-native-floating-labels' import Icon from 'react-native-vector-icons/Ionicons' import moment from 'moment' import DatePicker from 'react-native-datepicker' import constants from '@tradle/constants' import { Text, getFontMapping } from './Text' import utils, { translate, isWeb, enumValue, getLensedModelForType } from '../utils/utils' import { getMarkdownStyles } from '../utils/uiUtils' import StyleSheet from '../StyleSheet' import RefPropertyEditor from './RefPropertyEditor' import Markdown from './Markdown' import Actions from '../Actions/Actions' const DEFAULT_CURRENCY = 'USD'; const { MONEY, SETTINGS, FORM, IDENTITY, MESSAGE } = constants.TYPES const { TYPE, ROOT_HASH } = constants const INTERSECTION = 'tradle.Intersection' const DURATION = 'tradle.Duration' const PHOTO = 'tradle.Photo' const YEAR = 3600 * 1000 * 24 * 365 const DAY = 3600 * 1000 * 24 const HOUR = 3600 * 1000 const MINUTE = 60 * 1000 var cnt = 0; var propTypesMap = { 'string': t.Str, 'boolean': t.Bool, 'date': t.Dat, 'number': t.Num }; const DEFAULT_LINK_COLOR = '#a94442' var NewResourceMixin = { onScroll(e) { this._contentOffset = { ...e.nativeEvent.contentOffset } }, getScrollOffset() { return { ...this._contentOffset } }, getFormFields(params) { let { editCols, originatingMessage, search, exploreData, errs, isRefresh, bookmark } = this.props let CURRENCY_SYMBOL = this.getCurrency() let { component, formErrors, model, data, validationErrors, editable } = params // Case when clicked in the FormRequest and modelsPack changed let meta = this.props.model let isInlineArray if (!meta) { meta = utils.getModel(this.props.metadata.items.ref) isInlineArray = true } let onSubmitEditing = exploreData && this.getSearchResult || this.onSavePressed let onEndEditing = this.onEndEditing || params.onEndEditing let dModel = data && getLensedModelForType(data[TYPE]) if (!utils.isEmpty(data) && !meta.items && data[TYPE] !== meta.id && !utils.isSubclassOf(dModel, meta.id)) { let interfaces = meta.interfaces; if (!interfaces || interfaces.indexOf(data[TYPE]) === -1) return; } meta = getLensedModelForType(meta.id) let props, bl if (!meta.items) props = meta.properties; else { bl = meta.items.backlink if (meta.items.ref) props = utils.getModel(meta.items.ref).properties else props = meta.items.properties } let eCols = this.getEditCols(props, meta) let showReadOnly = data._dataBundle !== null if (!showReadOnly) { eCols.forEach(p => { let prop = props[p] // prop is readOnly if explicitely has readOnly on it or // it is a _group property with 'list' of props annotation if (prop && !utils.isReadOnly(prop) && !p.endsWith('_group') && !prop.list) { if (!originatingMessage || !originatingMessage.prefill) showReadOnly = false } }) } let requestedProperties, excludeProperties if (this.state.requestedProperties) ({requestedProperties, excludeProperties} = this.state.requestedProperties) let softRequired if (requestedProperties && !utils.isEmpty(requestedProperties)) { showReadOnly = true if (!formErrors) { _.extend(params, {formErrors: {}}) formErrors = params.formErrors } ;({ eCols, softRequired } = this.addRequestedProps({eCols, params, props})) } else if (data) { for (let p in data) { let prop = props[p] if (!eCols.includes(p) && p.charAt(0) !== '_' && prop && !utils.isReadOnly(prop)) eCols.push(p) } } // Add props for which request for corrections came, if they are not yet added if (formErrors) { for (let p in formErrors) if (eCols.indexOf(p) === -1) eCols.push(p) } let required = utils.ungroup({model: meta, viewCols: meta.required, edit: true}) if (!softRequired) softRequired = meta.softRequired || [] if (validationErrors) { formErrors = validationErrors this.state.validationErrors = null } const isMessage = meta.id === MESSAGE let options = {fields: {}} let resource = this.state.resource let isNew = !data[ROOT_HASH] let me = utils.getMe() for (let i=0; i<eCols.length; i++) { let p = eCols[i] if (!isMessage && (p === TYPE || p.charAt(0) === '_' || p === bl || (props[p].items && props[p].items.backlink))) continue; if (meta.hidden && meta.hidden.indexOf(p) !== -1) continue if (!me.isEmployee && props[p].internalUse) continue let maybe = !required || !required.includes(p) if (maybe) { if (p.indexOf('_group') === -1 && softRequired.includes(p)) maybe = false } let type = props[p].type let formType = propTypesMap[type]; // Don't show readOnly property in edit mode if not set let isReadOnly = utils.isReadOnly(props[p]) if (isReadOnly && !search && !showReadOnly) // && (type === 'date' || !data || !data[p])) continue; this.setDefaultValue(props[p], data, true) if (!this.props.metadata && utils.isHidden(p, resource)) { // if (!resource[p]) // this.setDefaultValue(p, resource, true) continue } let label = translate(props[p], meta) //props[p].title; if (!label) label = utils.makeLabel(p); let errMessage if (errs && errs[p]) { maybe = false if (resource[p] === this.props.resource[p]) errMessage = errs[p] } if (!validationErrors && formErrors && formErrors[p]) { if (resource[p] && this.props.resource[p] && _.isEqual(resource[p], this.props.resource[p])) // if (resource[p] === this.props.resource[p]) errMessage = formErrors[p] else if (!resource[p] && !this.props.resource[p]) errMessage = formErrors[p] else delete formErrors[p] } if (!errMessage) errMessage = translate('thisFieldIsRequired') options.fields[p] = { error: errMessage, //'This field is required', bufferDelay: 20, // to eliminate missed keystrokes } if (props[p].units) { if (props[p].units.charAt(0) === '[') options.fields[p].placeholder = label + ' ' + props[p].units else options.fields[p].placeholder = label + ' (' + props[p].units + ')' } let propNotEditable = isReadOnly || (props[p].immutable && data[p] && !isNew) if (props[p].description) options.fields[p].help = props[p].description; if (propNotEditable) options.fields[p] = { editable: false } let pName = isInlineArray && `${params.meta.name}_${p}` let val = isInlineArray && resource[pName] || data[p] if (formType) { if (props[p].keyboard) options.fields[p].keyboardType = props[p].keyboard else if (props[p].range === 'email') options.fields[p].keyboardType = 'email-address' else if (props[p].range === 'url') { if (utils.isIOS()) options.fields[p].keyboardType = 'url' } if (!model[p]) model[p] = maybe ? t.maybe(formType) : formType if (type == 'date') { model[p] = t.Str if (val) val = new Date(val) options.fields[p].template = this.myDateTemplate.bind(this, { label, prop: props[p], required: !maybe, model: meta, errors: formErrors, component, editable: !propNotEditable || search, value: val }) if (val) data[p] = val options.fields[p].mode = 'date' options.fields[p].auto = 'labels' options.fields[p].label = label options.fields[p].onDateChange = this.onDateChange } else if (type === 'boolean') { if (val) { if (typeof val !== 'boolean') val = val.title === 'No' ? false : true } options.fields[p].template = this.myBooleanTemplate.bind(this, { label, prop: props[p], model: meta, value: val, required: !maybe, component, editable: !propNotEditable || search, errors: formErrors, }) options.fields[p].onSubmitEditing = onSubmitEditing.bind(this); if (onEndEditing) options.fields[p].onEndEditing = onEndEditing.bind(this, p); if (props[p].maxLength) options.fields[p].maxLength = props[p].maxLength; } else if (type === 'string') { if (props[p].maxLength > 300) options.fields[p].multiline = true; options.fields[p].autoCorrect = false; if (props[p].oneOf) { model[p] = t.enums(props[p].oneOf); options.fields[p].auto = 'labels'; } } else if (type === 'number') { if (!search) { if (!props[p].keyboard) options.fields[p].keyboardType = 'numeric' if (val && (typeof val != 'number')) data[p] = parseFloat(val) } } if (type === 'string' && p.length > 6 && p.indexOf('_group') === p.length - 6) { options.fields[p].template = this.myTextTemplate.bind(this, { label, prop: props[p], model: meta, }) } else if (type === 'string' && props[p].markdown) { options.fields[p].template = this.myMarkdownTextInputTemplate.bind(this, { label, prop: props[p], model: meta, value: val || null, required: !maybe, errors: formErrors, editable: editable && !propNotEditable || search, }) } else if (type === 'string' && props[p].signature) { options.fields[p].template = this.mySignatureTemplate.bind(this, { label, prop: props[p], model: meta, value: val, required: !maybe, errors: formErrors, component, doSet: eCols.length > 1, editable: editable && !propNotEditable || search, }) } else if (!options.fields[p].multiline && (type === 'string' || type === 'number')) { if (val) val += '' else val = null let keyboard = props[p].keyboard || options.fields[p].keyboardType || (!search && type === 'number' ? 'numeric' : 'default') options.fields[p].template = this.myTextInputTemplate.bind(this, { label, prop: props[p], model: meta, value: val, required: !maybe, errors: formErrors, component, editable: editable && !propNotEditable || search || false, keyboard, }) options.fields[p].onSubmitEditing = onSubmitEditing.bind(this); if (onEndEditing) options.fields[p].onEndEditing = onEndEditing.bind(this, p); if (props[p].maxLength) options.fields[p].maxLength = props[p].maxLength; } } else { let ref = props[p].ref; let iref = props[p].items && props[p].items.ref if (!ref) { if (type === 'number' || type === 'string') ref = MONEY else if (props[p].range === 'json') continue if (!iref) continue; if (!utils.isEnum(iref) && !utils.getModel(iref).inlined && !isReadOnly) continue ref = iref } if (ref === MONEY) { model[p] = maybe ? t.maybe(t.Num) : t.Num; let value = val let currency = this.props.currency || CURRENCY_SYMBOL if (value) { if (typeof value !== 'object') { value = { value, currency } } else if (!value.currency) value.currency = currency } else { value = { currency } } options.fields[p].template = this.myMoneyInputTemplate.bind(this, { label, prop: props[p], value, model: meta, onSubmitEditing: onSubmitEditing.bind(this), keyboard: 'numeric', component, required: !maybe, editable: !propNotEditable, errors: formErrors, }) options.fields[p].onSubmitEditing = onSubmitEditing.bind(this) if (onEndEditing) options.fields[p].onEndEditing = onEndEditing.bind(this, p); continue; } else if (ref === DURATION) { model[p] = maybe ? t.maybe(t.Num) : t.Num; let value = val let durationType if (value) { if (typeof value !== 'object') { value = { value, durationType } } else if (!value.durationType) value.durationType = durationType } else { value = { durationType } } options.fields[p].template = this.myDurationInputTemplate.bind(this, { label, prop: props[p], value, model: meta, onSubmitEditing: onSubmitEditing.bind(this), keyboard: 'numeric', component, required: !maybe, errors: formErrors, editable: !propNotEditable }) options.fields[p].onSubmitEditing = onSubmitEditing.bind(this) if (onEndEditing) options.fields[p].onEndEditing = onEndEditing.bind(this, p); continue; } else if (props[p].signature) { model[p] = maybe ? t.maybe(t.Str) : t.Str; options.fields[p].template = this.mySignatureTemplate.bind(this, { label, prop: props[p], model: meta, value: val || null, required: !maybe, errors: formErrors, component, doSet: eCols.length > 1, editable: !propNotEditable }) continue } else if (search) { if (ref === PHOTO || ref === IDENTITY) continue } model[p] = maybe ? t.maybe(t.Str) : t.Str; if (val) { let vType = utils.getType(val) if (vType) { let subModel = utils.getModel(vType) options.fields[p].value = utils.getId(val) if (!search && !bookmark) data[p] = utils.getDisplayName({ resource: val, model: subModel }) || val.title } } if (iref && !utils.isEnum(iref)) { options.fields[p].template = this.myInlinedResourcesTemplate.bind(this, { label, prop: props[p], value: val, model: meta, component, required: !maybe, errors: formErrors, editable: !propNotEditable }) } else { // options.fields[p].onFocus = chooser.bind(this, props[p], p) options.fields[p].template = this.myCustomTemplate.bind(this, { label, prop: p, required: !maybe, errors: formErrors, resource: bookmark && search && data, component, chooser: options.fields[p].onFocus, }) options.fields[p].nullOption = {value: '', label: 'Choose your ' + utils.makeLabel(p)}; } } } // HACK for video if (eCols.indexOf('video') !== -1) { let maybe = required && !required.hasOwnProperty('video'); model.video = maybe ? t.maybe(t.Str) : t.Str; options.fields.video.template = this.myCustomTemplate.bind(this, { label: translate(props.video, meta), prop: 'video', errors: formErrors, component, required: !maybe }) } return options; }, addRequestedProps({eCols, params={}, props}) { let {requestedProperties, excludeProperties, formErrors, model} = this.state.requestedProperties if (!formErrors) { _.extend(params, {formErrors: {}}) formErrors = params.formErrors } eCols = eCols.filter(p => requestedProperties[p]) let softRequired = [] let groupped = [] for (let p in requestedProperties) { // if (eCols.some((prop) => prop.name === p) { let idx = p.indexOf('_group') let eidx = eCols.indexOf(p) if (eidx !== -1) { if (groupped.indexOf(p) !== -1) continue eCols.splice(eidx, 1) } if (excludeProperties && excludeProperties.indexOf(p) !== -1) continue if (requestedProperties[p].hide) continue eCols.push(p) let isRequired = requestedProperties[p].required if (idx === -1 && utils.isReadOnly(props[p])); // showReadOnly = true else if (props[p].list) { props[p].list.forEach((pp) => { let rProp = requestedProperties[pp] let isHidden = rProp && rProp.hide let idx = eCols.indexOf(pp) if (idx !== -1) eCols.splice(idx, 1) if (isHidden) return if (excludeProperties && excludeProperties.indexOf(pp) !== -1) return eCols.push(pp) if (isRequired) { if (!rProp) softRequired.push(pp) } else if (rProp && rProp.required) softRequired.push(pp) groupped.push(pp) }) } else if (isRequired) softRequired.push(p) } return { eCols, softRequired } }, getEditCols(props, model) { const { editCols, exploreData, bookmark, search } = this.props const isMessage = model.id === MESSAGE if (editCols) return editCols.slice(); if (isMessage) return model.viewCols let isSearch = exploreData || (bookmark && search) let eCols = utils.getEditCols(model, exploreData).map(p => p.name) if (!eCols.length) { if (model.required) return model.required.slice() else return Object.keys(props) } else if (!isSearch) return eCols let vColsList = utils.getViewCols(model) vColsList.forEach(p => { if (props[p] && !utils.isReadOnly(props[p]) && eCols.indexOf(p) === -1) eCols.push(p) }) let exclude = ['time', 'context', 'lens'] let prefillProp = utils.getPrefillProperty(model) if (prefillProp) exclude.push(prefillProp.name) for (let p in props) { if (!eCols.includes(p) && !props[p].items && p.charAt(0) !== '_' && !exclude.includes(p)) eCols.push(p) } return eCols }, addError(p, params) { let { errs } = this.props let { formErrors } = params if (errs) errs[p] = '' if (!formErrors[p]) formErrors[p] = translate('thisFieldIsRequired') }, getNextKey() { return (this.props.model || this.props.metadata).id + '_' + cnt++ }, changeValue(prop, value) { const { originatingMessage: originatingResource } = this.props let { name: pname, ref: pref, type: ptype } = prop if (ptype === 'string' && !value.trim().length) // debugger if(ptype === 'string' && !value.trim().length) value = '' const { resource, missedRequiredOrErrorValue } = this.state let search = this.props.search let r = _.cloneDeep(resource) let { metadata, parentMeta } = this.props if (metadata && parentMeta) pname = `${metadata.name}_${pname}` if(ptype === 'number' && !search) { let val = Number(value) let idx = value.indexOf('.') if (idx !== -1) { // Some strange HACK debugger const len = value.length if (++idx === len) return while(value.charAt(idx) === '0') idx++ if (idx === len) return } value = val } if (!this.floatingProps) this.floatingProps = {} if (pref == MONEY) { if (!this.floatingProps[pname]) this.floatingProps[pname] = {} let val = Number(value) this.floatingProps[pname].value = val if (!r[pname]) r[pname] = {} r[pname].value = val if (!this.floatingProps[pname].currency) this.floatingProps[pname].currency = r[pname].currency || (resource[pname] && resource[pname].currency) } else if (pref == DURATION) { if (!this.floatingProps[pname]) this.floatingProps[pname] = {} let val = Number(value) this.floatingProps[pname].value = val if (!r[pname]) r[pname] = {} r[pname].value = val if (!this.floatingProps[pname].durationType) this.floatingProps[pname].durationType = r[pname].durationType || (resource[pname] && resource[pname].durationType) } else if (ptype === 'boolean') { if (value === 'null') { let m = utils.getModel(resource[TYPE]) if (!search || (m.required && m.required.includes(pname))) { delete r[pname] delete this.floatingProps[pname] } else { r[pname] = null this.floatingProps[pname] = value } } else { if (value === 'true') value = true else if (value === 'false') value = false r[pname] = value this.floatingProps[pname] = value } } else { r[pname] = value this.floatingProps[pname] = value } if (missedRequiredOrErrorValue) delete missedRequiredOrErrorValue[pname] if (!search && r[TYPE] !== SETTINGS) { // if 'string' no need to check if requested properties changed on entering every letter if (ptype !== 'string' || value.length <= 1) Actions.getRequestedProperties({resource: r, originatingResource}) } this.setState({ resource: r, inFocus: pname }) }, myTextTemplate(params) { let label = translate(params.prop, params.model) let bankStyle = this.props.bankStyle let linkColor = (bankStyle && bankStyle.linkColor) || DEFAULT_LINK_COLOR return ( <View style={{flexDirection: 'row', paddingVertical: 5, paddingLeft: 15}}> <View style={[styles.accent, {borderLeftColor: bankStyle.accentColor || 'orange'}]}/> <Text style={[styles.dividerText, {color: linkColor}]}>{label}</Text> </View> ); }, myMarkdownTextInputTemplate(params) { let { prop, value, editable } = params let { bankStyle } = this.props let hasValue = value && value.length if (hasValue) { value = format(value, this.state.resource).trim() hasValue = value && value.length } let { lcolor, bcolor } = this.getLabelAndBorderColor(prop.name) if (hasValue) lcolor = '#555555' let lStyle = { color: lcolor, fontSize: 20} let vStyle = { height: 45, marginTop: 10, paddingVertical: 10, flexDirection: 'row', justifyContent: 'space-between', margin: 10} let help = this.paintHelp(prop) let st = {paddingBottom: 10} if (!help) st.flex = 5 let markdown, title if (hasValue) { markdown = <View style={styles.markdown}> <Markdown markdownStyles={getMarkdownStyles(bankStyle, true)}> {value} </Markdown> </View> title = utils.translate(prop) } else title = utils.translate('Please click here to view/edit') let header if (editable) st.marginTop = -10 else header = <View style={vStyle}> <Text style={lStyle}>{title}</Text> <Icon name='md-create' size={25} color={bankStyle.linkColor} /> </View> return <View style={st}> <TouchableOpacity onPress={this.showMarkdownEditView.bind(this, prop)}> {header} </TouchableOpacity> {markdown} </View> }, showMarkdownEditView(prop) { this.props.navigator.push({ title: translate(prop), //m.title, // titleTextColor: '#7AAAC3', componentName: 'MarkdownPropertyEdit', backButtonTitle: 'Back', rightButtonTitle: 'Done', passProps: { prop: prop, resource: this.state.resource, bankStyle: this.props.bankStyle, callback: this.changeValue.bind(this) } }) }, mySignatureTemplate(params) { let {prop, required, model, value, doSet} = params let label = translate(prop, model) if (required) label += ' *' let { bankStyle } = this.props // if (hasValue) { // value = format(value, this.state.resource).trim() // hasValue = value && value.length // } let { lcolor, bcolor } = this.getLabelAndBorderColor(prop.name) if (value) lcolor = '#555555' let help = this.paintHelp(prop) let st = {paddingBottom: 10} if (!help) st.flex = 5 let title, sig if (value) { let vStyle = { height: 100, justifyContent: 'space-between', margin: 10, borderBottomColor: '#cccccc', borderBottomWidth: 1} // let lStyle = [styles.labelStyle, { paddingBottom: 10, color: lcolor, fontSize: 12}] let lStyle = { paddingBottom: 10, color: lcolor, fontSize: 12} title = utils.translate('Please click here to change signature') let {width, height} = value //utils.dimensions(params.component) let h = 70 let w if (width > height) w = (width * 70)/(height - 100) else w = (height * 70)/(width - 100) sig = <View style={vStyle}> <Text style={lStyle}>{label}</Text> <Image source={{uri: value.url}} style={{width: w, height: h}} /> </View> } else { let vStyle = { height: 55, paddingVertical: 10, flexDirection: 'row', justifyContent: 'space-between', margin: 15, borderBottomColor: '#cccccc', borderBottomWidth: 1} // let lStyle = [styles.labelStyle, { color: lcolor, fontSize: 20}] let lStyle = { color: lcolor, fontSize: 20} title = utils.translate('Please click here to sign') sig = <View style={vStyle}> <Text style={lStyle}>{title}</Text> <Icon name='md-create' size={25} color={bankStyle.linkColor} /> </View> } if (prop.immutable && value) { return <View style={st}>{sig}</View> } else { return <View style={st}> <TouchableOpacity onPress={this.showSignatureView.bind(this, { prop, doSet, onSet: this.changeValue.bind(this) })}> {sig} </TouchableOpacity> </View> } }, myTextInputTemplate(params) { let {prop, required, model, editable, keyboard, value} = params let label = translate(prop, model) if (prop.units) { label += (prop.units.charAt(0) === '[') ? ' ' + prop.units : ' (' + prop.units + ')' } if (!this.props.search && required) label += ' *' let lStyle = styles.labelStyle let maxChars = (utils.dimensions(params.component).width - 40)/utils.getFontSize(9) if (maxChars < label.length && (!this.state.resource[prop.name] || !this.state.resource[prop.name].length)) lStyle = [lStyle, {marginTop: 0}] let { lcolor, bcolor } = this.getLabelAndBorderColor(prop.name) if (this.state.isRegistration) lStyle = [lStyle, {color: lcolor}] let multiline = prop.maxLength > 100 let help = prop.ref !== MONEY && prop.ref !== DURATION && this.paintHelp(prop) let st = { paddingBottom: 10 } // Especially for money type props if (!help) st.flex = 5 let icon let { bankStyle } = this.props if (!help) st = {...st, flex: 5} if (!editable) icon = <Icon name='ios-lock-outline' size={25} color={bankStyle.textColor} style={styles.readOnly} /> let fontF = bankStyle && bankStyle.fontFamily && {fontFamily: getFontMapping(bankStyle.fontFamily)} || {} let autoCapitalize = this.state.isRegistration || (prop.range !== 'url' && prop.name !== 'form' && prop.name !== 'product' && prop.range !== 'email') ? 'sentences' : 'none' let addStyle = editable ? {} : {backgroundColor: bankStyle.backgroundColor || '#f7f7f7'} return ( <View style={st}> <FloatLabel labelStyle={[lStyle, fontF, {color: lcolor}]} autoCorrect={false} password={prop.range === 'password' ? true : false} multiline={multiline} editable={editable} autoCapitalize={autoCapitalize} onFocus={this.inputFocused.bind(this, prop)} inputStyle={this.state.isRegistration ? styles.regInput : styles.textInput} style={[styles.formInput, addStyle, {borderColor: bcolor, minHeight: 60}]} value={value} keyboardShouldPersistTaps='always' keyboardType={keyboard || 'default'} onChangeText={this.changeValue.bind(this, prop)} underlineColorAndroid='transparent' >{label} </FloatLabel> {icon} {this.paintError(params)} {help} </View> ); }, paintHelp(prop) { if (!prop.description) return <View style={styles.help1}/> return ( <View style={styles.help}> <Markdown markdownStyles={getMarkdownStyles(this.props.bankStyle, false)}> {translate(prop, this.props.model, true)} </Markdown> </View> ) }, paintError(params) { if (params.noError) return let {missedRequiredOrErrorValue, isRegistration} = this.state let {prop} = params let err = missedRequiredOrErrorValue ? missedRequiredOrErrorValue[prop.name] : null if (!err) { if (params.errors && params.errors[prop.name]) err = params.errors[params.prop.name] else return } if (isRegistration) { let estyle = [styles.err, typeof params.paddingLeft !== 'undefined' ? {paddingLeft: params.paddingLeft} : {paddingLeft: 10}] return <View style={estyle} key={this.getNextKey()}> <Text style={styles.font14, {color: '#eeeeee'}}>{err}</Text> </View> } let { bankStyle } = this.props let addStyle = { paddingVertical: 3, marginTop: prop.type === 'object' || prop.type === 'date' || prop.items ? 0 : 2, backgroundColor: bankStyle.errorBgColor || '#990000', paddingHorizontal: 10, } return <View style={styles.err} key={this.getNextKey()}> <View style={addStyle}> <Text style={styles.font14, {paddingLeft: 5, color: bankStyle.errorColor || '#eeeeee'}}>{err}</Text> </View> </View> }, myBooleanTemplate(params) { let {prop, model, value, required, component, editable} = params let { search, bankStyle } = this.props let labelStyle = styles.booleanLabel let textStyle = [styles.booleanText, {color: this.state.isRegistration ? '#ffffff' : '#757575'}] let { lcolor, bcolor } = this.getLabelAndBorderColor(prop.name) let resource = this.state.resource let style = (resource && (typeof resource[prop.name] !== 'undefined')) ? textStyle : labelStyle let isTroolean = prop.range === 'troolean' || search let label = translate(prop, model) if (!isTroolean && !isWeb() && label.length > 30) { label = label.slice(0, 27) let idx = label.lastIndexOf(' ') if (idx > 20) label = label.slice(0, idx) label += '...' } if (prop.units) { label += (prop.units.charAt(0) === '[') ? ' ' + prop.units : ' (' + prop.units + ')' } if (!search && required) label += ' *' let switchView let switchC, icon let fontF = bankStyle && bankStyle.textFont && {fontFamily: bankStyle.textFont} || {} if (!editable && !search) { icon = <Icon name='ios-lock-outline' size={25} color={bankStyle.textColor} style={styles.readOnly} /> switchC = <View style={{paddingVertical: 5}}> <Text style={[styles.dateText, fontF]}>{value ? 'Yes' : 'No'}</Text> {icon} </View> } else if (isTroolean) { const options = [ { value: 'true', customIcon: <Icon size={30} color='#000' name='ios-checkmark' />}, { value: 'null', customIcon: <Icon size={30} color='#000' name='ios-radio-button-off' /> }, { value: 'false', customIcon: <Icon size={30} color='#000' name='ios-close' /> }, ]; let initial let v = value + '' for (let i=0; i<options.length && !initial; i++) { if (options[i].value === v) initial = i } if (typeof initial === 'undefined') initial = 1 let switchWidth = Math.floor(utils.dimensions(component).width / 2) switchView = { paddingVertical: 15, width: switchWidth, alignSelf: 'flex-end'} switchC = <TouchableOpacity onPress={() => this.changeValue(prop, isTroolean && value || !value)}> <View> <Text style={[style, {color: lcolor}]}>{label}</Text> <View style={switchView}> <SwitchSelector initial={initial} hasPadding={true} fontSize={30} options={options} onPress={(v) => this.changeValue(prop, v)} backgroundColor='transparent' buttonColor='#ececec' /> </View> </View> </TouchableOpacity> } else { switchC = <View style={styles.booleanContentStyle}> <Text style={[style, {color: lcolor}]}>{label}</Text> <Switch onValueChange={(value) => { let r = _.cloneDeep(resource) r[prop.name] = value this.setState({resource: r}) Actions.getRequestedProperties({resource: r}) }} style={{marginTop: -3}} value={value}/> </View> } return ( <View style={styles.bottom10} key={this.getNextKey()} ref={prop.name}> <View style={[styles.booleanContainer, {borderColor: bcolor}]}> {switchC} </View> {this.paintError(params)} {this.paintHelp(prop)} </View> ) }, myDateTemplate(params) { let { prop, required, component, editable } = params let { search, bankStyle, bookmark } = this.props let resource = this.state.resource let propLabel let { lcolor, bcolor } = this.getLabelAndBorderColor(prop.name) if (resource && resource[prop.name]) propLabel = <Text style={[styles.dateLabel, {color: lcolor}]}>{params.label}</Text> else propLabel = <View style={styles.floatingLabel}/> let valueMoment = params.value && moment.utc(new Date(params.value)) // let value = valueMoment && valueMoment.format(format) let value = params.value && utils.getDateValue(new Date(params.value)) let dateProps = {} if (prop.maxDate || prop.minDate) { let maxDate = this.getDateRange(prop.maxDate) let minDate = this.getDateRange(prop.minDate) if (minDate && maxDate) dateProps = {maxDate: new Date(maxDate), minDate: new Date(minDate)} else dateProps = minDate ? {minDate: new Date(minDate)} : {maxDate: new Date(maxDate)} } if (!value) value = translate(params.prop, utils.getModel(resource[TYPE])) + (!search && required ? ' *' : '') let st = isWeb() ? [styles.formInput, {minHeight: 60, borderColor: bcolor}] : [styles.formInput, {minHeight: 60, borderColor: bcolor, marginHorizontal: 15}] // convert from UTC date to local, so DatePicker displays it correctly // e.g. 1999-04-13 UTC -> 1999-04-13 EDT let localizedDate if (valueMoment) { localizedDate = new Date(valueMoment.year(), valueMoment.month(), valueMoment.date()) } let linkColor = (bankStyle && bankStyle.linkColor) || DEFAULT_LINK_COLOR let format = 'LL' // if (prop.format) { // dateProps.format = prop.format // format = prop.format // if (localizedDate) // value = dateformat(localizedDate, format) // } let datePicker if (!editable && !search) { datePicker = <View style={{paddingVertical: 5, paddingHorizontal: 10}}> <Text style={styles.dateText}>{dateformat(localizedDate, 'mmmm dd, yyyy')}</Text> </View> } else { datePicker = <DatePicker style={[styles.datePicker, {width: utils.dimensions(component).width - 20}]} mode="date" placeholder={value} format={format} confirmBtnText="Confirm" cancelBtnText="Cancel" locale={utils.getMe().languageCode || 'en'} date={localizedDate} onDateChange={(date) => { this.changeTime(params.prop, moment.utc(date, format).toDate()) }} customStyles={{ dateInput: styles.dateInput, dateText: styles.dateText, placeholderText: [styles.font20, { color: params.value ? '#555555' : '#777777', paddingLeft: params.value ? 10 : 0 }], dateIconColor: {color: linkColor}, dateIcon: styles.dateIcon, btnTextConfirm: {color: linkColor}, datePicker: { justifyContent:'center' } }} {...dateProps} /> } let icon if (!editable) icon = <Icon name='ios-lock-outline' size={25} color={bankStyle.textColor} style={styles.readOnly} /> let help = this.paintHelp(prop) return ( <View key={this.getNextKey()} ref={prop.name} style={styles.bottom10}> <View style={[st, {paddingBottom: this.hasError(params.errors, prop.name) || isWeb() ? 0 : 10}]}> {propLabel} {datePicker} {icon} </View> {help} {this.paintError(params)} </View> ) }, getLabelAndBorderColor(prop) { let bankStyle = this.props.bankStyle let lcolor, bcolor if (this.state.isRegistration) lcolor = '#eeeeee' else if (this.state.inFocus === prop) lcolor = bankStyle && bankStyle.linkColor || '#757575' else { lcolor = '#888888' bcolor = '#dddddd' } return {lcolor, bcolor: bcolor || lcolor} }, getDateRange(dateStr) { if (!dateStr) return null let parts = dateStr.split(' ') if (parts.length === 1) { switch(dateStr) { case 'today': return new Date().getTime() case 'tomorrow': return (new Date().getTime() + DAY) } } let [number, measure] = parts let beforeAfter = parts.length === 3 ? parts[2] : 'before' let coef switch (measure) { case 'years': coef = YEAR break case 'days': coef = DAY break case 'hours': coef = HOUR break case 'minutes': coef = MINUTE break default: coef = 1000 } switch(beforeAfter) { case 'before': return new Date().getTime() - number * coef case 'after': return new Date().getTime() + number * coef } }, async showPicker(prop, stateKey, options) { try { // let newState = {}; let date const {action, year, month, day} = await DatePickerAndroid.open(options); if (action !== DatePickerAndroid.dismissedAction) { // newState[stateKey + 'Text'] = 'dismissed'; // } else { date = new Date(year, month, day); // newState[stateKey + 'Text'] = date.toLocaleDateString(); // newState[stateKey + 'Date'] = date; } // this.setState(newState); this.changeTime(prop, date) } catch ({code, message}) { console.warn(`Error in example '${stateKey}': `, message); } }, changeTime: function(prop, date) { let r = _.cloneDeep(this.state.resource) r[prop.name] = date.getTime() if (!this.floatingProps) this.floatingProps = {} this.floatingProps[prop.name] = date.getTime() this.setState({ resource: r, inFocus: prop.name }); if (this.state.missedRequiredOrErrorValue) delete this.state.missedRequiredOrErrorValue[prop.name] }, inputFocused(prop) { if (utils.isReadOnly(prop)) return let { metadata, parentMeta } = this.props let pname = prop.name if (metadata && parentMeta) pname = `${metadata.name}_${pname}` if (/*!this.state.isRegistration &&*/ this.refs && this.refs.scrollView && this.props.model && Object.keys(this.props.model.properties).length > 5) { utils.scrollComponentIntoView(this, this.refs.form.getComponent(pname)) this.setState({inFocus: pname}) } else if (this.state.inFocus !== pname) this.setState({inFocus: pname}) }, myCustomTemplate(params) { if (!this.floatingProps) this.floatingProps = {} let { model, metadata, isRefresh, bookmark, allowedMimeTypes } = this.props let { required, errors, component } = params let { missedRequiredOrErrorValue, resource, inFocus } = this.state let props if (model) props = model.properties else if (metadata.items.properties) props = metadata.items.properties else props = utils.getModel(metadata.items.ref).properties let pName = params.prop let prop = props[pName] let ref = prop.ref || prop.items.ref let isMedia = pName === 'video' || pName === 'photos' || ref === PHOTO || utils.isSubclassOf(ref, 'tradle.File') let onChange if (isMedia) onChange = this.setState.bind(this) else onChange = this.setChosenValue.bind(this) let error = missedRequiredOrErrorValue && missedRequiredOrErrorValue[pName] if (!error && params.errors && params.errors[pName]) error = params.errors[pName] return <RefPropertyEditor {...this.props} resource={params.resource || this.state.resource} onChange={onChange} prop={prop} bookmark={bookmark} photo={this.state[pName + '_photo']} component={component} labelAndBorder={this.getLabelAndBorderColor.bind(this, pName)} error={error} inFocus={inFocus} isRefresh={isRefresh} required={required} allowedMimeTypes={allowedMimeTypes} floatingProps={this.floatingProps} paintHelp={this.paintHelp.bind(this)} paintError={this.paintError.bind(this)} styles={styles}/> }, setDefaultValue(prop, data, isHidden) { let p = prop.name let resource = this.state.resource if (resource[p] || resource[ROOT_HASH]) return if (this.floatingProps && this.floatingProps.hasOwnProperty(p)) return let defaults = this.props.defaultPropertyValues let value if (defaults) { let vals = defaults[resource[TYPE]] if (vals && vals[p]) value = vals[p] } if (prop.default) { if (!prop.ref) value = prop.default else value = enumValue({model: utils.getModel(prop.ref), value: prop.default}) } if (!value) return if (prop.type === 'date') { if (typeof value === 'string') value = this.getDateRange(value) } data[p] = value resource[p] = value if (isHidden) { if (!this.floatingProps) this.floatingProps = {} this.floatingProps[p] = value } }, hasError(errors, propName) { return (errors && errors[propName]) || this.state.missedRequiredOrErrorValue && this.state.missedRequiredOrErrorValue[propName] }, setChosenValue(propName, value) { let resource = _.cloneDeep(this.state.resource) if (typeof propName === 'object') propName = propName.name // debugger let setItemCount let { metadata, model, search, originatingMessage:originatingResource } = this.props let isItem = metadata != null if (!model && isItem) model = utils.getModel(metadata.items.ref) let prop = model.properties[propName] let isEnum if (prop.ref) isEnum = utils.isEnum(prop.ref) else if (prop.items && prop.items.ref) isEnum = utils.isEnum(prop.items.ref) let isMultichooser = search && prop.ref && utils.isEnum(prop.ref) let isArray = prop.type === 'array' let doDelete let currentR = _.cloneDeep(resource) if (isItem) propName = `${metadata.name}_${propName}` // clause for the items properies - need to redesign if (prop && prop.type === 'array') { if (isEnum) value = value.map(v => utils.buildRef(v)) else value = Array.isArray(value) && value || [value] if (!this.floatingProps) this.floatingProps = {} this.floatingProps[propName] = value if (resource[propName]) { if (Array.isArray(resource[propName])) { if (Array.isArray(value)) { // if (value.length) // value.forEach(v => resource[propName].push(v)) // else resource[propName] = value } else resource[propName].push(value) } else resource[propName] = [resource[propName], value] } else resource[propName] = value } else if (isArray || isMultichooser) { let hasReset if (!Array.isArray(value)) hasReset = value[ROOT_HASH] === '__reset' else hasReset = value.find(v => v[ROOT_HASH] === '__reset') if (hasReset) { if (this.floatingProps && this.floatingProps[propName]) delete this.floatingProps[propName] // resource[propName] = null delete resource[propName] doDelete = true } else ({setItemCount} = this.setArrayOrMultichooser(prop, value, resource)) } else if (value[ROOT_HASH] === '__reset') { if (this.floatingProps && this.floatingProps[propName]) delete this.floatingProps[propName] // resource[propName] = null delete resource[propName] doDelete = true } else { // resource[propName] = utils.buildRef(value) resource[propName] = isEnum ? utils.buildRef(value) : value if (!this.floatingProps) this.floatingProps = {} this.floatingProps[propName] = resource[propName] let data = this.refs.form.refs.input.state.value; if (data) { for (let p in data) if (!resource[p]) resource[p] = data[p]; } } let state = { resource: resource, prop: propName } if (!doDelete) { if (this.state.missedRequiredOrErrorValue) delete this.state.missedRequiredOrErrorValue[propName] if (setItemCount) state.itemsCount = resource[propName].length if (value.photos) state[propName + '_photo'] = value.photos[0] else if (model && prop.ref === PHOTO) state[propName + '_photo'] = value } state.inFocus = propName let r = _.cloneDeep(this.state.resource) for (let p in this.floatingProps) r[p] = this.floatingProps[p] this.setState(state); if (!search) { if (utils.isForm(model)) Actions.getRequestedProperties({resource, currentResource: resource, originatingResource}) if (!utils.isImplementing(r, INTERSECTION)) Actions.saveTemporary(resource) } }, setArrayOrMultichooser(prop, value, resource) { let propName = prop.name let isArray = prop.type === 'array' let setItemCount let isEnum = isArray ? utils.isEnum(prop.items.ref) : utils.isEnum(prop.ref) if (!prop.inlined && prop.items && prop.items.ref && !isEnum) { if (!Array.isArray(value)) { if (isArray) { if (!resource[propName]) value = [value] else { let valueId = utils.getId(value) let hasValue = resource[propName].some(r => utils.getId(r) === valueId) if (hasValue) value = resource[propName] else { let arr = _.cloneDeep(resource[propName]) || [] arr.push(value) value = arr } } } else value = [value] } let v = value.map((vv) => { let val = utils.buildRef(vv) if (vv.photos) val.photo = vv.photos[0].url return val }) if (!resource[propName]) { resource[propName] = [] resource[propName] = v } else { let arr = resource[propName].filter((r) => { return r.id === v.id }) if (!arr.length) resource[propName] = v } return { setItemCount: true } } let val if (prop.items) { if (prop.items.ref && isEnum) val = value.map((v) => utils.buildRef(v)) else val = value } else if (isEnum) { if (value.length) val = value.map((v) => utils.buildRef(v)) } else val = value if (value.length) { resource[propName] = val if (!this.floatingProps) this.floatingProps = {} this.floatingProps[propName] = resource[propName] } else if (prop.items.ref) { resource[propName] = null } else { delete resource[propName] if (this.floatingProps) delete this.floatingProps[propName] } return {} }, // MONEY value and curency template myMoneyInputTemplate(params) { let { required, model, value, prop, editable, errors, component } = params let { search, locale, bankStyle } = this.props let isReadOnly = utils.isReadOnly(prop) let v if (!value.value) v = '' else if (isReadOnly) v = utils.formatCurrency(value, locale) else v = value.value + '' let keyboard = isReadOnly || search ? null : 'numeric' let val = this.myTextInputTemplate({ prop, value: v, required, model, onSubmitEditing: params.onSubmitEditing.bind(this), noError: true, // errors: errors, editable, component, keyboard, }) let currency if (editable) { let cur = utils.normalizeCurrencySymbol(value.currency) let symbol = utils.getModel(MONEY).properties.currency.oneOf.find(c => c[cur]) symbol = symbol && symbol[cur] || cur currency = this.myEnumTemplate({ prop, enumProp: utils.getModel(MONEY).properties.currency, required, value: symbol, // errors: errors, component, // noError: errors && errors[prop], noError: true }) } return ( <View> <View style={styles.moneyInput}> {val} {currency} </View> {this.paintError({prop, errors})} {this.paintHelp(prop)} </View> ); }, myInlinedResourcesTemplate(params) { let { value, editable, prop, component } = params if (editable) return <View /> if (prop.grid) return this.renderSimpleGrid(value, prop, component) this.renderSimpleProp({val: value, pMeta: prop, modelName: prop.items.ref, component}) }, myEnumTemplate(params) { let { prop, enumProp, errors } = params let error if (!params.noError) { let err = this.state.missedRequiredOrErrorValue ? this.state.missedRequiredOrErrorValue[prop.name] : null if (!err && errors && errors[prop.name]) err = errors[prop.name] error = err ? <View style={styles.enumErrorLabel} /> : <View /> } else error = <View/> let value = prop ? params.value : this.state.resource[enumProp.name] let bankStyle = this.props.bankStyle let linkColor = (bankStyle && bankStyle.linkColor) || DEFAULT_LINK_COLOR // let help = this.paintHelp(prop, true) return ( <View style={[styles.chooserContainer, styles.enumElement]} key={this.getNextKey()} ref={enumProp.name}> <TouchableOpacity onPress={this.enumChooser.bind(this, prop, enumProp)}> <View> <View style={styles.chooserContentStyle}> <Text style={styles.enumText}>{value}</Text> <Icon name='ios-arrow-down' size={15} color={linkColor} style={[styles.arrowIcon, styles.enumProp]} /> </View> {error} </View> </TouchableOpacity> </View> ); }, myDurationInputTemplate(params) { let { required, model, value, prop, editable, errors, component } = params let { search, locale } = this.props let isReadOnly = utils.isReadOnly(prop) let v if (!value.value) v = '' // else if (isReadOnly) // v = utils.formatCurrency(value, locale) else v = value.value + '' let keyboard = isReadOnly || search ? null : 'numeric' let val = this.myTextInputTemplate({ prop, value: v, required, model, onSubmitEditing: params.onSubmitEditing.bind(this), noError: true, // errors: errors, editable, component, keyboard, }) let durationType if (editable) { durationType = this.myEnumTemplate({ prop, enumProp: utils.getModel(DURATION).properties.durationType, required, value: value && value.durationType, // errors: errors, component, // noError: errors && errors[prop], noError: true }) } return ( <View> <View style={styles.moneyInput}> {val} {durationType} </View> {this.paintError({prop, errors})} {this.paintHelp(prop)} </View> ); }, getCurrency() { let { currency } = this.props if (!currency) return DEFAULT_CURRENCY if (typeof currency === 'string') return currency return currency.symbol }, enumChooser(prop, enumProp, event) { let resource = this.state.resource; let model = (this.props.model || this.props.metadata) if (!resource) { resource = {}; resource[TYPE] = model.id; } const { navigator, bankStyle, currency, locale } = this.props let currentRoutes = navigator.getCurrentRoutes(); navigator.push({ title: enumProp.title, // titleTextColor: '#7AAAC3', componentName: 'EnumList', backButtonTitle: 'Back', passProps: { prop, bankStyle, enumProp, resource, currency, returnRoute: currentRoutes[currentRoutes.length - 1], callback: this.setChosenEnumValue.bind(this), } }); }, setChosenEnumValue(propName, enumPropName, value) { let resource = _.cloneDeep(this.state.resource) // clause for the items properies - need to redesign // resource[propName][enumPropName] = value const { metadata, parentMeta } = this.props let isItem = metadata && parentMeta if (isItem) propName = `${metadata.name}_${propName}` let key = Object.keys(value)[0] if (!isNaN(key)) key = value if (resource[propName]) { if (typeof resource[propName] === 'object') resource[propName][enumPropName] = key else { resource[propName] = { value: resource[propName], [enumPropName]: key } } } // if no value set only currency else { resource[propName] = {} resource[propName][enumPropName] = key if (!this.floatingProps) this.floatingProps = {} if (!this.floatingProps[propName]) this.floatingProps[propName] = {} this.floatingProps[propName][enumPropName] = key } let data = this.refs.form.refs.input.state.value; if (data) { for (let p in data) if (!resource[p]) resource[p] = data[p]; } this.setState({ resource: resource, prop: propName }); }, validateProperties(value) { let m = value[TYPE] ? utils.getModel(value[TYPE]) : this.props.model let properties = m.properties let err = [] let deleteProps = [] for (let p in value) { let prop = properties[p] if (!prop) // properties like _t, _r, time continue if (typeof value[p] === 'undefined' || value[p] === null) { deleteProps.push(p) continue } if (prop.type === 'number') this.checkNumber(value[p], prop, err) else if (prop.ref === MONEY) { let error = this.checkNumber(value[p], prop, err) if (error && m.required && m.required.indexOf(p) === -1) deleteProps.push(p) else if (!value[p].currency && this.props.currency) value[p].currency = this.props.currency } else if (prop.units && prop.units === '[min - max]') { let v = value[p].split('-').map(coerceNumber) if (v.length === 1) this.checkNumber(v, prop, err) else if (v.length === 2) { this.checkNumber(v[0], prop, err) if (err[p]) continue this.checkNumber(v[1], prop, err) if (!err[p]) continue if (v[1] < v[0]) err[p] = translate('theMinValueBiggerThenMaxValue') //'The min value for the range should be smaller then the max value' } else err[p] = translate('thePropertyWithMinMaxRangeError') // The property with [min-max] range can have only two numbers' } // 'pattern' can be regex pattern or property where the pattern is defined. // It is for country specific patterns like 'phone number' else if (prop.pattern) { if (!value[p]) deleteProps.push(p) if (!(new RegExp(prop.pattern).test(value[p]))) err[prop.name] = translate('invalidProperty', prop.title) } } if (deleteProps) deleteProps.forEach((p) => { delete value[p] delete err[p] }) return err }, checkNumber(v, prop, err) { let p = prop.name let error if (typeof v !== 'number') { if (prop.ref === MONEY && typeof v === 'object') v = v.value } if (isNaN(v)) error = 'Please enter a valid number' else { if (prop.max && v > prop.max) error = 'The maximum value for is ' + prop.max else if (prop.min && v < prop.min) error = 'The minimum value for is ' + prop.min } if (error) err[p] = error return error }, } function coerceNumber (obj, p) { const val = obj[p] if (typeof val === 'string') { obj[p] = Number(val.trim()) } } const formField = { minHeight: 60, backgroundColor: '#ffffff', borderWidth: StyleSheet.hairlineWidth, borderColor: '#dddddd', borderRadius: 6, } var styles= StyleSheet.create({ enumProp: { marginTop: 15, }, enumText: { marginTop: 10, marginLeft: 20, marginRight: 3, color: '#757575', fontSize: 20 }, labelStyle: { paddingLeft: 10, }, arrowIcon: { width: 15, height: 15, // marginVertical: 2 }, formInput: { ...formField, marginHorizontal: 15 }, booleanContainer: { ...formField, // minHeight: 60, paddingTop: 5, paddingHorizontal: 10, marginHorizontal: 15, justifyContent: 'center', flex: 1 }, booleanContentStyle: { flexDirection: 'row', justifyContent: 'space-between' }, datePicker: { justifyContent: 'flex-start', alignSelf: 'stretch', paddingHorizontal: 10, paddingRight: 22 }, chooserContainer: { // ...formField, minHeight: 60, flexDirection: 'row', justifyContent: 'space-between', marginHorizontal: 10, position: 'relative', flex: 1 }, chooserContentStyle: { justifyContent: 'space-between', flexDirection: 'row', borderRadius: 4 }, enumElement: { width: 40, marginTop: 20, height: 45 }, enumErrorLabel: { paddingLeft: 5, height: 14, backgroundColor: 'transparent' }, regInput: { borderWidth: 0, height: 50, fontSize: 20, color: '#eeeeee' }, textInput: { borderWidth: 0, color: '#555555', fontSize: 20 }, thumb: { width: 40, height: 40, marginRight: 2, borderRadius: 5, }, err: { paddingHorizontal: 15, // backgroundColor: 'transparent' }, element: { position: 'relative' }, labelClean: { marginTop: 21, color: '#AAA', position: 'absolute', fontSize: 20, top: 7 }, labelDirty: { marginTop: 21, // marginLeft: 10, paddingLeft: 10, color: '#AAA', position: 'absolute', fontSize: 12, top: -17, }, photoIcon: { position: 'absolute', right: 0, bottom: 3 }, lockIcon: { position: 'absolute', right: 0, bottom: 5 }, photoIconEmpty: { position: 'absolute', right: 0, marginTop: 15 }, readOnly: { position: 'absolute', right: 25, top: 20 }, immutable: { marginTop: 15, paddingRight: 10 }, input: { backgroundColor: 'transparent', color: '#aaaaaa', fontSize: 20, }, textAfterImage: { backgroundColor: 'transparent', color: '#aaaaaa', fontSize: 20, marginTop: 17, marginLeft: 7 }, customIcon: { // marginTop: 20, position: 'absolute', right: isWeb() && 10 || 0, alignSelf: 'center' }, dateInput: { flex: 1, height: 35, paddingBottom: 5, // marginTop: 5, // borderWidth: 1, borderColor: 'transparent', // borderBottomColor: '#eeeeee', alignItems: 'flex-start', justifyContent: 'center' }, dateText: { fontSize: 20, color: '#555555', }, // font18: { // fontSize: 18, // }, font20: { fontSize: 20, }, dateIcon: { // position: 'absolute', // right: 0, // top: 5 }, divider: { // justifyContent: 'center', borderColor: 'transparent', borderWidth: 1.5, marginTop: 10, // marginHorizontal: 10, paddingHorizontal: 13, marginBottom: 5 }, dividerText: { marginBottom: 5, fontSize: 26, fontWeight: '500', color: '#ffffff' }, font14: { fontSize: 14 }, booleanLabel: { color: '#aaaaaa', fontSize: 20 }, booleanText: { fontSize: 20 }, dateLabel: { marginLeft: 10, fontSize: 12, marginTop: 5, paddingBottom: 5 }, noItemsText: { fontSize: 20, color: '#AAAAAA', }, markdown: { backgroundColor: '#f7f7f7', padding: 10 // paddingVertical: 10, }, container: { flex: 1 }, help1: { backgroundColor: utils.isAndroid() ? '#eeeeee' : '#efefef', paddingHorizontal: 15, }, help: { backgroundColor: '#f3f3f3', paddingHorizontal: 20, paddingBottom: 15 }, bottom10: { paddingBottom: 10 }, floatingLabel: { marginTop: 20 }, moneyInput: { flexDirection: 'row', justifyContent: 'space-between' }, accent: { width: 12, borderLeftWidth: 5, } }) module.exports = NewResourceMixin
src/components/shared/Validate.js
juandjara/open-crono
import React from 'react'; import PropTypes from 'prop-types'; function getValidationErrors( rules = [], model = {}, touched = {}, ignoreTouched = false ) { const rulesWithError = rules.filter(rule => { const [key, validator] = rule let ruleHasError = !validator(model) if(!ignoreTouched) { ruleHasError = ruleHasError && touched[key] } return ruleHasError }) return rulesWithError.reduce((errors, rule) => { const key = rule[0] const errorMessage = rule[2] errors[key] = errorMessage return errors }, {}) } const validateRules = (rules) => { if(!rules.every(rule => rule.length === 3)) { throw new Error('Expected every rule to be an array of 3 elements') } rules.forEach((rule, index) => { if(typeof rule[0] !== 'string') { throw new Error(` Expected first element of rule ${index} to be of type string but found ${typeof rule[0]} `) } if(typeof rule[1] !== 'function') { throw new Error(` Expected first element of rule ${index} to be of type function but found ${typeof rule[0]} `) } if(typeof rule[2] !== 'string') { throw new Error(` Expected first element of rule ${index} to be of type string but found ${typeof rule[0]} `) } }) } const Validate = (rules) => WrappedComponent => { validateRules(rules) const Wrapper = props => { const validationErrors = getValidationErrors(rules, props.model, props.touched) const rawValidation = getValidationErrors(rules, props.model, props.touched, true) const isValid = Object.keys(rawValidation).length === 0 return ( <WrappedComponent {...props} validationErrors={validationErrors} isValid={isValid} /> ) } const name = WrappedComponent.displayName || WrappedComponent.name Wrapper.displayName = `Validate(${name})` Wrapper.propTypes = { model: PropTypes.object.isRequired, touched: PropTypes.object.isRequired } return Wrapper } export const isRequired = key => ([ key, model => !!model[key], 'Este campo es obligatorio' ]) export const passwordMatch = (key, repeatKey) => ([ key, model => model[key] === model[repeatKey], 'Las contraseñas deben coincidir' ]) export default Validate
fields/types/datearray/DateArrayField.js
Pop-Code/keystone
import ArrayFieldMixin from '../../mixins/ArrayField'; import DateInput from '../../components/DateInput'; import Field from '../Field'; import React from 'react'; import moment from 'moment'; const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD'; const DEFAULT_FORMAT_STRING = 'Do MMM YYYY'; module.exports = Field.create({ displayName: 'DateArrayField', statics: { type: 'DateArray', }, mixins: [ArrayFieldMixin], propTypes: { formatString: React.PropTypes.string, inputFormat: React.PropTypes.string, }, getDefaultProps () { return { formatString: DEFAULT_FORMAT_STRING, inputFormat: DEFAULT_INPUT_FORMAT, }; }, processInputValue (value) { if (!value) return; const m = moment(value); return m.isValid() ? m.format(this.props.inputFormat) : value; }, formatValue (value) { return value ? moment(value).format(this.props.formatString) : ''; }, getInputComponent () { return DateInput; }, });
imports/ui/pages/AddPaperToJournalEdition/AddPaperToJournalEdition.js
jamiebones/Journal_Publication
/* eslint-disable */ import React from 'react'; import PropTypes from 'prop-types'; import { Meteor } from 'meteor/meteor'; import { withTracker } from 'meteor/react-meteor-data'; import { _ } from 'meteor/underscore'; import Papers from '../../../api/Papers/Papers'; import Journals from '../../../api/Journal/Journal'; import { Bert } from 'meteor/themeteorchef:bert'; import {Treebeard} from 'react-treebeard'; import { Row, Col, FormGroup, ControlLabel, Table , ButtonGroup , Panel , PanelGroup , InputGroup ,FormControl, Button , Label , Modal , Well , Alert } from 'react-bootstrap'; import { Capitalize , paymentType , sumMeUp , AuthorRank } from '../../../modules/utilities'; import { extractPapersInJournalEdition, SortPublicationEditions, StripHtml } from '../../../modules/utilities2'; import Loading from '../../components/Loading/Loading'; import moment from 'moment'; import { templateParser, templateFormatter, parseDigit } from 'input-format' import { ReactInput } from 'input-format'; import DatePicker from 'react-datepicker'; import renderHTML from 'react-render-html'; import './AddPaperToJournalEdition.scss'; removePaperFromJournal = ( paperId , journalId , published) => { if (published){ Bert.alert('Can\'t remove a paper already published on a journal' , 'danger'); return ; } if (confirm('Do you want to remove the selected paper')){ Meteor.call('journal.removePaperFromJournal' , journalId , paperId , (error , response) => { if (response){ Bert.alert('Paper removed successfully' , 'success'); } else{ Bert.alert(error.reason , 'danger'); } }) } } class AddPaperToJournalEdition extends React.Component{ constructor( props ){ super( props ); this.state = { selectedValue : "", selectedEdition : "", published : "" , date : "", selectedIndex : [], selectedPaperDetails : [], showPagesInput : false , pageInput : [], editPage : "00-000", showModal : false , paperId : "" , editionId : "", submitted : false, startDate: moment(), } this.handleSelectChange = this.handleSelectChange.bind( this ); this.handleChange = this.handleChange.bind( this ) this.addSelectedPaper = this.addSelectedPaper.bind( this ); this.removeSelectedPaper = this.removeSelectedPaper.bind( this ); this.addPaperToEdition = this.addPaperToEdition.bind( this ); this.publishPaperEdition = this.publishPaperEdition.bind( this ); this.editPageNumber = this.editPageNumber.bind( this ); this.close = this.close.bind( this); this.open = this.open.bind( this ); this.submitEditedPageNumber = this.submitEditedPageNumber.bind( this ); this.handleDateChange = this.handleDateChange.bind( this ); } editPageNumber( event , pages , id , editionId ){ event.preventDefault(); this.setState({"editPage" : pages }); this.setState({ showModal: true , paperId : id , editionId : editionId }) } close() { this.setState({ showModal: false }); } open() { this.setState({ showModal: true }); } handleChange( value , index ) { const pageInput = this.state.pageInput; pageInput[index] = value this.setState({"pageInput" : pageInput }) } handlePageEditChange( value ) { const pageInput = value; this.setState({"editPage" : pageInput }) } submitEditedPageNumber( event ){ const { editionId , paperId } = this.state; const input = document.getElementById('pageEditInput'); const pages = input.value; const { journals } = this.props; const journalId = journals && journals[0]._id; Meteor.call('journal.editPageNumber' , journalId , editionId , paperId , pages || "" , (error , response ) => { if (response){ Bert.alert( 'Edited' , 'success'); this.setState({"showModal" : false }); } else{ Bert.alert(`${error}` , 'danger'); } }); } publishPaperEdition( event ){ event.preventDefault(); const {papers , journals} = this.props; const editionId = this.state.selectedValue; const editionName = this.state.selectedEdition; const publishedDate =moment( this.state.startDate ).format(); this.setState({ submitted : true }); const journalId = journals[0] && journals[0]._id; const papersInJournal = extractPapersInJournalEdition( journals[0] && journals[0].publishedEditions , editionId); //extract only the id of the paper const paperIdArray = papersInJournal.map(({id})=> { return id; }); const confirmPubDate = confirm(`Please confirm the publication date for this issue ${moment(this.state.startDate).format('MMMM Do, YYYY [at] hh:mm a')}`) if ( !confirmPubDate ) { Bert.alert('Select the correct date' , 'danger'); return } const askMe = confirm('This action is not reversible. Are you sure you want to publish the selected papers to the journal edition.') if ( askMe ) { Meteor.call('journal.publishEdition' , journalId , editionId , paperIdArray , editionName, publishedDate ,(error , response ) => { if ( ! error ){ this.setState({"published" : "true" , "submitted" : true }); Bert.alert( `Journal Issue was published successfully.` , 'success'); } else{ this.setState({"submitted" : true }); Bert.alert( `${error}` , 'danger'); } }); } } addPaperToEdition( event ){ event.preventDefault(); //get the value of the pages input let elementArray; let pagesFilled = true; if ( this.state.showPagesInput ) { const pagesInput = document.getElementsByClassName('pagesInput'); elementArray = [ ...pagesInput ]; for (let i=0; i < elementArray.length; i++){ const element = elementArray[i]; const value = element.value; const id = element.dataset.index; if ( value == ""){ element.classList.add('error'); pagesFilled = false; } } } if (! pagesFilled ){ Bert.alert('Please enter the page number.') return false; } const {papers , journals} = this.props; const editionId = this.state.selectedValue; const journalId = journals[0] && journals[0]._id; const hiddenField = document.getElementsByClassName('paperIdHidden'); const paperIdArray = [...hiddenField ]; let idArray = []; let paperDetails = []; paperIdArray.map((id)=> { const details = _.find(papers , (paper) => { return paper._id == id.value; }); let obj; if ( this.state.showPagesInput ) { const elementInput = _.find( elementArray , ( element ) => { return details._id === element.dataset.index; }); const pages = elementInput.value; obj = { "paperTitle" : details.title, "abstract" : details.abstract, "authors" : details.authors , "links" : details.pdf, "id" : details._id, "pages" : pages , "paperType" : details.paperType , "views" : 0 , "downloads" : 0 }; } else{ obj = { "paperTitle" : details.title, "abstract" : details.abstract, "authors" : details.authors , "links" : details.pdf, "id" : details._id, "paperType" : details.paperType , "views" : 0 , "pages" : "", "downloads" : 0 }; } const pages = obj.pages; paperDetails.push( obj ); const objToUpdatePaper = { id : id.value , pages : pages } idArray.push( objToUpdatePaper ); }); const askMe = confirm('This action is not reversible. Are you sure you want to add the selected papers to the journal edition.') if ( askMe ) { Meteor.call('journal.addPapersToEdition' , journalId , editionId , idArray , paperDetails , (error , response ) => { if (response){ Bert.alert( 'paper added succesfully' , 'success'); this.state.selectedPaperDetails = []; } else{ Bert.alert(`${error}` , 'danger'); } }); } } addSelectedPaper(index , id){ const selectedIndex = this.state.selectedIndex; const pageInput = this.state.pageInput; const {papers} = this.props; selectedIndex[index]["selected"] = true; pageInput[index] = ""; //fill the table with the selected paper details const arr = this.state.selectedPaperDetails; const details = _.find(papers , (paper) => { return paper._id == id; }); arr.push( details ); this.setState({"selectedPaperDetails" : arr , "selectedIndex" : selectedIndex , "pageInput" : pageInput }); } removeSelectedPaper(index , id){ const selectedIndex = this.state.selectedIndex; let pageInput = this.state.pageInput; pageInput.splice( index , 1 ); const {papers} = this.props; const selectedDetails = _.find(papers , (paper) => { return paper._id == id; }); //loop through and find the one being removed for(let i=0; i < selectedIndex.length; i++){ if ( selectedIndex[i]["id"] == selectedDetails._id ) { selectedIndex[i]["selected"] = false; } } //fill the table with the selected paper details const arr = this.state.selectedPaperDetails; const filter = arr.filter(( paper , index)=> { return paper._id !== selectedDetails._id }); this.setState({"selectedPaperDetails" : filter , "selectedIndex" : selectedIndex , "pageInput" : pageInput }); } handleSelectChange( event ){ event.preventDefault(); const sel = document.querySelector(`[name="journalEdition"]`); const published = sel.options[sel.selectedIndex].dataset.pub; const date = sel.options[sel.selectedIndex].dataset.date; const selectedEdition = sel.options[sel.selectedIndex].text; if ( selectedEdition !== "select journal edition" ){ this.setState({"selectedEdition" : selectedEdition , "selectedValue" : event.target.value, "published" : published , "date" : date }); } else{ this.setState({"selectedEdition" : "" , "selectedValue" : "", "published" : "" , "date" : "" }); } } componentWillReceiveProps(nextProps) { const {papers} = nextProps; let selState = []; papers && papers.length && papers.map(({_id} , index) => { const obj = { "id" : _id , "selected" : false , } selState.push( obj ); }); this.setState({"selectedIndex" : selState}); } handleDateChange(date) { this.setState({ startDate: date }); } render(){ const { papers , loading , journals , history } = this.props; const sortedEditions = SortPublicationEditions( journals[0] && journals[0].publishedEditions && journals[0].publishedEditions) const { published , date , selectedEdition , selectedValue , selectedIndex , selectedPaperDetails , showPagesInput } = this.state; const TEMPLATE = 'xx-xxx' const parse = templateParser(TEMPLATE, parseDigit); const format = templateFormatter(TEMPLATE) return ( !loading ? ( <div> {journals[0] && journals[0].publishedEditions && journals[0].publishedEditions.length ? ( <Row> <Col mdOffset={2} md={8}> <Well> <FormGroup> <select className="form-control" name="journalEdition" onChange={(event)=>this.handleSelectChange(event)} defaultValue={this.state.selectedEdition}> <option value="0">select journal edition</option> { sortedEditions.length && sortedEditions.map(({editionName , editionId , published , creationDate })=> { return ( <option key={editionId} value={editionId} data-pub={published} data-date={creationDate}> {editionName} </option> ) })} </select> </FormGroup> </Well> <br/> <hr/> </Col> </Row> ) : <Alert><h4>No Journal Volume Created Yet!</h4></Alert> } <Row> <Col mdOffset={2} md={8}> <p> {selectedValue ? (<span>Selected Edition : <b>{Capitalize(selectedEdition)}</b></span>) : ""} <br/> {selectedValue ? (<span>Published : <Label bsStyle={published === "true" ? ("success") : "default"}> {published === "true" ? ("Yes") : "No"}</Label></span> ) : ""} <br/> {selectedValue ? ( <span>Created on : {moment(selectedValue && date).format('MMMM Do, YYYY [at] hh:mm a')} </span>) : ""} <br/> </p> <div> {selectedValue ? (extractPapersInJournalEdition( journals[0] && journals[0].publishedEditions && journals[0].publishedEditions , this.state.selectedValue).length ? ( published === "false" ? ( <div> <div className="datePickerDiv"> <p>Published Date:</p> <DatePicker selected={this.state.startDate} onChange={this.handleDateChange} className="form-control" placeholderText="MM-DD-YYYY" id="publishedDate" /> </div> <br/> <Button disabled={this.state.submitted} onClick={(event)=>this.publishPaperEdition(event)} bsStyle={this.state.submitted ? "success" : "info"} bsSize="xsmall"> { this.state.submitted ? 'Please wait----------' : "Publish Journal Issue"} </Button> </div> ) : "" ) :"" ) : ""} </div> <br/> <hr/> { this.state.selectedValue ? ( <div className="papersJournal"> <p className="text-center"><b>Papers in journal </b></p> <hr/> {this.state.selectedValue ? extractPapersInJournalEdition( journals[0] && journals[0].publishedEditions && journals[0].publishedEditions , this.state.selectedValue).length ? ( extractPapersInJournalEdition( journals[0] && journals[0].publishedEditions && journals[0].publishedEditions , this.state.selectedValue).map(({ paperTitle , links , id , pages } , index )=> { return ( <div key={sumMeUp(index , 3)}> { Capitalize(StripHtml(paperTitle))} <p> <br/> <span>Page Number : <b>{pages ? pages : "Nil"}</b></span> <br/> <span className="pull-right"> <Button onClick={( event ) => this.editPageNumber( event , pages || "" , id , this.state.selectedValue )} bsStyle="danger" bsSize="xsmall"> Edit page </Button> </span> <br/> </p> <hr/> </div> ) }) ) : <div> <br/> <Alert> <h4>No papers in selected edition.</h4> </Alert> </div> : "" } </div> ) : <div></div>} </Col> </Row> <Row> <Col md={4} className="approvedPapers"> <br/> <br/> <br/> {selectedValue && published === "false" ? ( papers.length ? ( <div> <p className="text-center">Approved <b>(paid)</b> paper(s) for publication</p> {papers.map(({title , _id , pdf , confirmPdf },index)=>{ return (<div key={index}> {StripHtml(title)} <div> { pdf ? ( confirmPdf && confirmPdf.pdfConfirmed ? ( <p> <Button disabled={selectedIndex[index]["selected"] ? true : false } onClick={()=> this.addSelectedPaper(index , _id )} bsSize="xsmall" bsStyle="success" className="addButton"> Add Paper </Button> </p> ) : <p> <b>Paper not yet confirmed by author</b> </p> ) : <p> <Button onClick={()=>history.push(`/auth/upload/doc_to_pdf/${_id}`)} bsSize="xsmall" bsStyle="warning" className="addButton"> Upload Pdf </Button> </p> } </div> <hr/> </div>) })} </div> ) : <div> <br/> <br/> <p className="text-center"><b>Approved Papers</b></p> <hr/> <Alert bsStyle="info"><p>No approved paper.</p></Alert> </div>) : <div></div>} </Col> <Col md={8}> { selectedPaperDetails && selectedPaperDetails.length ? ( <div> <div className="selectedPaperInfo"> <p className="text-center"><b>Selected papers for publishing </b></p> <p className="text-center"> <Button bsSize="small" bsStyle={showPagesInput ? "danger" : "default"} onClick={()=>this.setState({showPagesInput : ! showPagesInput})}> {!showPagesInput ? ("Click to add pages input") : "Click to remove pages input"} </Button> </p> <p className="text-center">If this edition has an hard copy please click the button above to add pages to the selected issue </p> </div> <Table condensed responsive> <thead> <tr> <th>S/N</th> <th>Paper Title</th> <th>Authors</th> { showPagesInput ? (<th>Pages</th>) : <th></th> } </tr> </thead> <tbody> { selectedPaperDetails && selectedPaperDetails.length && selectedPaperDetails.map(({_id , title , authors }, index)=>{ return ( <tr key={sumMeUp(index , 22)}> <td> {sumMeUp( 1 , index)} <input type="hidden" className="paperIdHidden" defaultValue={_id} /> </td> <td> { StripHtml(title)} </td> <td> {authors.map(({title , firstname , surname , rank} , index )=> { return ( <p key={sumMeUp(index , 10)}>{title && Capitalize(title)} {Capitalize(firstname)} {Capitalize(surname)} &nbsp;&nbsp;||&nbsp;&nbsp;{AuthorRank(rank)} </p> ) })} </td> {showPagesInput ? ( <td> <ReactInput value={this.state.pageInput[ index ]} onChange={( value )=> this.handleChange( value , index )} className="form-control pagesInput" parse={parse} format={format} placeholder="00-00" data-index={ _id } /> </td> ) : <td></td> } <td> <Button onClick={()=>this.removeSelectedPaper(index , _id)} bsStyle="danger" bsSize="xsmall"> Remove </Button> </td> </tr> ) })} </tbody> </Table> <p className="pull-right"> <Button bsStyle="success" onClick={(event)=>this.addPaperToEdition(event)}> Add Paper(s) To Edition </Button> </p> </div> ) : <div></div> } </Col> </Row> {/* Modal starts*/} <Row> <div className="ModalOverlay"> <Modal show={this.state.showModal} onHide={this.close} dialogClassName="custom-modal" aria-labelledby="contained-modal-title-small"> <Modal.Header closeButton bsSize="small" aria-labelledby="contained-modal-title-small"> <Modal.Title>Page Number</Modal.Title> </Modal.Header> <Modal.Body> <Row> <Col md={12}> <Col mdOffset={3} md={6}> <ReactInput value={ this.state.editPage } onChange={( value )=> this.handlePageEditChange( value )} className="form-control pagesInput" id="pageEditInput" parse={parse} format={format} placeholder="00-00" /> </Col> </Col> </Row> </Modal.Body> <Modal.Footer> <ButtonGroup> <Button onClick={(event)=> this.submitEditedPageNumber(event)} bsStyle="danger" >Save Changes</Button> <Button onClick={this.close}>Close</Button> </ButtonGroup> </Modal.Footer> </Modal> </div> </Row> {/* modal ends */} </div> ) : <Loading /> ) } } export default AddPaperToJournalEditionContainer = withTracker(() => { const subscription = Meteor.subscribe('journals.getApprovedPapersPaidForNotPublished'); return { loading: !subscription.ready(), papers : Papers.find({"currentPaperStatus" : "09" , "publishFeePaid" : true , "paperPublished" : false }).fetch(), journals : Journals.find({"owner" : Meteor.userId() }).fetch(), }; }) (AddPaperToJournalEdition );
src/components/NavBar.js
happy-dev/petitbus_mobile
import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity, } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; const NavBar = React.createClass({ tabIcons: [], propTypes: { goToPage: React.PropTypes.func, activeTab: React.PropTypes.number, tabs: React.PropTypes.array, }, componentDidMount() { this._listener = this.props.scrollValue.addListener(this.setAnimationValue); }, setAnimationValue({ value, }) { this.tabIcons.forEach((icon, i) => { const progress = (value - i >= 0 && value - i <= 1) ? value - i : 1; icon.setNativeProps({ style: { color: this.iconColor(progress), }, }); }); }, //color between rgb(59,89,152) and rgb(204,204,204) iconColor(progress) { const red = 59 + (204 - 59) * progress; const green = 89 + (204 - 89) * progress; const blue = 152 + (204 - 152) * progress; return `rgb(${red}, ${green}, ${blue})`; }, render() { return <View style={[styles.tabs, this.props.style, ]}> {this.props.tabs.map((tab, i) => { return <TouchableOpacity key={tab} onPress={() => this.props.goToPage(i)} style={styles.tab}> <Icon name={tab} size={30} color={this.props.activeTab === i ? 'rgb(59,89,152)' : 'rgb(204,204,204)'} ref={(icon) => { this.tabIcons[i] = icon; }} /> </TouchableOpacity>; })} </View>; }, }); const styles = StyleSheet.create({ tab: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingBottom: 10, }, tabs: { height: 45, flexDirection: 'row', paddingTop: 5, borderWidth: 1, borderTopWidth: 0, borderLeftWidth: 0, borderRightWidth: 0, borderBottomColor: 'rgba(0,0,0,0.05)', }, }); export default NavBar;
app/jsx/bundles/context_modules.js
venturehive/canvas-lms
/* * Copyright (C) 2011 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import $ from 'jquery' import React from 'react' import ReactDOM from 'react-dom' import ModulesHomePage from 'jsx/courses/ModulesHomePage' import modules from 'context_modules' const container = document.getElementById('modules_homepage_user_create') if (container) { ReactDOM.render(<ModulesHomePage onCreateButtonClick={modules.addModule} />, container) } if (ENV.NO_MODULE_PROGRESSIONS) { $('.module_progressions_link').remove() }
app/javascript/mastodon/features/compose/components/navigation_bar.js
primenumber/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ActionBar from './action_bar'; import Avatar from '../../../components/avatar'; import Permalink from '../../../components/permalink'; import IconButton from '../../../components/icon_button'; import { FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class NavigationBar extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, onLogout: PropTypes.func.isRequired, onClose: PropTypes.func, }; render () { return ( <div className='navigation-bar'> <Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}> <span style={{ display: 'none' }}>{this.props.account.get('acct')}</span> <Avatar account={this.props.account} size={48} /> </Permalink> <div className='navigation-bar__profile'> <Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}> <strong className='navigation-bar__profile-account'>@{this.props.account.get('acct')}</strong> </Permalink> <a href='/settings/profile' className='navigation-bar__profile-edit'><FormattedMessage id='navigation_bar.edit_profile' defaultMessage='Edit profile' /></a> </div> <div className='navigation-bar__actions'> <IconButton className='close' title='' icon='close' onClick={this.props.onClose} /> <ActionBar account={this.props.account} onLogout={this.props.onLogout} /> </div> </div> ); } }
jenkins-design-language/src/js/components/material-ui/svg-icons/maps/rate-review.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsRateReview = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 14v-2.47l6.88-6.88c.2-.2.51-.2.71 0l1.77 1.77c.2.2.2.51 0 .71L8.47 14H6zm12 0h-7.5l2-2H18v2z"/> </SvgIcon> ); MapsRateReview.displayName = 'MapsRateReview'; MapsRateReview.muiName = 'SvgIcon'; export default MapsRateReview;
src/pages/repl.js
frintjs/frint.js.org
import React from 'react'; const ReplPage = () => { return ( <div> <section className="editor-section"> <iframe sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin" src="https://codesandbox.io/embed/6MNkoppL" style={{ width: '100%', height: '1200px', border: 0, 'borderRadius': '4px', overflow: 'hidden' }} /> </section> </div> ); }; export default ReplPage;
docs/src/pages/demos/progress/LinearBuffer.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import { LinearProgress } from 'material-ui/Progress'; const styles = { root: { flexGrow: 1, }, }; class LinearBuffer extends React.Component { state = { completed: 0, buffer: 10, }; componentDidMount() { this.timer = setInterval(this.progress, 500); } componentWillUnmount() { clearInterval(this.timer); } timer = null; progress = () => { const { completed } = this.state; if (completed > 100) { this.setState({ completed: 0, buffer: 10 }); } else { const diff = Math.random() * 10; const diff2 = Math.random() * 10; this.setState({ completed: completed + diff, buffer: completed + diff + diff2 }); } }; render() { const { classes } = this.props; const { completed, buffer } = this.state; return ( <div className={classes.root}> <LinearProgress variant="buffer" value={completed} valueBuffer={buffer} /> <br /> <LinearProgress color="secondary" variant="buffer" value={completed} valueBuffer={buffer} /> </div> ); } } LinearBuffer.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(LinearBuffer);
spec/javascripts/jsx/account_course_user_search/UsersListSpec.js
djbender/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {shallow, mount} from 'enzyme' import UsersList from 'jsx/account_course_user_search/components/UsersList' import UsersListRow from 'jsx/account_course_user_search/components/UsersListRow' QUnit.module('Account Course User Search UsersList View') const usersProps = { accountId: '1', users: [ { id: '1', name: 'UserA', avatar_url: 'http://someurl' }, { id: '2', name: 'UserB', avatar_url: 'http://someurl' }, { id: '3', name: 'UserC', avatar_url: 'http://someurl' } ], handlers: { handleOpenEditUserDialog() {}, handleSubmitEditUserForm() {}, handleCloseEditUserDialog() {} }, permissions: { can_masquerade: true, can_message_users: true, can_edit_users: true }, searchFilter: { search_term: 'User', sort: 'username', order: 'asc' }, onUpdateFilters: sinon.spy(), onApplyFilters: sinon.spy(), roles: {} } test('displays users that are passed in as props', () => { const wrapper = shallow(<UsersList {...usersProps} />) const nodes = wrapper.find(UsersListRow).getElements() equal(nodes[0].props.user.name, 'UserA') equal(nodes[1].props.user.name, 'UserB') equal(nodes[2].props.user.name, 'UserC') }) Object.entries({ username: 'Name', email: 'Email', sis_id: 'SIS ID', last_login: 'Last Login' }).forEach(([columnID, label]) => { Object.entries({ asc: { expectedArrow: 'Up', unexpectedArrow: 'Down', expectedTip: `Click to sort by ${label} descending` }, desc: { expectedArrow: 'Down', unexpectedArrow: 'Up', expectedTip: `Click to sort by ${label} ascending` } }).forEach(([sortOrder, {expectedArrow, unexpectedArrow, expectedTip}]) => { const props = { ...usersProps, searchFilter: { search_term: 'User', sort: columnID, order: sortOrder } } test(`sorting by ${columnID} ${sortOrder} puts ${expectedArrow}-arrow on ${label} only`, () => { const wrapper = mount(<UsersList {...props} />) equal( wrapper.find(`IconMiniArrow${unexpectedArrow}Solid`).length, 0, `no columns have an ${unexpectedArrow} arrow` ) const icons = wrapper.find(`IconMiniArrow${expectedArrow}Solid`) equal(icons.length, 1, `only one ${expectedArrow} arrow`) const header = icons.closest('UsersListHeader') ok( header .find('Tooltip') .first() .prop('tip') .match(RegExp(expectedTip, 'i')), 'has right tooltip' ) ok(header.text().includes(label), `${label} is the one that has the ${expectedArrow} arrow`) }) test(`clicking the ${label} column header calls onChangeSort with ${columnID}`, () => { const sortSpy = sinon.spy() const wrapper = mount( <UsersList {...{ ...props, onUpdateFilters: sortSpy }} /> ) const header = wrapper .find('UsersListHeader') .filterWhere(n => n.text().includes(label)) .find('button') header.simulate('click') ok(sortSpy.calledOnce) ok( sortSpy.calledWith({ search_term: 'User', sort: columnID, order: sortOrder === 'asc' ? 'desc' : 'asc', role_filter_id: undefined }) ) }) }) }) test('component should not update if props do not change', () => { const instance = new UsersList(usersProps) notOk(instance.shouldComponentUpdate({...usersProps})) }) test('component should update if a prop is added', () => { const instance = new UsersList(usersProps) ok(instance.shouldComponentUpdate({...usersProps, newProp: true})) }) test('component should update if a prop is changed', () => { const instance = new UsersList(usersProps) ok(instance.shouldComponentUpdate({...usersProps, users: {}})) }) test('component should not update if only the searchFilter prop is changed', () => { const instance = new UsersList(usersProps) notOk(instance.shouldComponentUpdate({...usersProps, searchFilter: {}})) })
src/main.js
vamc-anne/react-redux-poc
import React from 'react' import ReactDOM from 'react-dom' import createStore from './store/createStore' import './styles/main.scss' // Store Initialization // ------------------------------------ const store = createStore(window.__INITIAL_STATE__) // Render Setup // ------------------------------------ const MOUNT_NODE = document.getElementById('root') let render = () => { const App = require('./components/App').default const routes = require('./routes/index').default(store) ReactDOM.render( <App store={store} routes={routes} />, MOUNT_NODE ) } // Development Tools // ------------------------------------ if (__DEV__) { if (module.hot) { const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react').default ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) } render = () => { try { renderApp() } catch (e) { console.error(e) renderError(e) } } // Setup hot module replacement module.hot.accept([ './components/App', './routes/index', ], () => setImmediate(() => { ReactDOM.unmountComponentAtNode(MOUNT_NODE) render() }) ) } } // Let's Go! // ------------------------------------ if (!__TEST__) render()
app/components/Print/index.js
IntAlert/chatplayer
/** * * Print * */ import React from 'react'; import styled from 'styled-components'; import './styles.css'; const ImageContainer = styled.div` text-align:center; `; const PrintLink = styled.a` display:block; text-align:center; background:#5cbfdc; color:#fff; text-decoration:none; border-radius:5px; margin:1em; padding:1em; &:hover { cursor:pointer; background:#085FFF; } `; const print = () => { window.print(); setTimeout(() => { window.location.href = '/'; }, 100); }; function Print() { return ( <div> <div className="no-print"> <ImageContainer> <img src="/images/cookie-dough-detail.png" alt="Free Icecream" /> <br /> <h1>One free ice cream topping</h1> </ImageContainer> <ImageContainer> <img src="/images/barcode.png" alt="barcode" /> </ImageContainer> <PrintLink onClick={print}> Print </PrintLink> </div> <div className="token"> <div className="logo"> <img src="/images/logo.svg" alt="logo" /> </div> <p> Congratulations!! You have beaten our Tomato Trader Challenge. Head over to the Ben & Jerry’s stall for a small peaceful reward with your ice cream and hopefully now you’ll find it easier to negotiate the next challenge you face, like the strong women in the Democratic Republic of Congo </p> <ImageContainer> <img src="/images/barcode.png" alt="barcode" /> </ImageContainer> </div> </div> ); } Print.propTypes = { }; export default Print;
examples/03 Nesting/Drag Sources/Container.js
wagonhq/react-dnd
import React from 'react'; import SourceBox from './SourceBox'; import TargetBox from './TargetBox'; import Colors from './Colors'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd/modules/backends/HTML5'; @DragDropContext(HTML5Backend) export default class Container { render() { return ( <div style={{ overflow: 'hidden', clear: 'both', margin: '-.5rem' }}> <div style={{ float: 'left' }}> <SourceBox color={Colors.BLUE}> <SourceBox color={Colors.YELLOW}> <SourceBox color={Colors.YELLOW} /> <SourceBox color={Colors.BLUE} /> </SourceBox> <SourceBox color={Colors.BLUE}> <SourceBox color={Colors.YELLOW} /> </SourceBox> </SourceBox> </div> <div style={{ float: 'left', marginLeft: '5rem', marginTop: '.5rem' }}> <TargetBox /> </div> </div> ); } }
src/ButtonSelection/ButtonSelection.driver.js
nirhart/wix-style-react
import React from 'react'; import ReactDOM from 'react-dom'; import ReactTestUtils from 'react-addons-test-utils'; import $ from 'jquery'; const buttonSelectionDriverFactory = ({element, wrapper, component}) => { const $component = $(element); const getButtonsNames = () => $component.find('span').map((index, b) => $(b).text()).toArray(); const getButtonsClasses = () => $component.find('span').map((index, b) => $(b).attr('class')).toArray(); return { exists: () => !!element, getButtonsNames, getButtonsClasses, getSelectedButton: () => getButtonsNames()[getButtonsClasses().indexOf('selected')], selectByValue: value => { $component.find('span').each((index, b) => { if ($(b).text() === value) { ReactTestUtils.Simulate.click(b); return; } }); }, setProps: props => { const ClonedWithProps = React.cloneElement(component, Object.assign({}, component.props, props), ...(component.props.children || [])); ReactDOM.render(<div ref={r => element = r}>{ClonedWithProps}</div>, wrapper); } }; }; export default buttonSelectionDriverFactory;
docs/app/Examples/collections/Table/Types/TableExampleStriped.js
mohammed88/Semantic-UI-React
import React from 'react' import { Icon, Table } from 'semantic-ui-react' const TableExampleStriped = () => { return ( <Table celled striped> <Table.Header> <Table.Row> <Table.HeaderCell colSpan='3'>Git Repository</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell collapsing> <Icon name='folder' /> node_modules </Table.Cell> <Table.Cell>Initial commit</Table.Cell> <Table.Cell collapsing textAlign='right'>10 hours ago</Table.Cell> </Table.Row> <Table.Row> <Table.Cell> <Icon name='folder' /> test </Table.Cell> <Table.Cell>Initial commit</Table.Cell> <Table.Cell textAlign='right'>10 hours ago</Table.Cell> </Table.Row> <Table.Row> <Table.Cell> <Icon name='folder' /> build </Table.Cell> <Table.Cell>Initial commit</Table.Cell> <Table.Cell textAlign='right'>10 hours ago</Table.Cell> </Table.Row> <Table.Row> <Table.Cell> <Icon name='file outline' /> package.json </Table.Cell> <Table.Cell>Initial commit</Table.Cell> <Table.Cell textAlign='right'>10 hours ago</Table.Cell> </Table.Row> <Table.Row> <Table.Cell> <Icon name='file outline' /> Gruntfile.js </Table.Cell> <Table.Cell>Initial commit</Table.Cell> <Table.Cell textAlign='right'>10 hours ago</Table.Cell> </Table.Row> </Table.Body> </Table> ) } export default TableExampleStriped
src/Slider.js
chris-gooley/react-materialize
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; class Slider extends Component { componentDidMount () { const { fullscreen, indicators, interval, transition } = this.props; $('.slider').slider({ full_width: fullscreen, indicators, interval, transition }); } render () { const { fullscreen, children, className } = this.props; const classes = { fullscreen, slider: true }; return ( <div className={cx(classes, className)}> <ul className='slides'>{children}</ul> </div> ); } } Slider.propTypes = { className: PropTypes.string, children: PropTypes.node, fullscreen: PropTypes.bool, /** * Set to false to hide slide indicators * @default true */ indicators: PropTypes.bool, /** * The interval between transitions in ms * @default 6000 */ interval: PropTypes.number, /** * The duration of the transation animation in ms * @default 500 */ transition: PropTypes.number }; Slider.defaultProps = { fullscreen: false, indicators: true, interval: 6000 }; export default Slider;
src/routes/contact/index.js
tomasreichmann/cards
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Contact from './Contact'; export default { path: '/contact', action() { return <Contact />; }, };
src/icons/SignalCellularNullIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class SignalCellularNullIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M40 13.66V40H13.66L40 13.66M44 4L4 44h40V4z"/></svg>;} };
examples/mobile/src/index.js
BelkaLab/react-yearly-calendar
import React from 'react'; import ReactDOM from 'react-dom'; import moment from 'moment'; import { Calendar, CalendarControls } from 'react-yearly-calendar'; import './style.css'; class Demo extends React.Component { constructor(props) { super(props); const today = moment(); const customCSSclasses = { holidays: ['2018-04-25', '2018-05-01', '2018-06-02', '2018-08-15', '2018-11-01'], spring: { start: '2018-03-21', end: '2018-6-20' }, summer: { start: '2018-06-21', end: '2018-09-22' }, autumn: { start: '2018-09-23', end: '2018-12-21' }, weekend: 'Sat,Sun', winter: day => day.isBefore(moment([2018, 2, 21])) || day.isAfter(moment([2018, 11, 21])) }; // alternatively, customClasses can be a function accepting a moment object. For example: // day => (day.isBefore(moment([day.year(),2,21])) || day.isAfter(moment([day.year(),11,21]))) ? 'winter': 'summer' this.state = { year: today.year(), selectedDay: today, selectedRange: [today, moment(today).add(15, 'day')], showDaysOfWeek: true, showTodayBtn: true, showWeekSeparators: true, selectRange: false, firstDayOfWeek: 0, // sunday customCSSclasses }; } onPrevYear() { this.setState(prevState => ({ year: prevState.year - 1 })); } onNextYear() { this.setState(prevState => ({ year: prevState.year + 1 })); } goToToday() { const today = moment(); this.setState({ selectedDay: today, selectedRange: [today, moment(today).add(15, 'day')], year: today.year() }); } datePicked(date) { this.setState({ selectedDay: date, selectedRange: [date, moment(date).add(15, 'day')] }); } rangePicked(start, end) { this.setState({ selectedRange: [start, end], selectedDay: start }); } toggleShowDaysOfWeek() { this.setState(prevState => ({ showDaysOfWeek: !prevState.showDaysOfWeek })); } toggleForceFullWeeks() { this.setState(prevState => ({ showDaysOfWeek: true, forceFullWeeks: !prevState.forceFullWeeks })); } toggleShowTodayBtn() { this.setState(prevState => ({ showTodayBtn: !prevState.showTodayBtn })); } toggleShowWeekSeparators() { this.setState(prevState => ({ showWeekSeparators: !prevState.showWeekSeparators })); } toggleSelectRange() { this.setState(prevState => ({ selectRange: !prevState.selectRange })); } selectFirstDayOfWeek(event) { this.setState({ firstDayOfWeek: parseInt(event.target.value, 10) }); } render() { const { year, showTodayBtn, selectedDay, showDaysOfWeek, forceFullWeeks, showWeekSeparators, firstDayOfWeek, selectRange, selectedRange, customCSSclasses } = this.state; return ( <div> <div id="calendar"> <CalendarControls year={year} showTodayButton={showTodayBtn} onPrevYear={() => this.onPrevYear()} onNextYear={() => this.onNextYear()} goToToday={() => this.goToToday()} /> <Calendar year={year} selectedDay={selectedDay} showDaysOfWeek={showDaysOfWeek} forceFullWeeks={forceFullWeeks} showWeekSeparators={showWeekSeparators} firstDayOfWeek={firstDayOfWeek} selectRange={selectRange} selectedRange={selectedRange} onPickDate={(date, classes) => this.datePicked(date, classes)} onPickRange={(start, end) => this.rangePicked(start, end)} customClasses={customCSSclasses} /> </div> <h5> Proudly brought to you by <a href="https://belkadigital.com">Belka</a> </h5> <div className="options"> <b>Demo Options</b> <br /> <ul> <li> <label htmlFor="firstDayOfWeek">First day of week</label> <select id="firstDayOfWeek" value={firstDayOfWeek} onChange={e => this.selectFirstDayOfWeek(e)}> {[0, 1, 2, 3, 4, 5, 6].map(i => ( <option key={i} value={i}> {moment() .weekday(i) .format('ddd')} </option> ))} </select> </li> <li> <input id="selectRange" type="checkbox" checked={selectRange} onChange={() => this.toggleSelectRange()} /> <label htmlFor="selectRange">Select Date range</label> </li> </ul> <br /> <i> All these options (and more!) are available as Calendar props. Colors are assigned with an object mapping class names to week days, periods or single days. </i> </div> </div> ); } } ReactDOM.render(<Demo />, document.getElementById('root'));
tests/react_children/text.js
gabelevi/flow
// @flow import React from 'react'; class Text extends React.Component<{children: string}, void> {} class TextOptional extends React.Component<{children?: string}, void> {} class TextLiteral extends React.Component<{children: 'foo' | 'bar'}, void> {} <Text />; // Error: `children` is required. <TextOptional />; // OK: `children` is optional. <TextLiteral />; // Error: `children` is required. <Text>Hello, world!</Text>; // OK: `children` is a single string. <Text></Text>; // Error: `children` does not exist. <Text> </Text>; // OK: `children` is some space. <Text>{}</Text>; // Error: `children` is required. <Text>{/* Hello, world! */}</Text>; // Error: `children` is required. <Text>{undefined}</Text>; // Error: `undefined` is not allowed. <Text>{null}</Text>; // Error: `null` is not allowed. <Text>{true}</Text>; // Error: `boolean`s are not allowed. <Text>{false}</Text>; // Error: `boolean`s are not allowed. <Text>{0}</Text>; // Error: `number`s are not allowed. <Text>{42}</Text>; // Error: `number`s are not allowed. <Text><intrinsic/></Text>; // Error: elements are not allowed. // OK: Text across multiple lines is fine. <Text> Hello, world! Multiline. </Text>; <Text>{'Hello, world!'}</Text>; // OK: Single string in an expression container. <Text>{'Hello, '}{'world!'}</Text>; // Error: We did not allow an array. <Text>Hello, {'world!'}</Text>; // Error: We did not allow an array. <Text>{'Hello, world!'} </Text>; // Error: Spaces cause there to be an array. <Text> {'Hello, world!'}</Text>; // Error: Spaces cause there to be an array. // OK: Newlines are trimmed. <Text> {'Hello, world!'} </Text>; <TextLiteral>foo</TextLiteral>; // OK: Text literal is fine. <TextLiteral>bar</TextLiteral>; // OK: Text literal is fine. <TextLiteral>{'foo'}</TextLiteral>; // OK: Text literal is fine. <TextLiteral>buz</TextLiteral>; // Error: `buz` is not allowed. <TextLiteral>{'buz'}</TextLiteral>; // Error: `buz` is not allowed. <TextLiteral>foo </TextLiteral>; // Error: Spaces are not trimmed. <TextLiteral> foo</TextLiteral>; // Error: Spaces are not trimmed. <TextLiteral>{'foo'} </TextLiteral>; // Error: Spaces are not trimmed. <TextLiteral> {'foo'}</TextLiteral>; // Error: Spaces are not trimmed. // OK: Newlines are trimmed. <TextLiteral> foo </TextLiteral>;
client/src/modules/dashboard/dashboard.view.js
euqen/spreadsheet-core
'use strict'; import React from 'react'; import SideBar from './../../components/sidebar'; import Header from './../../components/header'; import DaySchedule from './../schedule/components/day-schedule.view'; import counterpart from 'counterpart'; import Translate from 'react-translate-component'; import bind from './../../infrastructure/store-connector'; import store from './../../modules/users/users.store'; counterpart.registerTranslations('en', { titleTodaySchedule: "Today Schedule", titleTomorrowSchedule: "Tomorrow Schedule" }); counterpart.registerTranslations('ru', { titleTodaySchedule: "Расписание на сегодня", titleTomorrowSchedule: "Расписание на завтра" }); function getState(props) { return { user: props.user } } @bind(store, getState) export default class Dashboard extends React.Component { render() { return ( <div> <SideBar /> <section className="content"> <Header user={this.props.user} /> <div className="wrapper container-fluid m-t-20"> {this.props.children ? this.props.children : <div> <DaySchedule title=<Translate content="titleTodaySchedule" /> hideAddForm={true} schedule={[]} /> <DaySchedule title=<Translate content="titleTomorrowSchedule" /> hideAddForm={true} schedule={[]} /> </div>} </div> </section> </div> ); } } Dashboard.contextTypes = { user: React.PropTypes.object };
src/client/spinner.js
Ribeiro/hacker-menu
import React from 'react' export default class Spinner extends React.Component { render () { return ( <div className='spinner'> Loading... </div> ) } }
src/lib/utils.js
livedo/react-i18nify
import React from 'react'; export const replace = (translation, replacements) => { if (typeof translation === 'string') { let result = translation; Object.keys(replacements).forEach((replacement) => { result = result.split(`%{${replacement}}`).join(replacements[replacement]); }); return result; } if (React.isValidElement(translation)) { return translation; } if (typeof translation === 'object') { const result = {}; Object.keys(translation).forEach((translationKey) => { result[translationKey] = replace(translation[translationKey], replacements); }); return result; } return null; }; export const fetchTranslation = (translations, key, count = null) => { const _index = key.indexOf('.'); if (typeof translations === 'undefined') { throw new Error('not found'); } if (_index > -1) { return fetchTranslation( translations[key.substring(0, _index)], key.substr(_index + 1), count, ); } if (count !== null) { if (translations[`${key}_${count}`]) { // when key = 'items_3' if count is 3 return translations[`${key}_${count}`]; } if (count !== 1 && translations[`${key}_plural`]) { // when count is not simply singular, return _plural return translations[`${key}_plural`]; } } if (translations[key] != null) { return translations[key]; } throw new Error('not found'); };
app/javascript/mastodon/features/ui/components/column_header.js
blackle/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class ColumnHeader extends React.PureComponent { static propTypes = { icon: PropTypes.string, type: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func, columnHeaderId: PropTypes.string, }; handleClick = () => { this.props.onClick(); } render () { const { icon, type, active, columnHeaderId } = this.props; let iconElement = ''; if (icon) { iconElement = <i className={`fa fa-fw fa-${icon} column-header__icon`} />; } return ( <h1 className={classNames('column-header', { active })} id={columnHeaderId || null}> <button onClick={this.handleClick}> {iconElement} {type} </button> </h1> ); } }
src/views/components/history/index.js
EragonJ/Kaku
import React, { Component } from 'react'; import Player from '../../modules/Player'; import HistoryManager from '../../../modules/HistoryManager'; import TracksComponent from '../shared/tracks'; class HistoryComponent extends Component { constructor(props) { super(props); this.state = { tracks: [] }; this._clickToDeleteAll = this._clickToDeleteAll.bind(this); } componentWillMount() { HistoryManager.ready().then(() => { this.setState({ tracks: HistoryManager.tracks }); }); } componentDidMount() { HistoryManager.on('history-updated', (tracks) => { this.setState({ tracks: tracks }); }); } _clickToDeleteAll() { HistoryManager.clean(); } render() { let tracks = this.state.tracks; let controls = { trackModeButton: true, playAllButton: false, deleteAllButton: true, addToPlayQueueButton: false }; return ( <TracksComponent headerL10nId="history_header" headerIconClass="fa fa-fw fa-history" controls={controls} tracks={tracks} onDeleteAllClick={this._clickToDeleteAll} /> ); } } module.exports = HistoryComponent;
app/demos/ChartWithAxis.js
chunghe/React-Native-Stock-Chart
import React, { Component } from 'react'; import { InteractionManager, ScrollView, StyleSheet } from 'react-native'; import { VictoryAxis, VictoryLine, VictoryChart } from 'victory-chart-native'; import T from '../components/T'; import Loading from '../components/Loading'; import data from '../data'; class ChartWithAxis extends Component { constructor(props) { super(props); this.state = { isReady: false }; } componentDidMount() { InteractionManager.runAfterInteractions(() => { this.setState({ isReady: true }); }); } render() { const { ticks, tradingHours, highestPrice, lowestPrice, previousClose } = data; if (!this.state.isReady) { return <Loading />; } return ( <ScrollView style={styles.container}> <T heading>Line Chart with Axis</T> <T>VictoryChart will calcualte proper scale with axis for you</T> <VictoryChart> <VictoryLine data={ticks} x={(d) => d.time} y={'price'} /> </VictoryChart> <T>add scale: "time" to x-axis, VictoryChart will display proper time format</T> <VictoryChart scale={{ x: 'time' }} > <VictoryLine data={ticks} x={(d) => d.time * 1000} y={'price'} /> </VictoryChart> <T>it turns out this is only partial data, add domain to the x-axis to make the chart only occupy part of the chart</T> <VictoryChart scale={{ x: 'time' }} domain={{ x: tradingHours.map(t => t * 1000) }} > <VictoryLine data={ticks} x={(d) => d.time * 1000} y={'price'} /> </VictoryChart> <T>add some padding at the bottom of the chart</T> <VictoryChart domainPadding={{ y: 20 }} scale={{ x: 'time' }} domain={{ x: tradingHours.map(t => t * 1000) }} > <VictoryLine data={ticks} x={(d) => d.time * 1000} y={'price'} /> </VictoryChart> <T>add grid lines</T> <VictoryChart domainPadding={{ y: 20 }} scale={{ x: 'time' }} domain={{ x: tradingHours.map(t => t * 1000) }} > <VictoryAxis /> <VictoryAxis dependentAxis style={{ grid: { stroke: '#ddd', strokeWidth: 1 }, axis: { stroke: 'transparent' }, ticks: { stroke: 'transparent' } }} /> <VictoryLine data={ticks} x={(d) => d.time * 1000} y={'price'} /> </VictoryChart> <T>add grid line to show previous close price</T> <VictoryChart domainPadding={{ y: 20 }} scale={{ x: 'time' }} domain={{ x: tradingHours.map(t => t * 1000) }} > <VictoryAxis /> <VictoryAxis dependentAxis style={{ grid: { stroke: '#ddd', strokeWidth: 1 }, axis: { stroke: 'transparent' }, ticks: { stroke: 'transparent' } }} /> <VictoryLine data={ticks} x={(d) => new Date(d.time * 1000)} y={'price'} /> <VictoryLine data={[ { x: tradingHours[0] * 1000, y: previousClose }, { x: tradingHours[1] * 1000, y: previousClose } ]} /> </VictoryChart> <T>somehow the domain of y-aix is wrongly calculated, let's calculate it manually</T> <VictoryChart domainPadding={{ y: 20 }} scale={{ x: 'time' }} domain={{ x: tradingHours.map(t => t * 1000), y: [lowestPrice, highestPrice] }} > <VictoryAxis /> <VictoryAxis dependentAxis style={{ grid: { stroke: '#ddd', strokeWidth: 1 }, axis: { stroke: 'transparent' }, ticks: { stroke: 'transparent' } }} /> <VictoryLine data={ticks} x={(d) => new Date(d.time * 1000)} y={'price'} /> <VictoryLine data={[ { x: tradingHours[0] * 1000, y: previousClose }, { x: tradingHours[1] * 1000, y: previousClose } ]} /> </VictoryChart> </ScrollView> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff' }, }); export default ChartWithAxis;
src/svg-icons/action/dashboard.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDashboard = (props) => ( <SvgIcon {...props}> <path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/> </SvgIcon> ); ActionDashboard = pure(ActionDashboard); ActionDashboard.displayName = 'ActionDashboard'; ActionDashboard.muiName = 'SvgIcon'; export default ActionDashboard;
Ch06/06_02/start/bulletin-board/src/App.js
MuhammadHafidzMisrudin/reactjs-basics
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
sc/src/main/javascript/bundles/homepage-species-summary-panel/index.js
gxa/atlas
import React from 'react' import ReactDOM from 'react-dom' import SpeciesSummaryPanel from 'species-summary-panel' import withFetchLoader from 'atlas-react-fetch-loader' const FetchLoadSpeciesSummaryPanel = withFetchLoader(SpeciesSummaryPanel) const render = (options, target) => { ReactDOM.render(<FetchLoadSpeciesSummaryPanel {...options} />, document.getElementById(target)) } export { render }
amp-pwa/src/index.js
pbakaus/amp-publisher-sample
/** @license * Copyright 2015 - present The AMP HTML Authors. All Rights Reserved. * * 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 AMPDocument from './components/amp-document/amp-document'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory } from 'react-router'; import Shell from './components/shell'; import 'bootstrap/dist/css/bootstrap.css'; import './bootstrap-theme.css'; // Replace with your own bootstrap theme! ReactDOM.render(( <Router history={browserHistory}> <Route path='/' component={Shell}> <Route path='content/:document' component={ props => <AMPDocument src={'/content/' + props.params.document} /> } /> </Route> </Router> ), document.getElementById('root'));
examples/with-mobx-state-tree/pages/_app.js
BlancheXu/test
import React from 'react' import { Provider } from 'mobx-react' import { getSnapshot } from 'mobx-state-tree' import App from 'next/app' import { initializeStore } from '../stores/store' export default class MyApp extends App { static async getInitialProps ({ Component, ctx }) { // // Use getInitialProps as a step in the lifecycle when // we can initialize our store // const isServer = typeof window === 'undefined' const store = initializeStore(isServer) // // Check whether the page being rendered by the App has a // static getInitialProps method and if so call it // let pageProps = {} if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) } return { initialState: getSnapshot(store), isServer, pageProps } } constructor (props) { super(props) this.store = initializeStore(props.isServer, props.initialState) } render () { const { Component, pageProps } = this.props return ( <Provider store={this.store}> <Component {...pageProps} /> </Provider> ) } }
src/views/reminders/RemindersList.js
project-abigail/app
import React, { Component } from 'react'; import groupBy from 'lodash/groupBy'; import moment from 'moment'; import ReminderItem from './ReminderItem'; import './RemindersList.css'; class RemindersList extends Component { constructor(props) { super(props); this.state = { reminders: props.reminders, }; this.server = props.server; this.analytics = props.analytics; this.refreshReminders = props.refreshReminders; this.editDialog = props.editDialog; } componentWillReceiveProps(props) { this.setState({ reminders: props.reminders }); this.editDialog = props.editDialog; } onEdit(id) { const reminder = this.state.reminders .find((reminder) => reminder.id === id); this.editDialog.show(reminder); } onDelete(id) { // @todo Nice to have: optimistic update. this.server.reminders.delete(id) .then(() => { this.analytics.event('reminders', 'delete'); const reminders = this.state.reminders .filter((reminder) => reminder.id !== id); this.setState({ reminders }); }) .catch(() => { this.analytics.event('reminders', 'error', 'delete-failed'); console.error(`The reminder ${id} could not be deleted.`); }); } render() { let reminders = this.state.reminders; if (!reminders) { return null; } // Sort all the reminders chronologically. reminders = reminders.sort((a, b) => { return a.due - b.due; }); // Group the reminders by month. reminders = groupBy(reminders, (reminder) => { return moment(reminder.due).format('YYYY/MM'); }); // For each month, group the reminders by day. Object.keys(reminders).forEach((month) => { reminders[month] = groupBy(reminders[month], (reminder) => { return moment(reminder.due).format('YYYY/MM/DD'); }); }); const remindersNode = Object.keys(reminders).map((key) => { const month = moment(key, 'YYYY/MM').format('MMMM'); const reminderMonth = reminders[key]; return ( <div key={key}> <h2 className="reminders__month">{month}</h2> {Object.keys(reminderMonth).map((key) => { const date = moment(key, 'YYYY/MM/DD'); const remindersDay = reminderMonth[key]; return ( <div key={key} className="reminders__day"> <div className="reminders__day-date"> <div className="reminders__day-mday"> {date.format('DD')} </div> <div className="reminders__day-wday"> {date.format('ddd')} </div> </div> <ol className="reminders__list"> {remindersDay.map((reminder) => { return (<ReminderItem key={reminder.id} reminder={reminder} onDelete={this.onDelete.bind(this, reminder.id)} onEdit={this.onEdit.bind(this, reminder.id)} />); })} </ol> </div> ); })} </div> ); }); return ( <div className="RemindersList"> {remindersNode} </div> ); } } RemindersList.propTypes = { server: React.PropTypes.object, analytics: React.PropTypes.object, reminders: React.PropTypes.array, refreshReminders: React.PropTypes.func, editDialog: React.PropTypes.object, }; export default RemindersList;
docs/src/sections/GridPropsSection.js
yyssc/ssc-grid
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; export default function GridSection() { return ( <div className="bs-docs-section"> <h3><Anchor id="grid-props">属性</Anchor></h3> <PropTable component="Grid"/> </div> ); }
app/components/queue/firstDisplay.js
ritishgumber/dashboard-ui
/** * Created by Darkstar on 11/29/2016. */ import React from 'react'; import CreateQueue from './createQueue' class FirstDisplay extends React.Component { constructor(props){ super(props) } render() { return ( <div className="row"> <div className="col-sm-12 col-md-12 col-lg-12 container-cache"> <div className="flex-general-column-wrapper-center first-visitto-cache" style={{}}> <div style={{width: '600px', height: 340, border: '1px solid #C0D0DB', borderRadius: 2, backgroundColor: 'white', padding: 20}}> <div className="cf" style={{height: '25%', width: '100%'}}> <div className="pull-left" style={{width: '60%', height: '100%'}}> <div style={{width: '100%', height: '100%'}} className="flex-general-row-wrapper"> <div style={{width: '23%', height: '100%'}} className="flex-general-column-wrapper-center"> <div className="flex-general-column-wrapper-center" style={{width: '100%', height: '100%', borderRadius: 50, backgroundColor: '#52d9a2'}}> <i className="fa fa-exchange" style={{color: 'white', fontSize: 30}} /> </div> </div> <div style={{width: '59%', height: '100%', marginLeft: 8}} className="solo-vertical-center"> <div className style={{paddingLeft: 5}}> <div> <span style={{fontSize: 18, fontWeight: 600}}>CloudBoost Queue</span> </div> <div> <span style={{fontSize: 14}}>Connect micro services with queue.</span> </div> </div> </div> </div> </div> <div className="pull-right" style={{width: '28%', height: '100%'}}> <div style={{width: '100%', height: '100%'}} className="flex-general-row-wrapper"> <div style={{width: '100%', height: '54%', marginTop: 2}}> <CreateQueue> <button style={{width: '100%', height: '40px', backgroundColor: '#1280E0', color: 'white', fontSize: 14, borderRadius: 4,border:"none"}} className="default-inputfield">Create Queue</button> </CreateQueue> </div> <div style={{width: '100%'}} className="solo-horizontal-center"> <span /> </div> </div> </div> </div> <div style={{height: '68%', width: '100%', marginTop: 20}} className="flex-general-row-wrapper"> <div style={{width: '60%', height: '100%', padding: 20, backgroundColor: '#F7FAFC'}}> <div style={{width: '100%', height: '80%'}} className> <span style={{fontSize: 18, fontWeight: 500}}> Queue helps you to glue different pieces and services of your app and make them work together. Create your first queue today. </span> </div> <div style={{width: '100%', height: '10%', marginTop: 9}} className="flex-general-row-wrapper"> <div> <span style={{marginTop: 1}}> <i className="icon ion-ios-book" style={{color: '#1280E0', fontSize: 16}} /> </span> <span> <a href="https://tutorials.cloudboost.io/en/queues/basicqueues" target="_blank" style={{color: '#1280E0', fontSize: 14,marginLeft:"4px",float:"right"}}>Take the Tutorial</a> </span> </div> <div style={{marginLeft: 10}}> </div> </div> </div> <div style={{width: '39%', height: '100%', backgroundColor: '#F7FAFC'}} className="solo-vertical-center"> <img src="/assets/images/queue-cog.png" style={{marginLeft: 15}} /> </div> </div> </div> </div> </div> </div> ); } } export default FirstDisplay
components/catalog/pie.js
sgmap/inspire
import React from 'react' import PropTypes from 'prop-types' import {translate} from 'react-i18next' import {Pie} from 'react-chartjs-2' const colors = [ '#2185D0', '#00B5AD', '#21BA45', '#FBBD08', '#A333C8', '#e03997', '#F2711C', '#DB2828', '#a5673f', '#DDDDDD', '#000000' ] const formatData = (data, t) => { const labels = Object.keys(data).sort((a, b) => data[a] < data[b]) return { labels: labels.map(label => t(`details.statistics.pie.${label}`, { defaultValue: label })), datasets: [ { data: labels.map(label => data[label]), backgroundColor: colors } ] } } export const PieChart = ({data, t}) => { const formatedData = formatData(data, t) if (formatedData.labels.length === 0) { return ( <div>{t('details.statistics.noData')}</div> ) } return ( <Pie data={formatedData} legend={null} options={{ maintainAspectRatio: false }} /> ) } PieChart.propTypes = { data: PropTypes.object, t: PropTypes.func.isRequired } PieChart.defaultProps = { data: {} } export default translate('catalogs')(PieChart)
app/containers/LanguageProvider/index.js
Third9/mark-one
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
src/components/CQuiz/Answer.js
maloun96/react-admin
import ReactDOM from 'react-dom'; import React from 'react'; import {render} from 'react-dom'; // import axios from 'axios'; // import Form from './Form.js'; // import FinishQuiz from './FinishQuiz.js'; const style = {overflow: 'hidden'}; class Answer extends React.Component { constructor(props) { super(props); this.addAnswer = this.addAnswer.bind(this); this.removeAnswer = this.removeAnswer.bind(this); this.handleInputChange = this.handleInputChange.bind(this); } handleInputChange(e){ let data = { "id" : this.props.answer.id, "name" : this.refs.name.value, "correct": this.refs.correct.checked }; if(this.refs.name.value.length == 0) { $('#answer-' + this.props.answer.id).closest('.form-group').addClass('has-error'); }else{ $('#answer-' + this.props.answer.id).closest('.form-group').removeClass('has-error'); } this.props.updateState(data, this.props.question_id, this.props.answer.id); } addAnswer() { this.props.addAnswer(this.props.question_id); } removeAnswer(){ this.props.removeAnswer(this.props.answer.id, this.props.question_id); } render() { return ( <div className="padding-30"> <div className="form-group" style={style}> <label className="col-sm-2 control-label">Answer #1</label> <div className="col-sm-10"> <div className="input-group"> <input type="text" value={this.props.answer.name} className="form-control" id={"answer-" + this.props.answer.id} ref="name" name="name" onChange={this.handleInputChange} placeholder="Answer #1"/> <span className="input-group-addon"> <input type="checkbox" defaultChecked={this.props.answer.correct} ref="correct" name="correct" onChange={this.handleInputChange}/> </span> <span className="input-group-addon"> <a onClick={this.addAnswer} className="pull-left"><i className="fa fa-plus" aria-hidden="true"></i></a> </span> {(this.props.answer.id != 1) ? <span className="input-group-addon"> <a onClick={this.removeAnswer} className="pull-left"><i className="fa fa-minus" aria-hidden="true"></i></a> </span> : '' } </div> </div> </div> </div> ); } } export default Answer;
classic/src/scenes/mailboxes/src/Scenes/AppScene/ServiceTab/ServiceInfoDrawer/GoogleInboxToGmailHelper.js
wavebox/waveboxapp
import PropTypes from 'prop-types' import React from 'react' import { accountActions, accountStore } from 'stores/account' import { withStyles } from '@material-ui/core/styles' import shallowCompare from 'react-addons-shallow-compare' import ServiceInfoPanelActionButton from 'wbui/ServiceInfoPanelActionButton' import ServiceInfoPanelActions from 'wbui/ServiceInfoPanelActions' import ServiceInfoPanelBody from 'wbui/ServiceInfoPanelBody' import ServiceInfoPanelContent from 'wbui/ServiceInfoPanelContent' import ServiceInfoPanelTitle from 'wbui/ServiceInfoPanelTitle' import Resolver from 'Runtime/Resolver' import blue from '@material-ui/core/colors/blue' import GoogleMailServiceReducer from 'shared/AltStores/Account/ServiceReducers/GoogleMailServiceReducer' import GoogleMailService from 'shared/Models/ACAccounts/Google/GoogleMailService' import { FormControl, InputLabel, Select, MenuItem, Paper } from '@material-ui/core' import WBRPCRenderer from 'shared/WBRPCRenderer' const styles = { headImgContainer: { textAlign: 'center' }, headImg: { width: 128, height: 128, marginTop: 8, marginLeft: 8, marginRight: 8 }, buttonIcon: { marginRight: 6 }, link: { textDecoration: 'underline', cursor: 'pointer', color: blue[600] }, list: { paddingLeft: 20, '>li': { marginBottom: 8 } }, inputPaper: { padding: '8px 16px', marginLeft: -8, marginRight: -8 }, helpSection: { marginTop: 32, fontSize: '85%' } } @withStyles(styles) class GoogleInboxToGmailHelper extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { serviceId: PropTypes.string.isRequired } /* **************************************************************************/ // Component lifecycle /* **************************************************************************/ componentDidMount () { accountStore.listen(this.accountChanged) } componentWillUnmount () { accountStore.unlisten(this.accountChanged) } componentWillReceiveProps (nextProps) { if (this.props.serviceId !== nextProps.serviceId) { const accountState = accountStore.getState() this.setState({ inboxType: (accountState.getService(nextProps.serviceId) || {}).inboxType || GoogleMailService.INBOX_TYPES.GMAIL_DEFAULT }) } } /* **************************************************************************/ // Data lifecycle /* **************************************************************************/ state = (() => { const accountState = accountStore.getState() return { inboxType: (accountState.getService(this.props.serviceId) || {}).inboxType || GoogleMailService.INBOX_TYPES.GMAIL_DEFAULT } })() accountChanged = (accountState) => { this.setState({ inboxType: (accountState.getService(this.props.serviceId) || {}).inboxType || GoogleMailService.INBOX_TYPES.GMAIL_DEFAULT }) } /* **************************************************************************/ // UI Events /* **************************************************************************/ handleOpenInboxTypeKB = (evt) => { WBRPCRenderer.wavebox.openExternal('https://wavebox.io/kb/gmail-inbox-type') } handleChangeInboxType = (evt) => { accountActions.reduceService( this.props.serviceId, GoogleMailServiceReducer.setInboxType, evt.target.value ) } handleDone = (evt) => { accountActions.reduceService( this.props.serviceId, GoogleMailServiceReducer.setHasSeenGoogleInboxToGmailHelper, true ) } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { serviceId, classes, ...passProps } = this.props const { inboxType } = this.state return ( <ServiceInfoPanelContent {...passProps}> <ServiceInfoPanelBody actions={1}> <div className={classes.headImgContainer}> <img className={classes.headImg} src={Resolver.image('google/logo_gmail_512px.png')} /> </div> <ServiceInfoPanelTitle>Welcome to Gmail</ServiceInfoPanelTitle> <p> Welcome to your new Gmail account. We've converted most things automatically for you, there's just one thing you need to setup; the Inbox Type you're using. When Wavebox knows which Inbox Type you're using it will display the correct count of unread messages and the most relevant notifications. </p> <Paper className={classes.inputPaper}> <FormControl fullWidth> <InputLabel>Inbox Type</InputLabel> <Select MenuProps={{ disableEnforceFocus: true, MenuListProps: { dense: true } }} fullWidth value={inboxType} onChange={this.handleChangeInboxType}> <MenuItem value={GoogleMailService.INBOX_TYPES.GMAIL_DEFAULT}> Default (Categories or tabs) </MenuItem> <MenuItem value={GoogleMailService.INBOX_TYPES.GMAIL_IMPORTANT}> Important first </MenuItem> <MenuItem value={GoogleMailService.INBOX_TYPES.GMAIL_UNREAD}> Unread first </MenuItem> <MenuItem value={GoogleMailService.INBOX_TYPES.GMAIL_STARRED}> Starred first </MenuItem> <MenuItem value={GoogleMailService.INBOX_TYPES.GMAIL_PRIORITY}> Priority Inbox </MenuItem> </Select> </FormControl> </Paper> <div className={classes.helpSection}> <h4>Which Inbox Type am I using?</h4> <p> If you're not sure which Inbox Type you're using here's some handy info to help you figure it out. </p> <ul className={classes.list}> <li> <strong>Default (categories & tabs): </strong> Your new emails are automatically sorted into Categories such as <em>Social</em> and <em>Promotions</em>. Typically you will see a number of category tabs above your emails. </li> <li> <strong>Important First: </strong> Emails are automatically given an importance flag and those deemed important will be shown at the top of your inbox. Typically you'll see an <em>Important</em> and <em>Everything else</em> section in your inbox. </li> <li> <strong>Unread First: </strong> Your new emails are sent directly to your Inbox and those that have not been read are placed at the top. Typically you'll see an <em>Unread</em> and <em>Everything else</em> title in your inbox. </li> <li> <strong>Starred First: </strong> Your new emails are sent directly to your Inbox and appear in time order. Those that you've starred will appear at the top. Typically you'll see a <em>Starred</em> and <em>Everything else</em> section in your inbox. </li> <li> <strong>Priority Inbox: </strong> Emails are automatically given an importance flag and those deemed important and unread, or those that have been starred will be shown at the top of your inbox. Typically you'll see an <em>Important and Unread</em>, <em>Starred</em> and <em>Everything else</em> section in your inbox. </li> </ul> <h4>I'm still not sure</h4> <p> Don't worry! You can change the Inbox Type anytime through Wavebox Settings. There's some handy information on <span className={classes.link} onClick={this.handleOpenInboxTypeKB}>how to do this here</span>. </p> </div> </ServiceInfoPanelBody> <ServiceInfoPanelActions actions={1}> <ServiceInfoPanelActionButton color='primary' variant='contained' onClick={this.handleDone}> Done </ServiceInfoPanelActionButton> </ServiceInfoPanelActions> </ServiceInfoPanelContent> ) } } export default GoogleInboxToGmailHelper
src/scripts/components/base.js
jie/microgate
import React from 'react'; import muiTheme from './theme/theme'; export default class BaseReactComponent extends React.Component { getChildContext() { return { muiTheme: muiTheme }; } getCurrentPage() { if (this.props.location.query.page) { return parseInt(this.props.location.query.page) } else { return 1 } } } BaseReactComponent.childContextTypes = { muiTheme: React.PropTypes.object.isRequired, };
app/javascript/mastodon/features/generic_not_found/index.js
amazedkoumei/mastodon
import React from 'react'; import Column from '../ui/components/column'; import MissingIndicator from '../../components/missing_indicator'; const GenericNotFound = () => ( <Column> <MissingIndicator /> </Column> ); export default GenericNotFound;
app/components/staff/inputForm.js
ongmin/batchtracker
import React from 'react' var inputForm = React.createClass({ propTypes: { onPostSubmit: React.PropTypes.func.isRequired, onInputChange: React.PropTypes.func.isRequired, recordStatus: React.PropTypes.array }, getInitialState: function () { return { queryBatchNumber: '', inputValueSKU: '', inputValueBatch: '', inputValueExpiryMonth: '', inputValueExpiryYear: '' } }, handleInputChangeSKU: function (e) { this.setState({inputValueSKU: e.target.value}) this.props.onInputChange() }, handleInputChangeBatch: function (e) { this.setState({inputValueBatch: e.target.value}) this.props.onInputChange() }, handleInputChangeExpiryMonth: function (e) { this.setState({inputValueExpiryMonth: e.target.value}) this.props.onInputChange() }, handleInputChangeExpiryYear: function (e) { this.setState({inputValueExpiryYear: e.target.value}) this.props.onInputChange() }, handlePostSubmit: function (e) { e.preventDefault() var skuNumber = this.state.inputValueSKU var batchNumber = this.state.inputValueBatch var expiryMonth = this.state.inputValueExpiryMonth var expiryYear = this.state.inputValueExpiryYear if (!skuNumber || !batchNumber || !expiryMonth || !expiryYear) { return } this.props.onPostSubmit({ skuNumber: skuNumber, batchNumber: batchNumber, month: expiryMonth, year: expiryYear }) this.setState({inputValueSKU: '', inputValueBatch: '', inputValueExpiryMonth: '', inputValueExpiryYear: ''}) }, render: function () { return ( <div id='container-input-form'> <form onSubmit={this.handlePostSubmit}> <input className='input-form-field' id='input-form-sku' type='text' placeholder='SKU Number' value={this.state.inputValueSKU} onChange={this.handleInputChangeSKU} /> <input className='input-form-field' id='input-form-batch' type='text' placeholder='Batch Number' value={this.state.inputValueBatch} onChange={this.handleInputChangeBatch} /> <input className='input-form-field' id='input-form-expiry-month' type='number' placeholder='Expiry Month (MM)' value={this.state.inputValueExpiryMonth} onChange={this.handleInputChangeExpiryMonth} /> <input className='input-form-field' id='input-form-expiry-year' type='number' placeholder='Expiry Year (YYYY)' value={this.state.inputValueExpiryYear} onChange={this.handleInputChangeExpiryYear} /> <input id='input-form-batch-input-button' type='submit' value='Save' txt='Submit' /> <div>{this.props.recordStatus}</div> </form> </div> ) } }) module.exports = inputForm
src/icons/font/AddCircleIcon.js
skystebnicki/chamel
import React from 'react'; import PropTypes from 'prop-types'; import FontIcon from '../../FontIcon'; import ThemeService from '../../styles/ChamelThemeService'; /** * AddCircle button * * @param props * @param context * @returns {ReactDOM} * @constructor */ const AddCircleIcon = (props, context) => { let theme = context.chamelTheme && context.chamelTheme.fontIcon ? context.chamelTheme.fontIcon : ThemeService.defaultTheme.fontIcon; return ( <FontIcon {...props} className={theme.iconAddCircle}> {'add_circle'} </FontIcon> ); }; /** * An alternate theme may be passed down by a provider */ AddCircleIcon.contextTypes = { chamelTheme: PropTypes.object, }; export default AddCircleIcon;
client/components/Route.js
muiradams/routetogo
import React from 'react'; const Route = (props) => { const { keyStart, route } = props; function isEmpty(object) { return Object.keys(object).length === 0; } if (isEmpty(route)) return null; const { airports } = route; function renderAirports() { return airports.map((airport, index, array) => { if (index < array.length - 1) { return <li className="airport" key={keyStart + airport.iata}>{airport.iata}<i className="fa fa-long-arrow-right" /></li>; } return <li className="airport" key={keyStart + airport.iata}>{airport.iata}</li>; }); } return <td className="airports"><ul className="route">{renderAirports()}</ul></td>; }; Route.defaultProps = { keyStart: '', route: {}, }; Route.propTypes = { keyStart: React.PropTypes.string, route: React.PropTypes.shape({ airline: React.PropTypes.string, airports: React.PropTypes.arrayOf( React.PropTypes.object ), }), }; export default Route;
flareth/app/client/js/EditDApps.js
Firescar96/Flare
import React from 'react'; import {Navbar} from './globals'; import Market from './Market.sol.js'; require('../sass/editDApps.scss'); var EditDApps = React.createClass({ createNewDApp: function(argument) { var ident = $("#ident").val() var fee = $("#fee").val() var hash = $("#hash").val() var classfile = $("#classfile").val() Market.deployed().createDApp.estimateGas(ident, parseInt(fee), hash, classfile).then((gas) => { Market.deployed().createDApp.sendTransaction(ident, parseInt(fee), hash, classfile, { gas: gas*4, }) }) }, render: function() { return ( <div> <Navbar /> <main id="editDApps"> <label> <span>Identifier</span> <input id="ident"/> </label> <label> <span>Price</span> <input id="fee"/> </label> <label> <span>IPFS Hash</span> <input id="hash"/> </label> <label> <span>Main Class</span> <input id="classfile"/> </label> <button id="create" onClick={this.createNewDApp}>Create</button> </main> </div> ) } }) export default EditDApps;
app/index.js
scherler/jenkins-plugin-site
import createAppStore from './createAppStore'; import { Provider } from 'react-redux'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import { render } from 'react-dom'; import Application from './Application'; import App from './App'; import PluginDetail from './components/PluginDetail'; import React from 'react'; const store = createAppStore(); render(( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={Application} /> <Route name="search" path="?query:query&limit=:limit&page=:page&category=:category&latest=:latest" component={Application} /> <Route name="detail" path=":pluginName" component={PluginDetail} /> </Route> </Router> </Provider> ), document.getElementById('grid-box') );
cmd/elwinator/src/components/NewExperiment.js
13scoobie/choices
// @flow import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { experimentAdd } from '../actions'; import { namespaceURL } from '../urls'; const NewExperiment = ({ namespaceName, dispatch }) => { let input; return ( <form onSubmit={e => { e.preventDefault(); if (!input.value.trim()) { return; } dispatch(experimentAdd(namespaceName, input.value)); browserHistory.push(namespaceURL(namespaceName)); }}> <div className="form-group"> <label>Experiment Name</label> <input type="text" className="form-control" placeholder="Enter experiment name" ref={node => { input = node }} /> </div> <button type="submit" className="btn btn-primary">Submit</button> </form> ); }; NewExperiment.propTypes = { namespaceName: React.PropTypes.string.isRequired, dispatch: React.PropTypes.func.isRequired, } const connected = connect()(NewExperiment); export default connected;
src/svg-icons/device/airplanemode-active.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAirplanemodeActive = (props) => ( <SvgIcon {...props}> <path d="M10.18 9"/><path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/> </SvgIcon> ); DeviceAirplanemodeActive = pure(DeviceAirplanemodeActive); DeviceAirplanemodeActive.displayName = 'DeviceAirplanemodeActive'; DeviceAirplanemodeActive.muiName = 'SvgIcon'; export default DeviceAirplanemodeActive;
node_modules/react-sortable/example-from-npm/index.js
Prash88/soccer-lineup
//block 1 import React from 'react'; import { Sortable } from 'react-sortable'; var ListItem = React.createClass({ displayName: 'SortableListItem', render: function () { return ( <div {...this.props} className="list-item">{this.props.children}</div> ) } }) var SortableListItem = Sortable(ListItem); var SortableList = React.createClass({ getInitialState: function () { return { draggingIndex: null, data: this.props.data }; }, updateState: function (obj) { this.setState(obj); }, removeItem: function (idx) { var data = this.state.data; data.items = data.items.splice(idx, 1), this.setState({ data }); }, render: function () { var listItems = this.state.data.items.map(function (item, i) { return ( <SortableListItem key={i} updateState={this.updateState} items={this.state.data.items} draggingIndex={this.state.draggingIndex} sortId={i} outline="list" childProps={{ onClick: this.removeItem.bind(this, i) }} >{item}</SortableListItem> ); }, this); return ( <div className="list">{listItems}</div> ) } }); //block 2 import ReactDOM from 'react-dom'; var data = { items: [ "Gold", "Crimson", "Hotpink", "Blueviolet", "Cornflowerblue" ] }; ReactDOM.render( <SortableList data={data} />, document.body );
src/main/web/app/utilities.js
dhbw-timetable/rablabla
import React from 'react'; import moment from 'moment'; import { createMuiTheme } from 'material-ui/styles'; import yellow from 'material-ui/colors/yellow'; import Slide from 'material-ui/transitions/Slide'; import $ from 'jquery'; // = = = = B A C K E N D = = = = = // for local testing against staging backend const ajaxTarget = window.location.href.indexOf('rablabla.mybluemix.net') !== -1 ? '' : 'https://rablabla-staging.mybluemix.net'; const getParams = (args) => { const params = {}; const pStrings = args.split('&'); Object.keys(pStrings).forEach((param) => { const kvStrings = pStrings[param].split('='); params[kvStrings[0]] = kvStrings[1]; }); return params; }; const getICSLink = (url, success, error) => { const deSuffix = '.de/rapla?'; const baseURL = url.substring(0, url.indexOf(deSuffix) + deSuffix.length); const params = getParams(url.substring(url.indexOf(deSuffix) + deSuffix.length)); if (params.key) { $.ajax({ url: `${ajaxTarget}/Rablabla?url=${url}`, type: 'POST', success, error, }); return 'Accessing calendar file...'; } else if (params.user && params.file) { console.log(baseURL); success(`${baseURL}page=ical&user=${params.user}&file=${params.file}`); } else { console.error(`Yearly calendar not supported for url: ${url}`); } return 'Request denied.'; }; const getAppointments = (url, mmt, success, error, pre) => { pre(mmt); // backend uses monday as first day of the week // we use en locale so we make an exception for sundays $.ajax({ url: `${ajaxTarget}/Rablabla?url=${encodeURIComponent(url)}&day=${mmt.day() > 0 ? mmt.date() : mmt.day(1).date()}&month=${mmt.month() + 1}&year=${mmt.year()}`, type: 'GET', success, error, }); return 'Accessing appointments...'; }; const parseDates = (events) => { events.forEach((el) => { const dateElements = el.date.split('.'); el.Date = moment().date(dateElements[0]).month(dateElements[1] - 1).year(dateElements[2]); }); return events; }; // check if there's a collision between the events a and b const intersects = (a, b) => { const startTimeWrapperA = a.startTime.split(':'); const endTimeWrapperA = a.endTime.split(':'); const startMinA = parseInt(startTimeWrapperA[0]) * 60 + parseInt(startTimeWrapperA[1]); const endMinA = parseInt(endTimeWrapperA[0]) * 60 + parseInt(endTimeWrapperA[1]); const startTimeWrapperB = b.startTime.split(':'); const endTimeWrapperB = b.endTime.split(':'); const startMinB = parseInt(startTimeWrapperB[0]) * 60 + parseInt(startTimeWrapperB[1]); const endMinB = parseInt(endTimeWrapperB[0]) * 60 + parseInt(endTimeWrapperB[1]); return (startMinA <= startMinB && endMinA >= endMinB) // a contains(equals) b || (startMinA >= startMinB && endMinA <= endMinB) // b contains(equals) a || (startMinA < startMinB && endMinA < endMinB && endMinA > startMinB) // a intersects b || (startMinA > startMinB && endMinA > endMinB && startMinA < endMinB) // b intersects a ; }; // checks if the target event intersects any of the dayAgenda (except itself) const intersectsAny = (targetEvent, dayAgenda) => { return dayAgenda.filter(evnt => evnt !== targetEvent && intersects(targetEvent, evnt)).length > 0; }; const makeDays = (events) => { const dailyEvents = [[], [], [], [], [], [], []]; events.forEach((el) => { dailyEvents[el.Date.day()].push(el); }); // for each day in week dailyEvents.forEach((dayAgenda) => { // a stack of columns const stacks = [[]]; // for each event of this day dayAgenda.forEach((evnt) => { let i = 0, finish = false; while (!finish) { // if there'd be an intersection on this stack if (!intersectsAny(evnt, stacks[i])) { stacks[i].push(evnt); finish = true; } else { i++; // open up a new column if (stacks.length === i) { stacks.push([evnt]); finish = true; } } } }); // assign the column values stacks.forEach((colLevel, i) => { colLevel.forEach((el) => { el.col = i; el.maxCol = stacks.length; el.intersections = dayAgenda.filter(evnt => evnt !== el && intersects(el, evnt)).length; }); }); }); console.log(dailyEvents); return dailyEvents; }; // = = = = T H E M E = = = = = const dhbwtimetablepalette = { 50: '#f7e7e7', 100: '#eac3c3', 200: '#dd9c9c', 300: '#cf7474', 400: '#c45656', 500: '#ba3838', 600: '#b33232', 700: '#ab2b2b', 800: '#a32424', 900: '#941717', A100: '#ffc9c9', A200: '#ff9696', A400: '#ff6363', A700: '#ff4a4a', contrastDefaultColor: 'light', }; const slidingTransition = props => <Slide direction="up" {...props} />; const theme = createMuiTheme({ palette: { primary: dhbwtimetablepalette, secondary: { ...dhbwtimetablepalette, A400: 'white', // Accent color }, error: yellow, }, }); module.exports = { getParams, slidingTransition, theme, parseDates, makeDays, getAppointments, getICSLink, ajaxTarget, };
src/components/Profiles/FirstPage.js
RahulDesai92/PHR
/** * Created by Rahuld on 2017/08/26 */ import React, { Component } from 'react'; import { Text, View, StyleSheet, ActivityIndicator, Image, Alert, ScrollView, KeyboardAvoidingView , TouchableOpacity } from 'react-native'; import { NavigationActions } from 'react-navigation'; import customstyles from '../../../assets/styles/customstyles'; import customtext from '../../utils/customtext'; // import LoginForm from './LoginForm'; import colors from '../../utils/colors'; import { TextField } from 'react-native-material-textfield'; //import MaterialIcon from 'react-native-vector-icons/MaterialIcons'; import { RaisedTextButton } from 'react-native-material-buttons'; import Toast from 'react-native-simple-toast'; import ImageSlider from 'react-native-image-slider'; import Drawer from 'react-native-drawer'; /*importing and using from const*/ const { loginscreenLogoContainer, loginscreenLogo, loginTitle } = customstyles; const { login_welcome } = customtext; const { username_label, password_label, login_label, update_profile, built_profile, view_profile, terms_profile, nearby_profile, create_account_text, create_account_link, myfamily_members } = customtext; const { loginscreenInputContainer, loginscreenContainer, loginscreenCreateAccountWrapper, loginscreenCreateAccountText, loginscreenCreateAccountLinkText, homescreenalignmentMyaccount, homescreenalignmentMyappointment, homescreenalignmentNearbyhospital, homescreenLogo, headerStyle, loginscreenLoginContainer } = customstyles; const { white, black, electricBlue } = colors; export default class HomeScreen extends Component { constructor() { super(); this.onFamilyMembers = this.onFamilyMembers.bind(this); this.onUpdateProfile = this.onUpdateProfile.bind(this); this.onViewProfile = this.onViewProfile.bind(this); this.onViewMembers = this.onViewMembers.bind(this); this.onClickHome = this.onClickHome.bind(this); this.onClickExit = this.onClickExit.bind(this); this.onTerms = this.onTerms.bind(this); // this.onNearByhospital = this.onNearByhospital.bind(this); this.state = { position: 1, interval: null }; } componentWillMount() { this.setState({interval: setInterval(() => { this.setState({position: this.state.position === 2 ? 0 : this.state.position + 1}); }, 3000)}); } componentWillUnmount() { clearInterval(this.state.interval); } onFamilyMembers(token){ console.log("familymembers"); console.log('token'+token); this.props.navigation.navigate('FamilyMemberPage',{token:token}); } onClickHome(token){ this.props.navigation.navigate('HomePage',{token:token}); } onClickExit(){ this.props.navigation.navigate('LoginPage'); } onViewMembers(token){ console.log("View Members"); console.log('token'+token); return fetch('http://192.168.0.20:8000/fetchfamilyMembers', { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'x-access-token': token } }).then((response) => response.json()).then((responseJson) => { var message = responseJson.names; var message1 = responseJson.message console.log("message"+JSON.stringify(message)); // var message = message; this.setState({loading_blur: false}); this.setState({showComponent: true}); console.log('message',message); if (message1 === 'profile not built yet' || message1 === 'internal server error' || message1 === 'invalid token' ) { Toast.show(message1); } else { // Toast.show(message); console.log("viewPage"); this.props.navigation.navigate('ViewMemberPage',{token:token,message:message}); } }).catch((error) => { console.error(error); }); } onUpdateProfile(token){ console.log("UpdateprofilePage"); console.log('token'+token); this.props.navigation.navigate('UpdateProfilePage',{token:token}); } onFamilyProfile(token){ console.log("FamilyProfile"); console.log('token'+token); this.props.navigation.navigate('FirstProfilePage',{token:token}); } onViewProfile(token){ console.log('token'+token); console.log("ViewProfilePage"); return fetch('http://192.168.0.20:8000/getProfile', { method: 'GET', headers: { 'Content-Type': 'application/json', 'x-access-token': token } }).then((response) => response.json()).then((responseJson) => { var message = responseJson.names; console.log("message"+message) this.setState({loading_blur: false}); this.setState({showComponent: true}); console.log('message',message); //this.props.navigation.navigate('ViewProfilePage',{token:token,message:message}); }).catch((error) => { console.error(error); }); } onTerms(){ Alert.alert( 'Once Profile is Build it cannot be rebuild.' ) } closeControlPanel = () => { this._drawer.close() }; openControlPanel = () => { this._drawer.open() }; static navigationOptions = { title: 'Family Members', headerStyle: { backgroundColor: 'powderblue' }, headerTitleStyle: { color: 'Black',alignSelf:'center' }, } render() { var {params} = this.props.navigation.state; var token = params.token let { errors = {}, secureTextEntry, ...data } = this.state; let { username = 'username' } = data; return ( <KeyboardAvoidingView behavior="padding" style={loginscreenContainer}> {/* <Image style={homescreenLogo} source={require('../../../assets/images/homeimage.jpg')} /> */} <View style={homescreenLogo}> <ImageSlider images={[ `https://familydoctor.org/wp-content/uploads/2017/01/41429331_l-705x472.jpg`, ]} position={this.state.position} onPositionChanged={position => this.setState({position})}/> </View> <ScrollView> <View style={loginscreenInputContainer}> <View style={homescreenalignmentMyaccount}> <RaisedTextButton title="About" color={electricBlue} titleColor={white} /> </View> <View style={homescreenalignmentMyaccount}> <RaisedTextButton onPress={()=>this.onFamilyMembers(token)} title="Add Members" color={electricBlue} titleColor={white} /> </View> <View style={homescreenalignmentMyappointment}> <RaisedTextButton onPress={()=>this.onViewMembers(token)} title="View Members" color={electricBlue} titleColor={white} /> <View style={homescreenalignmentMyappointment}> <RaisedTextButton onPress={()=>this.onClickHome(token)} title="Go To Home" color={electricBlue} titleColor={white} /> </View> <View style={homescreenalignmentMyappointment}> <RaisedTextButton onPress={()=>this.onClickExit(token)} title="Exit" color={electricBlue} titleColor={white} /> </View> </View> </View> </ScrollView> { /* Due to parent child relation of (this.props.navigation.navigate) page is not navigating from LoginScreen to RegisterScreen */} {/* <LoginForm /> */} </KeyboardAvoidingView> ); } }
shared/modules/app/components/Terms.js
founderlab/fl-base-webapp
import React from 'react' export default () => ( <div> <h2>Website Terms and Conditions</h2> </div> )
src/svg-icons/image/straighten.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageStraighten = (props) => ( <SvgIcon {...props}> <path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H3V8h2v4h2V8h2v4h2V8h2v4h2V8h2v4h2V8h2v8z"/> </SvgIcon> ); ImageStraighten = pure(ImageStraighten); ImageStraighten.displayName = 'ImageStraighten'; ImageStraighten.muiName = 'SvgIcon'; export default ImageStraighten;
docs/src/app/components/pages/components/Card/Page.js
mtsandeep/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import cardReadmeText from './README'; import cardExampleWithAvatarCode from '!raw!./ExampleWithAvatar'; import CardExampleWithAvatar from './ExampleWithAvatar'; import cardExampleExpandableCode from '!raw!./ExampleExpandable'; import CardExampleExpandable from './ExampleExpandable'; import cardExampleControlledCode from '!raw!./ExampleControlled'; import CardExampleControlled from './ExampleControlled'; import cardCode from '!raw!material-ui/Card/Card'; import cardActionsCode from '!raw!material-ui/Card/CardActions'; import cardHeaderCode from '!raw!material-ui/Card/CardHeader'; import cardMediaCode from '!raw!material-ui/Card/CardMedia'; import cardTextCode from '!raw!material-ui/Card/CardText'; import cardTitleCode from '!raw!material-ui/Card/CardTitle'; const descriptions = { avatar: 'A `Card` containing each of the card components: `CardHeader` (with avatar), `CardMedia` (with overlay), ' + '`CardTitle`, `CardText` & `CardActions`.', simple: 'An expandable `Card` with `CardHeader`, `CardText` and `CardActions`. ' + 'Use the icon to expand the card.', controlled: 'A controlled expandable `Card`. Use the icon, the toggle or the ' + 'buttons to control the expanded state of the card.', }; const CardPage = () => ( <div> <Title render={(previousTitle) => `Card - ${previousTitle}`} /> <MarkdownElement text={cardReadmeText} /> <CodeExample title="Card components example" description={descriptions.avatar} code={cardExampleWithAvatarCode} > <CardExampleWithAvatar /> </CodeExample> <CodeExample title="Expandable example" description={descriptions.simple} code={cardExampleExpandableCode} > <CardExampleExpandable /> </CodeExample> <CodeExample title="Controlled example" description={descriptions.controlled} code={cardExampleControlledCode} > <CardExampleControlled /> </CodeExample> <PropTypeDescription code={cardCode} header="### Card properties" /> <PropTypeDescription code={cardActionsCode} header="### CardActions properties" /> <PropTypeDescription code={cardHeaderCode} header="### CardHeader properties" /> <PropTypeDescription code={cardMediaCode} header="### CardMedia properties" /> <PropTypeDescription code={cardTextCode} header="### CardText properties" /> <PropTypeDescription code={cardTitleCode} header="### CardTitle properties" /> </div> ); export default CardPage;
actor-apps/app-web/src/app/components/sidebar/ContactsSectionItem.react.js
yangchenghu/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class ContactsSectionItem extends React.Component { static propTypes = { contact: React.PropTypes.object }; constructor(props) { super(props); } openNewPrivateCoversation = () => { DialogActionCreators.selectDialogPeerUser(this.props.contact.uid); } render() { const contact = this.props.contact; return ( <li className="sidebar__list__item row" onClick={this.openNewPrivateCoversation}> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> </li> ); } } export default ContactsSectionItem;
src/svg-icons/editor/merge-type.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorMergeType = (props) => ( <SvgIcon {...props}> <path d="M17 20.41L18.41 19 15 15.59 13.59 17 17 20.41zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5 7.5 8z"/> </SvgIcon> ); EditorMergeType = pure(EditorMergeType); EditorMergeType.displayName = 'EditorMergeType'; EditorMergeType.muiName = 'SvgIcon'; export default EditorMergeType;
client/modules/District/components/DistrictList/DistrictList.js
lordknight1904/bigvnadmin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Table, Checkbox, Button } from 'react-bootstrap'; import { fetchDistricts, toggleDistrict } from '../../DistrictActions'; import { getDistricts, getCurrentPage, getCityId } from '../../DistrictReducer'; import { getId } from '../../../Login/LoginReducer'; // import { setNotify } from '../../../App/AppActions'; import { getCities } from '../../../City/CityReducer'; import styles from '../../../../main.css'; import dateFormat from 'dateformat'; class DistrictList extends Component { constructor(props) { super(props); } componentDidMount() { if (this.props.cityId && this.props.cityId !== '') { this.props.dispatch(fetchDistricts(this.props.cityId, this.props.currentPage - 1)); } } onToggle = (id) => { const district = { id, }; this.props.dispatch(toggleDistrict(district)).then(() => { if (this.props.cityId && this.props.cityId !== '') { this.props.dispatch(fetchDistricts(this.props.cityId, this.props.currentPage - 1)); } }); }; render() { return ( <Table striped bordered condensed hover className={styles.table}> <thead> <tr> <th style={{ width: '40%' }}>Tên Quận/Huyện</th> <th style={{ width: '20%' }}>Ngày tạo</th> <th style={{ width: '20%' }}>Sửa</th> <th style={{ width: '20%' }} className={styles.tableButtonCol}>Khóa</th> </tr> </thead> <tbody> { this.props.districts.map((district, index) => { return ( <tr key={index}> <td>{district.name}</td> <td>{dateFormat(district.dateCreated, 'dd/mm/yyyy HH:mm')}</td> <td> <Button onClick={() => this.props.onEdit(district)}>Sửa</Button> </td> <td className="text-center"> <Checkbox checked={district.disable} onClick={() => this.onToggle(district._id)} /> </td> </tr> ); }) } </tbody> </Table> ); } } // Retrieve data from store as props function mapStateToProps(state) { return { cities: getCities(state), districts: getDistricts(state), currentPage: getCurrentPage(state), id: getId(state), cityId: getCityId(state), }; } DistrictList.propTypes = { dispatch: PropTypes.func.isRequired, cities: PropTypes.array.isRequired, districts: PropTypes.array.isRequired, currentPage: PropTypes.number.isRequired, id: PropTypes.string.isRequired, cityId: PropTypes.string.isRequired, showDialog: PropTypes.func.isRequired, onEdit: PropTypes.func.isRequired, }; DistrictList.contextTypes = { router: PropTypes.object, }; export default connect(mapStateToProps)(DistrictList);
me_v0.2/src/components/form-types/htmlview.js
EdoMagen/project-s-v2
import React from 'react'; import FormTypes from './form-types'; const HtmlView = ({formField}) => ( <div dangerouslySetInnerHTML={{__html: formField.value}} /> ); // Init FormTypes.addItem('html_view', HtmlView); export default HtmlView;
packages/material-ui-icons/src/InvertColorsOff.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M20.65 20.87l-2.35-2.35-6.3-6.29-3.56-3.57-1.42-1.41L4.27 4.5 3 5.77l2.78 2.78c-2.55 3.14-2.36 7.76.56 10.69C7.9 20.8 9.95 21.58 12 21.58c1.79 0 3.57-.59 5.03-1.78l2.7 2.7L21 21.23l-.35-.36zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59c0-1.32.43-2.57 1.21-3.6L12 14.77v4.82zM12 5.1v4.58l7.25 7.26c1.37-2.96.84-6.57-1.6-9.01L12 2.27l-3.7 3.7 1.41 1.41L12 5.1z" /></g> , 'InvertColorsOff');
examples/huge-apps/components/GlobalNav.js
sleexyz/react-router
import React from 'react'; import { Link } from 'react-router'; const styles = {}; class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } }; constructor (props, context) { super(props, context); this.logOut = this.logOut.bind(this); } logOut () { alert('log out'); } render () { var { user } = this.props; return ( <div style={styles.wrapper}> <div style={{float: 'left'}}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link}>Calendar</Link>{' '} <Link to="/grades" style={styles.link}>Grades</Link>{' '} <Link to="/messages" style={styles.link}>Messages</Link>{' '} </div> <div style={{float: 'right'}}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ); } } styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: 'hsl(200, 20%, 20%)', color: '#fff' }; styles.link = { padding: 10, color: '#fff', fontWeight: 200 } export default GlobalNav;
js/components/loaders/Spinner.android.js
tausifmuzaffar/bisApp
import React, { Component } from 'react'; import ProgressBar from 'ProgressBarAndroid'; export default class SpinnerNB extends Component { prepareRootProps() { const type = { height: 40, }; const defaultProps = { style: type, }; return computeProps(this.props, defaultProps); } render() { const getColor = () => { if (this.props.color) { return this.props.color; } else if (this.props.inverse) { return this.getTheme().inverseSpinnerColor; } return this.getTheme().defaultSpinnerColor; }; return ( <ProgressBar {...this.prepareRootProps()} styleAttr={this.props.size ? this.props.size : 'Large'} color={getColor()} /> ); } }
views/status_line.js
stefohnee/black-screen
import React from 'react'; export default React.createClass({ render() { return ( <div className="status-line"> <CurrentDirectory currentWorkingDirectory={this.props.currentWorkingDirectory}/> <VcsData data={this.props.vcsData}/> </div> ) } }); const CurrentDirectory = React.createClass({ render() { return ( <div className="current-directory">{this.props.currentWorkingDirectory}</div> ) } }); const VcsData = React.createClass({ render() { if (!this.props.data.isRepository) { return null; } return ( <div className="vcs-data"> <div className={`status ${this.props.data.status}`}>{this.props.data.branch}</div> </div> ) } });
client-src/components/pages/InspectionDetails.js
Neil-G/InspectionLog
import React, { Component } from 'react'; import { Link } from 'react-router' require('./../../../public/custom.css') import Parts from './../parts' import Containers from './../../containers' import Forms from './../forms' var axios = require('axios') class InspectionDetails extends Component { constructor(){ super() this.state = { inspection: undefined, edit: false } this.toggleEdit = this.toggleEdit.bind(this) this.updateInspection = this.updateInspection.bind(this) } componentWillMount(){ console.log(this.props.routeParams.id) axios.get('/api/inspections/' + this.props.routeParams.id) .then( (res) => { console.log(res.data) this.setState({ inspection: res.data }) }) .then( (err) => { console.log(err) }) } toggleEdit(){ console.log('toggle') this.setState({ edit: !this.state.edit }) } updateInspection(inspection){ this.setState({ inspection }) } render() { const { inspection, edit } = this.state console.log('edit: ',edit) return ( <div> <p className='center-text'><Link to='/inspections'> Search Inspections </Link></p> { (inspection == undefined) && "LOADING..." } { inspection && !edit && <Parts.InspectionDetails inspection={inspection} toggleEdit={this.toggleEdit} /> } { inspection && edit && <Forms.EditForm inspection={inspection} toggleEdit={this.toggleEdit} updateInspection={this.updateInspection}/> } </div> ); } } export default InspectionDetails
src/App.js
wlto/shopping-cart
import React, { Component } from 'react'; import { Route, Switch } from 'react-router-dom' import Home from './Home.js' import Checkout from './Checkout.js' class App extends Component { constructor(props) { super(props); this.state = { inventoryItems: props.data, cartItems: [], totalPrice: 0 }; } handleUpdateInventoryItem(itemIndex, itemStock, itemQty, removeFromCart) { const itemList = this.state.inventoryItems.slice(0); const currentInventoryStock = itemList[itemIndex].stock; const newStock = removeFromCart ? currentInventoryStock + itemQty : currentInventoryStock - itemQty; itemList[itemIndex].stock = newStock; this.setState({ inventoryItems: itemList }); } handleUpdateCartItems(itemIndexInInventory, itemCode, itemName, itemPrice, itemQty) { const currentCartItems = this.state.cartItems.slice(0); let itemExist = false; let newItem; let currentCartTotal = this.state.totalPrice; // Check if item already exists for (let i = 0; i < currentCartItems.length && itemExist === false; i++) { // If item exists, update the quantity and price if (currentCartItems[i].code === itemCode) { currentCartItems[i].quantity += itemQty; currentCartItems[i].totalPrice += parseFloat(itemPrice * itemQty); currentCartTotal += parseFloat(itemPrice * itemQty); this.setState({ cartItems: currentCartItems, totalPrice: currentCartTotal }); itemExist = true; } } // If item does not exist, add it to the cart as a new item if (itemExist !== true) { newItem = { indexInInventory: itemIndexInInventory, code: itemCode, name: itemName, quantity: itemQty, totalPrice: parseFloat(itemPrice * itemQty) } currentCartTotal = this.state.totalPrice + newItem.totalPrice; this.setState((prevState, props) => ({ cartItems:[...prevState.cartItems,newItem], totalPrice: currentCartTotal })); } } handleRemoveFromCart(item) { let currentInventoryItems = this.state.inventoryItems.slice(0); let currentCartItems = this.state.cartItems.slice(0); let currentCartTotal = this.state.totalPrice; let inventoryItemIndex; let itemFound = false; for (let i = 0; i < currentCartItems.length && itemFound === false; i++) { if (currentCartItems[i].code === item.code) { // Restore stock level in inventory inventoryItemIndex = currentCartItems[i].indexInInventory; this.handleUpdateInventoryItem( inventoryItemIndex, currentInventoryItems[inventoryItemIndex].stock, currentCartItems[i].quantity, true ); currentCartTotal -= currentCartItems[i].totalPrice; // Decreases the total price in cart currentCartItems.splice(i, 1); // Remove the item from cart this.setState({ cartItems: currentCartItems, totalPrice: currentCartTotal }); itemFound = true; } } } render() { return ( <Switch> <Route exact path='/' render={() => ( <Home onUpdateInventoryItem={this.handleUpdateInventoryItem.bind(this)} onUpdateCartItems={this.handleUpdateCartItems.bind(this)} onRemoveFromCart={this.handleRemoveFromCart.bind(this)} inventoryItems={this.state.inventoryItems} cartItems={this.state.cartItems} totalPrice={this.state.totalPrice} /> )} /> <Route exact path='/checkout' render={() => ( <Checkout cartItems={this.state.cartItems} totalPrice={this.state.totalPrice} /> )} /> </Switch> ); } } export default App;
app/react-icons/fa/flask.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaFlask extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m35.6 32.3q1.2 2 0.5 3.4t-3.2 1.4h-25.7q-2.4 0-3.1-1.4t0.5-3.4l11.2-17.7v-8.9h-1.4q-0.6 0-1-0.4t-0.5-1 0.5-1 1-0.4h11.4q0.6 0 1 0.4t0.4 1-0.4 1-1 0.4h-1.4v8.9z m-17.4-16.2l-6.1 9.6h15.9l-6.1-9.6-0.4-0.7v-9.7h-2.9v9.7z"/></g> </IconBase> ); } }
docs/src/editors/BsEditor/BsEditor.js
gocreating/redux-draft
import request from 'superagent'; import React, { Component } from 'react'; import { Editor, RichUtils } from 'draft-js'; import Col from 'react-bootstrap/lib/Col'; import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar'; import ButtonGroup from 'react-bootstrap/lib/ButtonGroup'; import { reduxDraft } from '../../../../lib'; import ControlButton from './ControlButton'; import draftConfig from './config'; import configs from '../../../configs'; import 'draft-js/dist/Draft.css'; import './BsEditor.css'; class BsEditor extends Component { state = { isFileUploading: false, } handleKeyCommand = (command, editorState) => { let newState = RichUtils.handleKeyCommand(editorState, command); if (newState) { this.props.updateEditorState(newState); return true; } return false; } applyBlock = (blockName) => (e) => { this.props.focus(); this.props.applyBlock(blockName); } toggleBlock = (blockName) => (e) => { this.props.focus(); this.props.toggleBlock(blockName); } toggleStyle = (styleName) => (e) => { this.props.focus(); this.props.toggleStyle(styleName); } handleLinkClick = (e) => { let { editorState, activeMap, focus, insertEntity, applyEntity, removeEntity, } = this.props; let selectionState = editorState.getSelection(); let isCollapsed = selectionState.isCollapsed(); if (!activeMap.LINK) { let url = prompt('url'); focus(); if (!url) { return; } if (isCollapsed) { insertEntity('LINK', 'MUTABLE', { url }, url); } else { applyEntity('LINK', 'MUTABLE', { url }); } } else { if (isCollapsed) { focus(); alert('Please select a range'); } else { focus(); removeEntity(); } } } handleBlockImageClick = (e) => { let { focus, insertAtomicBlock } = this.props; let src = prompt('src'); focus(); if (src) { insertAtomicBlock('IMAGE', 'IMMUTABLE', { src }); } } handleTeXClick = (e) => { let { focus, insertAtomicBlock } = this.props; focus(); insertAtomicBlock('TEX', 'IMMUTABLE', { math: 'P(E) = {n \\choose k} p^k (1-p)^{ n-k} ', }); } handleCodeHighlightClick = (e) => { let { focus, insertAtomicBlock } = this.props; focus(); insertAtomicBlock('CODE_HIGHLIGHT', 'IMMUTABLE', { language: 'javascript', lineNumbers: false, lineHighlight: '', value: 'console.log(\'Hello world!\');', }); } handleFileChange = (e) => { let { updateReadOnly, focus, insertAtomicBlock } = this.props; let file = this.fileInput.files[0]; let form = new FormData(); if (!file) { return; } updateReadOnly(true); this.setState({ isFileUploading: true }); form.append('image', file); request .post('https://api.imgur.com/3/image') .send(form) .set('authorization', `Client-ID ${configs.imgur.clientID}`) .end((err, res) => { updateReadOnly(false); this.setState({ isFileUploading: false }); this.fileInput.value = ''; if (err) { throw err; } let { link } = res.body.data; focus(); insertAtomicBlock('IMAGE', 'IMMUTABLE', { src: link }); }); } render() { let { setRef, editorState, updateEditorState, blockRenderMap, blockRendererFn, customStyleMap, readOnly, activeMap, } = this.props; let { isFileUploading } = this.state; let selectionState = editorState.getSelection(); let isCollapsed = selectionState.isCollapsed(); return ( <div className="bs-editor"> <ButtonToolbar> <Col md={2}> <select className="form-control" onChange={(e) => { this.applyBlock(e.target.value)(e); }} > <option value="unstyled" selected={activeMap['unstyled']} > Normal Text </option> <option value="header-one" selected={activeMap['header-one']} > H1 </option> <option value="header-two" selected={activeMap['header-two']} > H2 </option> <option value="header-three" selected={activeMap['header-three']} > H3 </option> <option value="header-four" selected={activeMap['header-four']} > H4 </option> <option value="header-five" selected={activeMap['header-five']} > H5 </option> <option value="header-six" selected={activeMap['header-six']} > H6 </option> </select> </Col> <ButtonGroup> <ControlButton label={<i className="fa fa-quote-left" aria-hidden="true" />} active={activeMap.blockquote} onClick={this.toggleBlock('blockquote')} /> <ControlButton label={<i className="fa fa-code" aria-hidden="true" />} active={activeMap['code-block']} onClick={this.toggleBlock('code-block')} /> <ControlButton label={<i className="fa fa-list" aria-hidden="true" />} active={activeMap['unordered-list-item']} onClick={this.toggleBlock('unordered-list-item')} /> <ControlButton label={<i className="fa fa-list-ol" aria-hidden="true" />} active={activeMap['ordered-list-item']} onClick={this.toggleBlock('ordered-list-item')} /> </ButtonGroup> <ButtonGroup> <ControlButton label={<i className="fa fa-bold" aria-hidden="true" />} active={activeMap.BOLD} onClick={this.toggleStyle('BOLD')} /> <ControlButton label={<i className="fa fa-italic" aria-hidden="true" />} active={activeMap.ITALIC} onClick={this.toggleStyle('ITALIC')} /> <ControlButton label={<i className="fa fa-underline" aria-hidden="true" />} active={activeMap.UNDERLINE} onClick={this.toggleStyle('UNDERLINE')} /> <ControlButton label={<i className="fa fa-strikethrough" aria-hidden="true" />} active={activeMap.STRIKETHROUGH} onClick={this.toggleStyle('STRIKETHROUGH')} /> <ControlButton label={<i className="fa fa-code" aria-hidden="true" />} active={activeMap.CODE} onClick={this.toggleStyle('CODE')} /> </ButtonGroup> <ButtonGroup> <ControlButton label={activeMap.LINK && !isCollapsed ? <i className="fa fa-unlink" aria-hidden="true" /> : <i className="fa fa-link" aria-hidden="true" />} disabled={activeMap.LINK && isCollapsed} active={activeMap.LINK} onClick={this.handleLinkClick} /> <ControlButton label={<i className="fa fa-picture-o" aria-hidden="true" />} onClick={this.handleBlockImageClick} /> <ControlButton label={ isFileUploading ? <i className="fa fa-spinner fa-spin" aria-hidden="true" /> : <i className="fa fa-upload" aria-hidden="true" /> } disabled={isFileUploading} onClick={() => this.fileInput.click()} /> <ControlButton label={<i className="fa fa-calculator" aria-hidden="true" />} onClick={this.handleTeXClick} /> <ControlButton label={<i className="fa fa-file-code-o" aria-hidden="true" />} onClick={this.handleCodeHighlightClick} /> </ButtonGroup> </ButtonToolbar> <input style={{ display: 'none' }} ref={ref => { this.fileInput = ref; }} onChange={this.handleFileChange} type="file" /> <div className="editor"> <Editor ref={setRef} editorState={editorState} onChange={updateEditorState} handleKeyCommand={this.handleKeyCommand} blockRenderMap={blockRenderMap} blockRendererFn={blockRendererFn} customStyleMap={customStyleMap} readOnly={readOnly} placeholder="write something..." /> </div> </div> ); } } export default reduxDraft(draftConfig)(BsEditor);
ui/src/components/App.js
Ion-Petcu/StockTrainer
import React from 'react'; import AuthService from '../utils/AuthService' import Main from '../views/Main' import Login from '../views/Login' class App extends React.Component { constructor(props) { super(props); this.state = { 'view': AuthService.loggedIn() ? 'main' : 'landing' }; AuthService.on('profile_updated', () => this.setState({'view': 'main'})); } render () { return this.state.view == 'main' ? <Main /> : <Login />; } } export default App;
frontend/src/views/Status/Status.js
rocknsm/docket
/* * Copyright (c) 2017, 2018 RockNSM. * * This file is part of RockNSM * (see http://rocknsm.io). * * 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, { Component } from 'react'; import {Link} from 'react-router-dom'; import {Card, CardHeader, CardBody, Table} from 'reactstrap'; class Status extends Component { constructor(props) { super(props); this.state = { queryId: props.match.params.queryId, entries: [], status: {state:'Loading...'}, url: null, }; this.updateTable = this.updateTable.bind(this); } updateTable() { var Config = require('Config'); var statusApi = fetch( Config.serverUrl + '/status/' + this.state.queryId ) .then(results => { return results.json(); }) var urlsApi = fetch( Config.serverUrl + '/urls/' + this.state.queryId ) .then(results => { return results.json(); }) Promise.all([statusApi, urlsApi]).then( values => { console.log("Values", values); var status = values[0][this.state.queryId]; var urls = values[1]; status['events'].sort(function(a,b) { return (a.datetime > b.datetime) }); let url = null; if (this.state.queryId in urls) url = urls[this.state.queryId]; let totalSize = 0; if ( status['state'] === 'Completed' ) { status['successes'].forEach( (element) => { totalSize += isNaN(element['value']) ? 0 : element['value']; } ) } console.log("totalSize", totalSize); this.setState({'status': status, 'url': url, 'resultSize': totalSize}); let entries = Object.entries(status['events']).map((entry, index) => { console.log("Entry", entry); return ( <tr key={ index }> <th scope="row">{ index + 1 }</th> <td>{ entry[1].datetime }</td> <td>{ entry[1].name }</td> <td>{ entry[1].msg }</td> <td>{ entry[1].state }</td> </tr> ); }) this.setState({'entries': entries}); if ( status['state'] === 'Completed' || status['state'] === 'Failed' ) clearInterval(this.interval); }) } componentDidMount() { this.interval = setInterval(this.updateTable, 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <div className="animated fadeIn"> <Card> <CardHeader><h2>Status for {this.state.queryId}</h2></CardHeader> <CardBody> <h3>Overview</h3> <dl> <dt>Overall State</dt> <dd>{this.state.status.state}</dd> <dt>Download Result</dt> <dd>{ (this.state.url !== null) ? <div><a href={this.state.url}>Get PCAP</a> <p>({ this.state.resultSize } bytes)</p></div> : <div>Unavailable</div> }</dd> </dl> <h3>Details</h3> <Table striped> <thead><tr> <th>#</th> <th>Event Time</th> <th>Name</th> <th>Message</th> <th>State</th> </tr></thead> <tbody> { this.state.entries } </tbody> </Table> </CardBody> </Card> </div> ) } } export default Status;
src/App.js
kad3nce/react-transform-boilerplate
import React, { Component } from 'react'; import { NICE, SUPER_NICE } from './colors'; class Counter extends Component { constructor(props) { super(props); this.state = { counter: 0 }; this.interval = setInterval(() => this.tick(), 1000); } tick() { this.setState({ counter: this.state.counter + this.props.increment }); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <h1 style={{ color: this.props.color }}> Counter ({this.props.increment}): {this.state.counter} </h1> ); } } export class App extends Component { render() { return ( <div> <Counter increment={1} color={NICE} /> <Counter increment={5} color={SUPER_NICE} /> </div> ); } }
app/app.js
MichelHalmes/sankey
import React from 'react'; import ReactDOM from 'react-dom'; import request from 'superagent'; import {loadData, parseLevelData} from './utils.js' import SankeyChart from './SankeyChart'; import Slider from '../d3_drag_drop/slider'; import bootstrap from 'bootstrap/dist/css/bootstrap.css'; import style from './sankey.css'; class App extends React.Component { constructor() { super() this.DATA_FILE = '../data/redshiftData.json'; this.state = { nodes: [], links: [] }; this.setSplitLevel1 = this.setSplitLevel1.bind(this); } componentDidMount() { request .get(this.DATA_FILE) .end((err, res) => { if (err) { console.log('Data import error!', err); } this.NODES = res.body.nodes; this.LINKS = res.body.links; var {nodes, links} = parseLevelData(this.NODES, this.LINKS, null); this.setState({nodes, links}); }) } setSplitLevel1(element) { if (element.is_split) { var next_split_level_1 = null; } else { var next_split_level_1 = element.name; } var {nodes, links} = parseLevelData(this.NODES, this.LINKS, next_split_level_1); this.setState({nodes, links}); } render() { return ( <div> <SankeyChart nodes={this.state.nodes} links={this.state.links} onNodeClick={this.setSplitLevel1} /> </div> ); } }; // <Slider width={20} height={10} value={2} /> ReactDOM.render(<App />, document.getElementById('app'));
src/client.js
chunkiat82/rarebeauty-ui
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'whatwg-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import deepForceUpdate from 'react-deep-force-update'; import queryString from 'query-string'; import { createPath } from 'history/PathUtils'; import App from './components/App'; import createFetch from './createFetch'; import configureStore from './store/configureStore'; import history from './history'; import { updateMeta } from './DOMUtils'; import router from './router'; /* eslint-disable global-require */ // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle const removeCss = styles.map(x => x._insertCss()); return () => { removeCss.forEach(f => f()); }; }, // Universal HTTP client fetch: createFetch(self.fetch, { baseUrl: window.App.apiUrl, }), store: configureStore(window.App.state, { history }), storeSubscription: null, }; // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration const scrollPositionsHistory = {}; if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } let onRenderComplete = function initialRenderComplete() { const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); onRenderComplete = function renderComplete(route, location) { document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }; }; const container = document.getElementById('app'); let appInstance; let currentLocation = history.location; // Re-render the app when window.location changes async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; try { // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await router.resolve({ ...context, path: location.pathname, query: queryString.parse(location.search), }); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } appInstance = ReactDOM.render( <App context={context}>{route.component}</App>, container, () => onRenderComplete(route, location), ); } catch (error) { if (__DEV__) { throw error; } console.error(error); // Do a full page reload if error occurs during client-side navigation if (action && currentLocation.key === location.key) { window.location.reload(); } } } // Handle client-side navigation by using HTML5 History API // For more information visit https://github.com/mjackson/history#readme history.listen(onLocationChange); onLocationChange(currentLocation); // Enable Hot Module Replacement (HMR) if (module.hot) { module.hot.accept('./router', () => { if (appInstance) { // Force-update the whole tree, including components that refuse to update deepForceUpdate(appInstance); } onLocationChange(currentLocation); }); }
pages/tutorials/index.js
pcm-ca/pcm-ca.github.io
import React from 'react' import { Link } from 'react-router' import Helmet from 'react-helmet' import { config } from 'config' import get from 'lodash/get' import _ from 'lodash' import Tutorial from '../../components/Tutorial' import { prefixLink } from 'gatsby-helpers' export default class Index extends React.Component { render() { const sortedPages = _.orderBy(this.props.route.pages, 'data.date', "desc") // Posts are those with md extension that are not 404 pages OR have a date (meaning they're a react component post). const visibleTutorials = sortedPages.filter(page => ( ( get(page, 'file.ext') === 'md' && !_.includes(page.path, '/404') || get(page, 'data.date') ) && (_.includes(get(page, 'file.dir'), 'tutorials') && !_.includes(get(page, 'file.dir'), 'vegas')) )) return ( <div> <Helmet title={config.siteTitle + ' | resources'} /> <h1> Tutorials </h1> <ul className="ulTutorials"> {_.map(visibleTutorials, tutorial => ( <li key={tutorial.data.title + tutorial.data.date}> <Tutorial {...tutorial} /> </li> ))} </ul> </div> ) } }
website/src/templates/mdx-renderer.js
spacy-io/spaCy
/** * Temporary hack to prevent this issue: * https://github.com/ChristopherBiscardi/gatsby-mdx/issues/244 */ import React from 'react' import { MDXTag } from '@mdx-js/tag' import { withMDXComponents } from '@mdx-js/tag/dist/mdx-provider' import { withMDXScope } from 'gatsby-mdx/context' const WrappedComponent = React.memo(({ scope = {}, components = {}, children, ...props }) => { if (!children) return null const fullScope = { React, MDXTag, ...scope } const keys = Object.keys(fullScope) const values = keys.map(key => fullScope[key]) const fn = new Function('_fn', ...keys, `${children}`) // eslint-disable-line no-new-func const End = fn({}, ...values) return React.createElement(End, { components, ...props }) }) export default withMDXScope(withMDXComponents(WrappedComponent))
node-life/build/build/react-native-life/ReactNativeLife/js/Components/ViewPagerAndroid/ViewPagerAndroid.js
CaMnter/front-end-life
/** * @author CaMnter */ import React from 'react'; import { Image, StyleSheet, Text, TouchableWithoutFeedback, TouchableOpacity, View, ViewPagerAndroid } from 'react-native'; import type {ViewPagerScrollState} from 'ViewPagerAndroid'; let PAGES = 5; let BGCOLOR = ['#fdc08e', '#fff6b9', '#99d1b7', '#dde5fe', '#f79273']; let IMAGE_URIS = [ 'https://apod.nasa.gov/apod/image/1410/20141008tleBaldridge001h990.jpg', 'https://apod.nasa.gov/apod/image/1409/volcanicpillar_vetter_960.jpg', 'https://apod.nasa.gov/apod/image/1409/m27_snyder_960.jpg', 'https://apod.nasa.gov/apod/image/1409/PupAmulti_rot0.jpg', 'https://apod.nasa.gov/apod/image/1510/lunareclipse_27Sep_beletskycrop4.jpg', ]; class LikeCount extends React.Component { state = { likes: 7, }; onClick = () => { this.setState({likes: this.state.likes + 1}); }; render() { let thumbsUp = '\uD83D\uDC4D'; return ( <View style={styles.likeContainer}> <TouchableOpacity onPress={this.onClick} style={styles.likeButton}> <Text style={styles.likesText}> {thumbsUp + ' Like'} </Text> </TouchableOpacity> <Text style={styles.likesText}> {this.state.likes + ' likes'} </Text> </View> ); } } class Button extends React.Component { _handlePress = () => { if (this.props.enabled && this.props.onPress) { this.props.onPress(); } }; render() { return ( <TouchableWithoutFeedback onPress={this._handlePress}> <View style={[styles.button, this.props.enabled ? {} : styles.buttonDisabled]}> <Text style={styles.buttonText}>{this.props.text}</Text> </View> </TouchableWithoutFeedback> ); } } class ProgressBar extends React.Component { render() { let fractionalPosition = (this.props.progress.position + this.props.progress.offset); let progressBarSize = (fractionalPosition / (PAGES - 1)) * this.props.size; return ( <View style={[styles.progressBarContainer, {width: this.props.size}]}> <View style={[styles.progressBar, {width: progressBarSize}]}/> </View> ); } } class ViewPagerAndroidExample extends React.Component { static title = '<ViewPagerAndroid>'; static description = 'Container that allows to flip left and right between child views.'; state = { page: 0, animationsAreEnabled: true, scrollEnabled: true, progress: { position: 0, offset: 0, }, }; onPageSelected = (e) => { this.setState({page: e.nativeEvent.position}); }; onPageScroll = (e) => { this.setState({progress: e.nativeEvent}); }; onPageScrollStateChanged = (state: ViewPagerScrollState) => { this.setState({scrollState: state}); }; move = (delta) => { let page = this.state.page + delta; this.go(page); }; go = (page) => { if (this.state.animationsAreEnabled) { this.viewPager.setPage(page); } else { this.viewPager.setPageWithoutAnimation(page); } this.setState({page}); }; render() { let pages = []; for (let i = 0; i < PAGES; i++) { let pageStyle = { backgroundColor: BGCOLOR[i % BGCOLOR.length], alignItems: 'center', padding: 20, }; pages.push( <View key={i} style={pageStyle} collapsable={false}> <Image style={styles.image} source={{uri: IMAGE_URIS[i % BGCOLOR.length]}} /> <LikeCount /> </View> ); } let {page, animationsAreEnabled} = this.state; return ( <View style={styles.container}> <ViewPagerAndroid style={styles.viewPager} initialPage={0} scrollEnabled={this.state.scrollEnabled} onPageScroll={this.onPageScroll} onPageSelected={this.onPageSelected} onPageScrollStateChanged={this.onPageScrollStateChanged} pageMargin={10} ref={viewPager => { this.viewPager = viewPager; }}> {pages} </ViewPagerAndroid> <View style={styles.buttons}> <Button enabled={true} text={this.state.scrollEnabled ? 'Scroll Enabled' : 'Scroll Disabled'} onPress={() => this.setState({scrollEnabled: !this.state.scrollEnabled})} /> </View> <View style={styles.buttons}> { animationsAreEnabled ? <Button text="Turn off animations" enabled={true} onPress={() => this.setState({animationsAreEnabled: false})} /> : <Button text="Turn animations back on" enabled={true} onPress={() => this.setState({animationsAreEnabled: true})} /> } <Text style={styles.scrollStateText}>ScrollState[ {this.state.scrollState} ]</Text> </View> <View style={styles.buttons}> <Button text="Start" enabled={page > 0} onPress={() => this.go(0)}/> <Button text="Prev" enabled={page > 0} onPress={() => this.move(-1)}/> <Text style={styles.buttonText}>Page {page + 1} / {PAGES}</Text> <ProgressBar size={100} progress={this.state.progress}/> <Button text="Next" enabled={page < PAGES - 1} onPress={() => this.move(1)}/> <Button text="Last" enabled={page < PAGES - 1} onPress={() => this.go(PAGES - 1)}/> </View> </View> ); } } const styles = StyleSheet.create({ buttons: { flexDirection: 'row', height: 30, backgroundColor: 'black', alignItems: 'center', justifyContent: 'space-between', }, button: { flex: 1, width: 0, margin: 5, borderColor: 'gray', borderWidth: 1, backgroundColor: 'gray', }, buttonDisabled: { backgroundColor: 'black', opacity: 0.5, }, buttonText: { color: 'white', }, scrollStateText: { color: '#99d1b7', }, container: { flex: 1, backgroundColor: 'white', }, image: { width: 300, height: 200, padding: 20, }, likeButton: { backgroundColor: 'rgba(0, 0, 0, 0.1)', borderColor: '#333333', borderWidth: 1, borderRadius: 5, flex: 1, margin: 8, padding: 8, }, likeContainer: { flexDirection: 'row', }, likesText: { flex: 1, fontSize: 18, alignSelf: 'center', }, progressBarContainer: { height: 10, margin: 10, borderColor: '#eeeeee', borderWidth: 2, }, progressBar: { alignSelf: 'flex-start', flex: 1, backgroundColor: '#eeeeee', }, viewPager: { flex: 1, }, }); module.exports = ViewPagerAndroidExample;
src/Button.js
IndWalker/react-calc
import React, { Component } from 'react'; const Button = ( {text, handle} ) => { return <button className="calculator-key" onClick={handle}>{text}</button> } export default Button;
src/components/common/Header.js
DarylRodrigo/DarylRodrigo.github.io
import React from 'react'; import { Link } from 'gatsby'; import '../../assets/sass/main.scss'; const Header = () => ( <header id="header"> <Link className="title" to="/"> Hyperspace </Link> <nav> <ul> <li> <Link to="/">Work</Link> </li> <li> <Link to="/generic">Projects</Link> </li> <li> <Link to="/elements">About</Link> </li> </ul> </nav> </header> ); export default Header;
app/components/toolbar/Title.js
cmilfont/zonaextrema
import React from 'react'; import { Link } from 'react-router'; export default class Title extends React.Component { render() { return ( <div className="zx-toolbar-title"> <Link className="zx-toolbar-logo" to="/"> <img src="/assets/images/biologo.png" alt="Biohacking" /> </Link> <div className="zx-toolbar-info"> <Link className="zx-toolbar-info-name" to="/">Biohacking</Link> <div className="zx-toolbar-info-logout"> <Link to="/logout">Log Out</Link> </div> </div> </div> ); } }
src/js/components/ui/dropdown/DropdownToggle.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import PropTypes from 'prop-types'; import React from 'react'; export default class DropdownToggle extends React.Component { handleClick(e) { e.preventDefault(); this.props.toggleDropdown(); } render() { return ( <a className={this.props.className} id={this.props.id} data-toggle="dropdown" onClick={this.handleClick.bind(this)} > {this.props.children} </a> ); } } DropdownToggle.propTypes = { children: PropTypes.node, className: PropTypes.string, id: PropTypes.string, toggleDropdown: PropTypes.func }; DropdownToggle.defaultProps = { className: 'dropdown-toggle' };
src/interface/others/CooldownOverview.js
FaideWW/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Cooldown from './Cooldown'; const CooldownOverview = ({ fightStart, fightEnd, cooldowns }) => ( <div style={{ marginTop: -10, marginBottom: -10 }}> <ul className="list"> {cooldowns.map(cooldown => ( <li key={`${cooldown.spell.id}-${cooldown.start}`} className="item clearfix" style={{ padding: '1em' }}> <Cooldown cooldown={cooldown} fightStart={fightStart} fightEnd={fightEnd} /> </li> ))} </ul> </div> ); CooldownOverview.propTypes = { fightStart: PropTypes.number.isRequired, fightEnd: PropTypes.number.isRequired, cooldowns: PropTypes.arrayOf(PropTypes.shape({ ability: PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, }), start: PropTypes.number.isRequired, end: PropTypes.number, events: PropTypes.arrayOf(PropTypes.shape({ type: PropTypes.string.isRequired, })).isRequired, })).isRequired, }; export default CooldownOverview;
src/svg-icons/maps/hotel.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsHotel = (props) => ( <SvgIcon {...props}> <path d="M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3zm12-6h-8v7H3V5H1v15h2v-3h18v3h2v-9c0-2.21-1.79-4-4-4z"/> </SvgIcon> ); MapsHotel = pure(MapsHotel); MapsHotel.displayName = 'MapsHotel'; MapsHotel.muiName = 'SvgIcon'; export default MapsHotel;
src/main.js
feedreaderco/web
import React from 'react'; import ReactDOM from 'react-dom'; import api from './api'; import Article from './components/Article'; import SubscribeButton from './components/SubscribeButton'; import UserLink from './components/UserLink'; const token = localStorage.token; const user = localStorage.user; const lib = api(user, token); const userLink = document.getElementById('userLink'); const userH2 = document.getElementById('user'); const splitPathname = window.location.pathname.split('/'); const isArticle = splitPathname[splitPathname.length - 1] === 'articles'; const labelArticles = {}; const userLinkDiv = document.getElementById('userLinkContainer'); let hash = window.location.hash; let pathname = splitPathname.join('/'); let current; let articles; function displaySubscribeButton({ allFolders, folders }) { const feed = pathname.slice(7, -1); let isSelectedInitially = false; let folderNames = ['Other']; if (allFolders && allFolders.length > 0 && folders && folders.length > 0) { folderNames = folders; isSelectedInitially = true; } ReactDOM.render(<SubscribeButton folderNames={folderNames} isSelectedInitially={isSelectedInitially} feedURL={feed} />, userLinkDiv); } function storeLabelArticles(label) { return lib.user.labels.get(label).then((response) => { labelArticles[label] = response.articles || []; }); } function getLabels() { return lib.user.labels.get().then((response) => { if (!response.labels) return; const promiseArr = response.labels.map(storeLabelArticles); Promise.all(promiseArr); }).catch(console.error); } function displayArticle(article) { const element = document.createElement('div'); element.id = article.hash; const e = document.getElementById('articles').appendChild(element); ReactDOM.render(<Article article={article} labels={labelArticles} user={user} />, e); if (!current) current = e; } function getArticle(id) { if (!id) return; lib.articles.get(id).then(({ article, error }) => { if (!article) { console.error(`Could not parse articles/${id}`, error); } if (!document.getElementById(id)) { displayArticle(article); } }).catch(console.error); } function getArticles() { let endpoint = pathname.slice(1, -1); if (endpoint == "") { endpoint = `${user}/feeds`; } return lib.get(endpoint).then((response) => { if (response.articles) { let i = 0; articles = response.articles; if (hash) { i = articles.indexOf(hash); } if (i < 0) { i = 0; } articles.slice(i, i + 4).forEach(getArticle); } }); } function refreshFeed({ key, title }) { return lib.feeds.get(key).then((response) => { if (!response.articles) return; console.log(`Refreshed ${title}, ${response.articles.length} articles so far`); }).catch((err) => { console.log(`Could not refresh ${title}: ${err}`); }); } function refreshFeeds() { if (!token) return; lib.user.feeds.get().then(({ feeds }) => { if (!feeds) return; const promiseArr = feeds.map(refreshFeed); Promise.all(promiseArr); }).catch(console.error); } function updateState() { const nextArticleIsCurrent = current.nextSibling.offsetTop < window.pageYOffset; const hasPreviousArticle = current.previousSibling.firstChild != null; const previousArticleIsCurrent = hasPreviousArticle && (current.offsetTop > window.pageYOffset); if (nextArticleIsCurrent || previousArticleIsCurrent) { const id = current.id; const i = articles.indexOf(id); getArticle(articles[i + 5]); if (previousArticleIsCurrent) { current = current.previousSibling; } else { current = current.nextSibling; } const articleDiv = current.firstChild; const articleTitle = articleDiv.childNodes[0].firstChild.innerHTML; const feedTitle = articleDiv.childNodes[1].firstChild.innerHTML; document.title = `${articleTitle} - ${feedTitle} (feedreader.co)`; history.replaceState({ id: current.id }, '', `https://${window.location.hostname}${pathname}#${current.id}`); if (token) { console.log(`Marking ${id} as read`); lib.user.labels.post('read', id).then(() => { console.log(`Marked ${id} as read`); }).catch(() => { console.log(`Couldn't mark ${id} as read`); }); } } } pathname = `${pathname}/`; window.onscroll = updateState; if (!user) { // no user logged in, redirect to signup page // there's a login link on that page window.location.pathname = "signup"; } if (splitPathname[1] === 'feeds' && user) { const feed = pathname.slice(7, -1); lib.user.folders.get(feed) .then(displaySubscribeButton) .catch(console.error); } else { ReactDOM.render(<UserLink user={user}/>, userLinkDiv); } if (hash && isArticle) { getLabels().then(() => getArticle(hash)).then(refreshFeeds); } else { getLabels().then(getArticles).then(refreshFeeds); }
jenkins-design-language/src/js/components/material-ui/svg-icons/editor/strikethrough-s.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const EditorStrikethroughS = (props) => ( <SvgIcon {...props}> <path d="M7.24 8.75c-.26-.48-.39-1.03-.39-1.67 0-.61.13-1.16.4-1.67.26-.5.63-.93 1.11-1.29.48-.35 1.05-.63 1.7-.83.66-.19 1.39-.29 2.18-.29.81 0 1.54.11 2.21.34.66.22 1.23.54 1.69.94.47.4.83.88 1.08 1.43.25.55.38 1.15.38 1.81h-3.01c0-.31-.05-.59-.15-.85-.09-.27-.24-.49-.44-.68-.2-.19-.45-.33-.75-.44-.3-.1-.66-.16-1.06-.16-.39 0-.74.04-1.03.13-.29.09-.53.21-.72.36-.19.16-.34.34-.44.55-.1.21-.15.43-.15.66 0 .48.25.88.74 1.21.38.25.77.48 1.41.7H7.39c-.05-.08-.11-.17-.15-.25zM21 12v-2H3v2h9.62c.18.07.4.14.55.2.37.17.66.34.87.51.21.17.35.36.43.57.07.2.11.43.11.69 0 .23-.05.45-.14.66-.09.2-.23.38-.42.53-.19.15-.42.26-.71.35-.29.08-.63.13-1.01.13-.43 0-.83-.04-1.18-.13s-.66-.23-.91-.42c-.25-.19-.45-.44-.59-.75-.14-.31-.25-.76-.25-1.21H6.4c0 .55.08 1.13.24 1.58.16.45.37.85.65 1.21.28.35.6.66.98.92.37.26.78.48 1.22.65.44.17.9.3 1.38.39.48.08.96.13 1.44.13.8 0 1.53-.09 2.18-.28s1.21-.45 1.67-.79c.46-.34.82-.77 1.07-1.27s.38-1.07.38-1.71c0-.6-.1-1.14-.31-1.61-.05-.11-.11-.23-.17-.33H21z"/> </SvgIcon> ); EditorStrikethroughS.displayName = 'EditorStrikethroughS'; EditorStrikethroughS.muiName = 'SvgIcon'; export default EditorStrikethroughS;
app/javascript/mastodon/features/compose/components/upload_progress.js
koba-lab/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import Icon from 'mastodon/components/icon'; export default class UploadProgress extends React.PureComponent { static propTypes = { active: PropTypes.bool, progress: PropTypes.number, icon: PropTypes.string.isRequired, message: PropTypes.node.isRequired, }; render () { const { active, progress, icon, message } = this.props; if (!active) { return null; } return ( <div className='upload-progress'> <div className='upload-progress__icon'> <Icon id={icon} /> </div> <div className='upload-progress__message'> {message} <div className='upload-progress__backdrop'> <Motion defaultStyle={{ width: 0 }} style={{ width: spring(progress) }}> {({ width }) => <div className='upload-progress__tracker' style={{ width: `${width}%` }} /> } </Motion> </div> </div> </div> ); } }
src/utils/DevTools.js
wanhongfu/p2p-book-library-frontend
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; const DevTools = createDevTools( <DockMonitor toggleVisibilityKey='Ctrl-H' changePositionKey='Ctrl-Q' defaultIsVisible={true}> <LogMonitor /> </DockMonitor> ); export default DevTools;
src/js/renderer/components/Login.js
tongariboyz/5rolli
/* @flow */ import React from 'react'; import nbem from 'nbem'; /** * Login */ export default class Login extends React.Component { constructor() { super(); this.state = { apiKey: '', apiToken: '', boardUrl: '' }; } /** * render * @return {ReactElement} */ render(): React.Element { const l = nbem(); const f = nbem(); return ( <div className="LoginView"> <div className={l('Login')}> <div className={l('&logo')}> <img src="images/5rolliLogo.png" /> </div> <div className={l('&form')}> <div className={f('Field')}> <input className={f('&input')} onChange={e => this.setState({apiToken: e.value})} placeholder="Trello Developer Api Token" type="text" value={this.state.apiToken} /> </div> <div className={f('Field')}> <input className={f('&input')} onChange={e => this.setState({apiKey: e.value})} placeholder="Trello Developer Api Key" type="text" value={this.state.apiKey} /> </div> <div className={f('Field')}> <input className={f('&input')} onChange={e => this.setState({boardUrl: e.value})} placeholder="Trello Board URL" type="text" value={this.state.boardUrl} /> </div> <div className={l('&&submit')}> <button className={l('&&&btn', 'btn')} onClick={() => {}} > LOGIN </button> </div> </div> </div> </div> ); } }
app/components/Loader/Loader.js
dmitru/react-redux-router-expense-tracker-example-app
/** * Created by dmitru on 6/5/16. */ import React from 'react' import styles from './Loader.scss' export default () => ( <div className={styles.loader}> Loading... </div> )
src/decorators/withViewport.js
inkless/react-small-project
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from '../../node_modules/react/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on('resize', this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); } }; } export default withViewport;
src/results.js
CMinusMinus/DerbyHacks
import React from 'react'; import ReactDOM from 'react-dom'; import {Paper, List, ListItem, Subheader} from 'material-ui'; import ContentInbox from 'material-ui/svg-icons/content/inbox'; import ActionGrade from 'material-ui/svg-icons/action/grade'; import ContentSend from 'material-ui/svg-icons/content/send'; import ContentDrafts from 'material-ui/svg-icons/content/drafts'; import Divider from 'material-ui/Divider'; import ActionInfo from 'material-ui/svg-icons/action/info'; export default class Results extends React.Component { render() { const paper = { height: '25%', width: '60%', marginLeft: '20%', marginRight: '20%', textAlign: 'center', display: 'inline-block', }; console.log("props",this.props.results); return ( <List> <Subheader>Here's what we found:</Subheader> {this.props.results ? this.props.results.map(item => ( <a key={item.name} href={item.link} target="_blank" style={{ linkStyle: 'none' }}> <ListItem primaryText={item.title} /><Divider/> </a> )) : null } </List> ); } }
src/svg-icons/image/tonality.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTonality = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93s3.05-7.44 7-7.93v15.86zm2-15.86c1.03.13 2 .45 2.87.93H13v-.93zM13 7h5.24c.25.31.48.65.68 1H13V7zm0 3h6.74c.08.33.15.66.19 1H13v-1zm0 9.93V19h2.87c-.87.48-1.84.8-2.87.93zM18.24 17H13v-1h5.92c-.2.35-.43.69-.68 1zm1.5-3H13v-1h6.93c-.04.34-.11.67-.19 1z"/> </SvgIcon> ); ImageTonality = pure(ImageTonality); ImageTonality.displayName = 'ImageTonality'; ImageTonality.muiName = 'SvgIcon'; export default ImageTonality;
source/client/components/form/RadioElement.js
achobanov/ReactJS-Fundamentals-lab
import React from 'react'; export default class RadioElement extends React.Component { render() { return ( <div className='radio radio-inline'> <input type='radio' name={ this.props.groupName } id={ this.props.value.toLowerCase() } value={ this.props.value } checked={ this.props.selectedValue === this.props.value } onChange={ this.props.handleChange }/> <label htmlFor={ this.props.value.toLowerCase() }>{ this.props.value }</label> </div> ); } }
src/layouts/SplitContentLayout/SplitContentLayout.js
Bandwidth/shared-components
import React from 'react'; import PropTypes from 'prop-types'; import * as styles from './styles'; import { Provider } from './Context'; import FixedLayer from './FixedLayer'; export default class SplitContentLayout extends React.PureComponent { static propTypes = { /** * Children should always be SplitContentLayout.MainContent or * SplitContentLayout.SecondaryContent */ children: PropTypes.node, /** * Flips the location of the main content in the layout */ mainContentLocation: PropTypes.oneOf(['left', 'right']), /** * Manually specify which side the action bar should attach to. By default, * it will be on the right, regardless of main content location. */ actionBarLocation: PropTypes.oneOf(['left', 'right']), /** * Controls the color of the content background */ gutter: PropTypes.bool, /** * A component to override the one that renders the top-level element of this * layout pattern */ RootLayout: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), }; static defaultProps = { mainContentLocation: 'right', actionBarLocation: null, gutter: false, RootLayout: styles.RootLayout, }; static styles = styles; render() { const { children, mainContentLocation, actionBarLocation, gutter, RootLayout, ...rest } = this.props; return ( <Provider mainContentLocation={mainContentLocation} actionBarLocation={actionBarLocation} > {(rootElementRef, layerElementRef) => ( <RootLayout ref={rootElementRef} className="content-layout split-content-layout" gutter={gutter} {...rest} > {children} <FixedLayer layerRef={layerElementRef} /> </RootLayout> )} </Provider> ); } }