path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/dumb/editor/EditorModal.js | jeckhummer/wf-constructor | import React from 'react';
import {Modal, Icon, Menu} from "semantic-ui-react";
import {Floated} from "../common/Floated";
import {Uppercase} from "../common/Uppercase";
import {SaveButton} from "../buttons/SaveButton";
import {CancelButton} from "../buttons/CancelButton";
export const EditorModal = ({
isActive,
tabs,
content,
header,
saveButtonDisabled,
onCloseClick,
onSaveClick,
errorMessage,
onTabClick
}) => {
return (
<Modal
open={isActive}
onClose={onCloseClick}>
<Modal.Header>
<Floated right>
<Icon
link
onClick={onCloseClick}
name='close'>
</Icon>
</Floated>
<Uppercase>
{header}
</Uppercase>
</Modal.Header>
<Modal.Content>
<div style={{
height: '411px',
}}>
{
tabs
? (
<Menu
secondary={true}
pointing={true}
items={tabs}
onItemClick={onTabClick}
/>
)
: null
}
{content}
</div>
</Modal.Content>
<Modal.Actions>
<div style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'left'
}}>
<div style={{flexGrow: '1', color: '#e33737'}}>
{errorMessage}
</div>
<div>
<CancelButton
content="CANCEL"
onClick={onCloseClick}
/>
<SaveButton
content="SAVE"
onClick={onSaveClick}
disabled={saveButtonDisabled}
/>
</div>
</div>
</Modal.Actions>
</Modal>
);
}; |
components/ViewPage/ViewPage.js | yodairish/pres-view | 'use strict';
import React from 'react';
import Pres from './Pres/Pres.js';
import SideBar from './SideBar/SideBar.js';
import PresViewStore from '../../js/stores/PresViewStore.js';
export default React.createClass({
/**
* Set default state
*/
getInitialState() {
return {
fullscreen: PresViewStore.getFullscreeStatus(),
loading: PresViewStore.getLoadingStatus()
};
},
/**
* When component into the DOM
* Start listening updating fullscreen mode
*/
componentDidMount() {
PresViewStore.addFullscreenListener(this.onUpdate);
PresViewStore.addLoadingListener(this.onUpdate);
},
/**
* When component remove from DOM
* Stop listening updating fullscreen mode
*/
componentWillUnmount() {
PresViewStore.removeFullscreenListener(this.onUpdate);
PresViewStore.removeLoadingListener(this.onUpdate);
},
/**
* Rendering component to html
*/
render() {
var presentation,
sideBar;
if (this.state.loading) {
presentation = (
<div className="spinner"></div>
);
} else {
if (!this.state.fullscreen) {
sideBar = <SideBar />;
}
presentation = <Pres />;
}
return (
<div className="viewPres">
{presentation}
{sideBar}
</div>
);
},
/**
* Update fullscreen status
*/
onUpdate() {
this.setState({
fullscreen: PresViewStore.getFullscreeStatus(),
loading: PresViewStore.getLoadingStatus()
});
}
});
|
es-react/src/root.js | majunbao/project | import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
); |
src/components/SignupIndex.js | jlmonroy13/brainstutor-client | import React from 'react';
import { Link } from 'react-router';
const SignupIndex = () => {
return (
<div className="section__auth section__auth--index">
<img className="full-width section__auth-image" src={require('../assets/images/hero-authentication.jpg')} />
<div className="section__auth-container section__auth-container--index">
<div className="section__auth-circle">registro</div>
<Link
className="button button--large button--block button--dark-green push-half--bottom"
to="/estudiantes/registrarse"
>Estudiantes</Link>
<Link
className="button button--large button--block button--blue push--bottom"
to="/como-ser-tutor"
>Tutores</Link>
<span className="section__auth-description">¿Ya tienes una cuenta?</span>
<Link
className="button button--link hard--left"
to="/ingresar"
>Ingresa</Link>
</div>
</div>
);
};
export default SignupIndex;
|
src/fe/components/UserEdit.js | searsaw/react-router-demo | import React from 'react';
import { get, patch } from 'axios';
import { Helmet } from 'react-helmet';
import UserForm from './UserForm';
import Page from './Page';
class UserEdit extends React.Component {
constructor(props) {
super(props);
this.state = { user: { name: '' } };
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
}
componentDidMount() {
get('/api/users/1')
.then(({ data: user }) => {
this.setState({ user });
});
}
handleSubmit(user) {
patch(`/api/users/${user.id}`, user)
.then(() => {
this.setState({ user });
console.log('updated:', user);
});
}
handleCancel(e) {
e.preventDefault();
console.log('you have canceled');
}
render() {
const { user } = this.state;
return (
<Page title="Edit User" columns={3}>
<Helmet>
<title>CMS | Edit {user.name}</title>
</Helmet>
<UserForm
user={user}
submitText="Update"
handleSubmit={this.handleSubmit}
handleCancel={this.handleCancel}
/>
</Page>
);
}
}
export default UserEdit;
|
Realization/frontend/czechidm-core/src/components/advanced/WorkflowTaskInfo/WorkflowTaskInfo.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
//
import * as Basic from '../../basic';
import { WorkflowTaskInstanceManager } from '../../../redux';
import UuidInfo from '../UuidInfo/UuidInfo';
import AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo';
const manager = new WorkflowTaskInstanceManager();
/**
* WorkflowTask basic information (info card)
*
* @author Švanda
*/
export class WorkflowTaskInfo extends AbstractEntityInfo {
getManager() {
return manager;
}
showLink() {
if (!super.showLink()) {
return false;
}
return true;
}
/**
* Get link to detail (`url`).
*
* @return {string}
*/
getLink() {
const { entityIdentifier, entity} = this.props;
//
return `/task/${entity ? entity.id : entityIdentifier}`;
}
/**
* TODO: implement different face
*/
render() {
const { rendered, showLoading, className, entity, entityIdentifier, _showLoading, style } = this.props;
//
if (!rendered) {
return null;
}
let _entity = this.props._entity;
if (entity) { // entity prop has higher priority
_entity = entity;
}
//
const classNames = classnames(
'wf-info',
className
);
if (showLoading || (_showLoading && entityIdentifier && !_entity)) {
return (
<Basic.Icon className={ classNames } value="refresh" showLoading style={style}/>
);
}
if (!_entity) {
if (!entityIdentifier) {
return null;
}
return (<UuidInfo className={ classNames } value={ entityIdentifier } style={style}/>);
}
//
let niceLabel = this.getManager().localize(_entity, 'description');
if (!niceLabel) {
niceLabel = _entity.taskName;
}
if (!this.showLink()) {
return (
<span className={ classNames }>{ niceLabel }</span>
);
}
return (
<Link className={ classNames } to={ this.getLink() }>{ niceLabel }</Link>
);
}
}
WorkflowTaskInfo.propTypes = {
...AbstractEntityInfo.propTypes,
/**
* Selected entity - has higher priority
*/
entity: PropTypes.object,
/**
* Selected entity's id - entity will be loaded automatically
*/
entityIdentifier: PropTypes.string,
/**
* Internal entity loaded by given identifier
*/
_entity: PropTypes.object,
_showLoading: PropTypes.bool
};
WorkflowTaskInfo.defaultProps = {
...AbstractEntityInfo.defaultProps,
entity: null,
face: 'link',
_showLoading: true,
};
function select(state, component) {
return {
_entity: manager.getEntity(state, component.entityIdentifier),
_showLoading: manager.isShowLoading(state, null, component.entityIdentifier)
};
}
export default connect(select)(WorkflowTaskInfo);
|
src/js/components/icons/base/SocialVine.js | kylebyerly-hp/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-social-vine`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'social-vine');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="#00B488" fillRule="evenodd" d="M22.0406139,11.9310646 C21.4226105,12.0735653 20.8241073,12.1365657 20.2863544,12.1365657 C17.257838,12.1365657 14.9268254,10.0215542 14.9268254,6.34428433 C14.9268254,4.54202458 15.6235791,3.6045195 16.6090845,3.6045195 C17.5465895,3.6045195 18.1713429,4.44602406 18.1713429,6.15228329 C18.1713429,7.12278854 17.9110915,8.18554429 17.7198405,8.8147977 C17.7198405,8.8147977 18.6528455,10.4423065 21.2043593,9.9428038 C21.7458623,8.7405473 22.0406139,7.18203886 22.0406139,5.81553147 C22.0406139,2.13901157 20.1656037,0 16.7290851,0 C13.196566,0 11.1295548,2.7157647 11.1295548,6.29628407 C11.1295548,9.84380327 12.7878138,12.8895697 15.5223286,14.2770773 C14.3725724,16.5765897 12.9093144,18.6031007 11.3830562,20.1301089 C8.61479121,16.7828408 6.11202766,12.3180667 5.0845221,3.6045195 L1,3.6045195 C2.88701021,18.116348 8.51129065,22.737123 9.99779869,23.6243778 C10.8393032,24.1291306 11.5638072,24.1051304 12.3325613,23.6723781 C13.5400679,22.9853744 17.1655875,19.3613548 19.1748483,15.1155818 C20.0178529,15.1133318 21.0311084,15.0165813 22.0406139,14.78783 L22.0406139,11.9310646 Z" stroke="none"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'SocialVine';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/components/utils/validation/selectField.js | tedyuen/react-redux-form-v6-example | import React from 'react';
const selectField = ({
input,
label,
selects,
meta: { touched, error, warning }
}) => (
<div className={touched && error ? 'has-error form-group':'form-group'}>
<div className="input-group">
<span className="input-group-addon">{label}</span>
<select {...input} className="form-control">
{
selects.map((item, i) => (
<option key={i} value={item.value}>{item.text}</option>
))
}
</select>
</div>
{touched &&
((error && <div className="help-block with-errors">{error}</div>) ||
(warning && <div className="help-block with-errors">{warning}</div>))}
</div>
)
export default selectField;
|
src/main/js/admin/modules/category/Categories.js | chaokunyang/amanda | import React, { Component } from 'react';
import Axios from 'axios'
import moment from 'moment';
import Navbar from './NavBar';
import CategoryEdit from './CategoryEdit';
import CreateCategory from './CreateCategory';
import './Category.css'
class Categories extends Component {
constructor(props) {
super(props);
this.state = {
category: {
children: []
},
categoryHistory: [{}],
editStatus: {},
newCategory: {
name: "",
zhName: "",
level: 0,
parentId: 0,
orderNumber: 0
}
};
this.handleClick = this.handleClick.bind(this);
this.handleNavbarClick = this.handleNavbarClick.bind(this);
this.handleEditClick = this.handleEditClick.bind(this);
this.onEditSave = this.onEditSave.bind(this);
this.onEditCancel = this.onEditCancel.bind(this);
this.handleDeleteClick = this.handleDeleteClick.bind(this);
this.onCreate = this.onCreate.bind(this);
this.onCreateChange = this.onCreateChange.bind(this);
this.onCreateCancel = this.onCreateCancel.bind(this);
}
componentDidMount() {
this.loadCategories();
}
loadCategories() {
Axios.get('/api/categories')
.then(response => {
this.setState({
category: response.data,
categoryHistory: [response.data],
newCategory: {
name: "",
zhName: "",
level: response.data.level + 1,
parentId: response.data.id,
orderNumber: response.data.children.length
}
})
})
.catch(error => {
console.log(error);
});
}
handleClick(event, category) {
event.preventDefault();
this.setState(prevState => {
prevState.categoryHistory.push(category);
return {
categoryHistory: prevState.categoryHistory,
category: category,
editStatus: {},
newCategory: {
name: "",
zhName: "",
level: category.level + 1,
parentId: category.id,
orderNumber: category.children.length
}
}
})
}
onEditSave(category, index) {
Axios.post(`/api/categories`, category)
.then(response => {
this.loadCategories();
this.setState(prevState => {
prevState.editStatus[index] = false;
return {
editStatus: prevState.editStatus
}
})
})
.catch(error => {
console.log(error);
});
}
onEditCancel(index) {
this.setState(prevState => {
prevState.editStatus[index] = false;
return {
editStatus: prevState.editStatus
}
})
}
handleEditClick(e, index) {
e.preventDefault();
this.setState(prevState => {
prevState.editStatus[index] = true;
return {
editStatus: prevState.editStatus
}
})
}
handleDeleteClick(e, categoryId) {
e.preventDefault();
Axios.delete(`/api/categories/${categoryId}`)
.then(response => {
this.loadCategories();
this.setState({
editStatus: {}
})
})
.catch(error => {
console.log(error);
});
}
onCreate() {
Axios.post(`/api/categories`, this.state.newCategory)
.then(response => {
const c = response.data;
let insertPoint = -1;
for(let i = 0; i < this.state.category.children.length; i++) {
let item = this.state.category.children[i];
if(item.orderNumber >= c.orderNumber) {
insertPoint = i;
}
}
if(insertPoint === -1) {
insertPoint = this.state.category.children.length - 1;
}
this.setState(prevState => {
prevState.category.children.splice(insertPoint, 0, c);
return {
category: prevState.category,
newCategory: {
name: "",
zhName: "",
level: prevState.category.level + 1,
parentId: prevState.category.id,
orderNumber: prevState.category.children.length
}
}
})
})
.catch(error => {
console.log(error);
});
}
onCreateChange(newCategory) {
this.setState({newCategory});
}
onCreateCancel() {
this.setState( {
newCategory: {
name: "",
zhName: "",
level: this.state.category.level + 1,
parentId: this.state.category.id
}
})
}
handleNavbarClick(event, category) {
event.preventDefault();
this.setState(prevState => {
let categoryHistory = prevState.categoryHistory;
for(let i = 0; i < categoryHistory.length; i++) {
if(categoryHistory[i] === category) {
categoryHistory = categoryHistory.slice(0, i + 1);
break;
}
}
return {
categoryHistory: categoryHistory,
category: category
}
})
}
render() {
const trs = this.state.category.children.map((category, index) => {
if(this.state.editStatus[index]) {
return <CategoryEdit category={category} key={category.id} onEditSave={this.onEditSave} index={index} onEditCancel={this.onEditCancel}/>
}else {
return (
<tr key={category.id}>
<td>{category.name}</td>
<td>{category.zhName}</td>
<td>{category.level}</td>
<td>{category.orderNumber}</td>
<td>{moment(category.dateCreated).format('YYYY/MM/DD HH:mm:ss')}</td>
<td>{moment(category.dateModified).format('YYYY/MM/DD HH:mm:ss')}</td>
<td>
<button className="btn btn-info" onClick={(e) => this.handleClick(e, category)}>{category.children ? category.children.length : 0}</button>
</td>
<td className="categories-options">
<button className="btn btn-primary btn-sm" onClick={(e) => this.handleEditClick(e, index)}>编辑</button>
<button className="btn btn-danger btn-sm" onClick={(e) => this.handleDeleteClick(e, category.id)}>删除</button>
</td>
</tr>
)
}
});
return (
<div className="Categories">
<h2>分类</h2>
<Navbar categoryHistory={this.state.categoryHistory} handleNavbarClick={this.handleNavbarClick} />
<div className="table-responsive">
<table className="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>分类名称</th>
<th>中文名称</th>
<th className="category-level">类目层级</th>
<th className="order-number">排序编号</th>
<th className="create-time">创建时间</th>
<th className="update-time">修改时间</th>
<th className="children">子类目</th>
<th className="categories-options">操作</th>
</tr>
</thead>
<tbody>
{trs}
<CreateCategory key={'create'} newCategory={this.state.newCategory} onCreate={this.onCreate} onCreateChange={this.onCreateChange} onCreateCancel={this.onCreateCancel} />
</tbody>
</table>
</div>
</div>
)
}
}
export default Categories; |
client/src/app/routes/settings/containers/Teachers/QualificationForm.js | zraees/sms-project | import React from 'react'
import { reset } from 'redux-form'
import axios from 'axios'
import classNames from 'classnames'
import { Field, reduxForm } from 'redux-form'
import WidgetGrid from '../../../../components/widgets/WidgetGrid'
import Datatable from '../../../../components/tables/Datatable'
// import RFDatePicker from '../../../../components/ui/RFDatePicker'
// import RFReactSelect from '../../../../components/ui/RFReactSelect'
// import RFRadioButtonList from '../../../../components/ui/RFRadioButtonList'
// import RFField from '../../../../components/ui/RFField'
// import RFTextArea from '../../../../components/ui/RFTextArea'
import {RFField, RFDatePicker, RFRadioButtonList, RFReactSelect, RFTextArea} from '../../../../components/ui'
import {required, email, number} from '../../../../components/forms/validation/CustomValidation'
import AlertMessage from '../../../../components/common/AlertMessage'
import {submitQualification, removeQualification} from './submit'
import mapForCombo, {getWebApiRootUrl, instanceAxios} from '../../../../components/utils/functions'
//import {Visibility as LoaderVisibility} from '../../../../components/Loader/Loader'
import Msg from '../../../../components/i18n/Msg'
class QualificationForm extends React.Component {
constructor(props){
super(props);
this.state = {
// educationDurationTypes: [
// {"label":"Weeks", "value":"Weeks"},
// {"label":"Months", "value":"Months"},
// {"label":"Years", "value":"Years"}],
qualificationTypes: [],
qualificationScoreTypes: [],
teacherId: 0,
// {"label":"CGPA", "value":"CGPA"},
// {"label":"Percentage", "value":"Percentage"}],
activeTab: "add"
}
}
componentDidMount(){
console.log('componentDidMount --> QualificationForm');
// LoaderVisibility(true);
this.setState({teacherId: this.props.teacherId});
this.props.change('teacherId', this.props.teacherId); // function provided by redux-form
$('#teacherQualificationsGrid').on('click', 'td', function(event) {
if ($(this).find('#dele').length > 0) {
//alert( $(this).find('#dele').data('tid'));
var id = $(this).find('#dele').data('tid');
removeQualification(id, $(this));
}
});
instanceAxios.get('/api/QualificationTypes/')
.then(res=>{
const qualificationTypes = mapForCombo(res.data);
// = res.data.map(function(item, index){
// return {value: item.Id + "", label: item.Name};
// });
this.setState({qualificationTypes});
});
axios.get('assets/api/teachers/qualification-score-types.json')
.then(res=>{
//console.log(res.data);
const qualificationScoreTypes = mapForCombo(res.data);
// = res.data.map(function(item, index){
// return {value: item.Id, label: item.Name};
// });
this.setState({qualificationScoreTypes});
});
}
//
render() {
const { handleSubmit, pristine, reset, submitting, touched, error, warning } = this.props
const { teacherId, qualificationScoreTypes, qualificationTypes, activeTab } = this.state;
return (
<WidgetGrid>
<div className="tabbable tabs">
<ul className="nav nav-tabs">
<li id="tabAddLink" className="active">
<a id="tabAdd" data-toggle="tab" href="#AA"><Msg phrase="AddText" /></a>
</li>
<li id="tabListLink">
<a id="tabList" data-toggle="tab" href="#BB"><Msg phrase="ListText" /></a>
</li>
</ul>
<div className="tab-content">
<div className="tab-pane active" id="AA">
<form id="form-teacher-qualification" className="smart-form"
onSubmit={handleSubmit((values)=>{submitQualification(values, teacherId)})}>
<fieldset>
<div className="row">
{/*<section>*/}
<section className="remove-col-padding col-sm-12 col-md-12 col-lg-12">
<Field name="qualification" labelClassName="input" labelIconClassName="icon-append fa fa-graduation-cap"
validate={required} component={RFField}
maxLength="150" type="text"
label="QualificationTitleText"
placeholder="Please enter qualification title"/>
</section>
{/*</section>*/}
</div>
<div className="row">
<section className="remove-col-padding col-sm-4 col-md-4 col-lg-4">
<Field name="startDate" label="StartDateText" component={RFDatePicker} />
</section>
{/*<article className="col-sm-1 col-md-1 col-lg-1">
</article>*/}
<section className="remove-col-padding col-sm-4 col-md-4 col-lg-4">
<Field name="endDate" label="EndDateText" component={RFDatePicker} />
</section>
<section className="remove-col-padding col-sm-4 col-md-4 col-lg-4">
</section>
</div>
<div className="row">
<section className="remove-col-padding col-sm-5 col-md-5 col-lg-5">
<Field
multi={false}
name="qualificationTypeId"
label="QualificationTypeText"
options={qualificationTypes}
component={RFReactSelect} />
</section>
<section className="remove-col-padding col-sm-4 col-md-4 col-lg-4">
<Field
multi={false}
name="scoreType"
label="CGPAPercentageText"
options={qualificationScoreTypes}
component={RFReactSelect} />
</section>
<section className="remove-col-padding col-sm-3 col-md-3 col-lg-3">
<Field name="score" labelClassName="input" labelIconClassName="icon-append fa fa-list"
validate={[required,number]} component={RFField} type="text"
label="ScoreText"
placeholder="Please enter score"/>
</section>
</div>
<div className="row">
<section className="remove-col-padding col-sm-12 col-md-12 col-lg-12">
<Field name="majors" labelClassName="input" labelIconClassName="icon-append fa fa-book"
component={RFField}
maxLength="500" type="text"
label="MajorsText"
placeholder="Please enter majors"/>
</section>
</div>
{(error!==undefined && <AlertMessage type="w" icon="alert-danger" message={error} />)}
<Field component="input" type="hidden" name="teacherId" />
<footer>
<button type="button" disabled={pristine || submitting} onClick={reset} className="btn btn-primary">
<Msg phrase="ResetText"/>
</button>
<button type="submit" disabled={pristine || submitting} className="btn btn-primary">
<Msg phrase="SaveText"/>
</button>
</footer>
</fieldset>
</form>
</div>
<div className="tab-pane table-responsive" id="BB">
<Datatable id="teacherQualificationsGrid"
options={{
ajax: {"url": getWebApiRootUrl() +'/api/TeacherQualifications/' + teacherId, "dataSrc": ""},
columnDefs: [
{/*{
"type": "date",
"render": function ( data, type, row ) {
//console.log(data);
return data;
//return '<Moment date="2017-05-26T00:00:00" format="DD-MM-YYYY" ></Moment>'; //return data !== null ? moment(data, "DD-MM-YYYY") : null;
},
"targets": 5
},*/},
{
"mRender": function (data, type, full) {
//console.log(data);
{/*if(data!=null){
//var dtStart = new Date(parseInt(data.substr(6)));
var dtStartWrapper = moment(data, "MM-DD-YYYY")
console.log(dtStartWrapper);
return dtStartWrapper;
}*/}
return data; //dtStartWrapper.format('DD/MM/YYYY');
},
"targets": 1
},
{
"render": function ( data, type, row ) {
//return (<a onClick={onOrderRestaurant.bind(self, this)}
// className="btn btn-primary btn-sm">Order this restaurant
// </a>);
return '<a id="dele" data-tid="' + data + '"><i class=\"glyphicon glyphicon-trash\"></i><span class=\"sr-only\">Edit</span></a>';
//return ('<a onClick={self.handleClick.bind(self, 1)}>del</a>');
//return '<a onClick={self.handleClick} className="btn btn-success">click</a>';
//return '<a onClick="javascript:deleteConfirm()" className="btn btn-success"> Callback ()</a>';
//return '<a data-toggle="modal" data-id="' + data + '" data-target="#teacherPopup"><i class=\"glyphicon glyphicon-edit\"></i><span class=\"sr-only\">Delete</span></a>';
}.bind(self),
"className": "dt-center",
"sorting": false,
"targets": 7
}
],
columns: [
//{
// "className": 'details-control',
// "orderable": false,
// "data": null,
// "defaultContent": ''
//},
{data: "Qualification"},
{data: "StartDate"},
{data: "EndDate"},
{data: "QualificationTypes"},
{data: "ScoreType"},
{data: "Score"},
{data: "Duration"},
{data: "TeacherQualificationId"}
],
buttons: [
'copy', 'excel', 'pdf'
]
}}
paginationLength={true}
//refresh={this.state.refresh}
className="table table-striped table-bordered table-hover"
width="100%">
<thead>
<tr>
<th data-hide="mobile-p"><Msg phrase="QualificationTitleText"/></th>
<th data-class="expand"><Msg phrase="StartDateText"/></th>
<th data-hide="mobile-p"><Msg phrase="EndDateText"/></th>
<th data-hide="mobile-p"><Msg phrase="QualificationTypeText"/></th>
<th data-hide="mobile-p"><Msg phrase="CGPAPercentageText"/></th>
<th data-hide="mobile-p"><Msg phrase="ScoreText"/></th>
<th data-hide="mobile-p"><Msg phrase="DurationText"/></th>
<th data-hide="mobile-p"></th>
</tr>
</thead>
</Datatable>
</div>
</div>
</div>
</WidgetGrid>
)
}
}
const afterSubmit = function(result, dispatch) {
dispatch(reset('QualificationForm'));
//this.props.change('teacherId', this.props.teacherId);
}//.bind(this);
export default reduxForm({
form: 'QualificationForm', // a unique identifier for this form
onSubmitSuccess: afterSubmit,
keepDirtyOnReinitialize: false
// ,
// asyncValidate,
// asyncBlurFields: ['email']
})(QualificationForm) |
app/javascript/mastodon/features/public_timeline/index.js | palon7/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import {
refreshPublicTimeline,
expandPublicTimeline,
updateTimeline,
deleteFromTimelines,
connectTimeline,
disconnectTimeline,
} from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ColumnSettingsContainer from './containers/column_settings_container';
import createStream from '../../stream';
const messages = defineMessages({
title: { id: 'column.public', defaultMessage: 'Federated timeline' },
});
const mapStateToProps = state => ({
hasUnread: state.getIn(['timelines', 'public', 'unread']) > 0,
streamingAPIBaseURL: state.getIn(['meta', 'streaming_api_base_url']),
accessToken: state.getIn(['meta', 'access_token']),
});
@connect(mapStateToProps)
@injectIntl
export default class PublicTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
streamingAPIBaseURL: PropTypes.string.isRequired,
accessToken: PropTypes.string.isRequired,
hasUnread: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('PUBLIC', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, streamingAPIBaseURL, accessToken } = this.props;
dispatch(refreshPublicTimeline());
if (typeof this._subscription !== 'undefined') {
return;
}
this._subscription = createStream(streamingAPIBaseURL, accessToken, 'public', {
connected () {
dispatch(connectTimeline('public'));
},
reconnected () {
dispatch(connectTimeline('public'));
},
disconnected () {
dispatch(disconnectTimeline('public'));
},
received (data) {
switch(data.event) {
case 'update':
dispatch(updateTimeline('public', JSON.parse(data.payload)));
break;
case 'delete':
dispatch(deleteFromTimelines(data.payload));
break;
}
},
});
}
componentWillUnmount () {
if (typeof this._subscription !== 'undefined') {
this._subscription.close();
this._subscription = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = () => {
this.props.dispatch(expandPublicTimeline());
}
render () {
const { intl, columnId, hasUnread, multiColumn } = this.props;
const pinned = !!columnId;
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='globe'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer />
</ColumnHeader>
<StatusListContainer
timelineId='public'
loadMore={this.handleLoadMore}
trackScroll={!pinned}
scrollKey={`public_timeline-${columnId}`}
emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other instances to fill it up' />}
/>
</Column>
);
}
}
|
assets/javascripts/kitten/components/structure/cards/summary-card/styles.js | KissKissBankBank/kitten | import React from 'react'
import styled, { css } from 'styled-components'
import TYPOGRAPHY from '../../../../constants/typography-config'
import { pxToRem } from '../../../../helpers/utils/typography'
import { mq } from '../../../../constants/screen-config'
/* ****************************************
Type-specific common styles
****************************************/
const ownerContributionStyles = css`
@media ${mq.tabletAndDesktop} {
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(140)}, 1fr)
${pxToRem(90)}
${pxToRem(100)}
${pxToRem(90)}
${pxToRem(20)};
grid-template-areas: 'title amount contribution availability last-stretch';
}
&.k-SummaryCard-Wrapper--tablet {
.k-SummaryCard-Wrapper__imageWrapper {
display: none;
}
}
&.k-SummaryCard-Wrapper--small,
&.k-SummaryCard-Wrapper--mobile {
.k-SummaryCard-Wrapper__imageWrapper {
display: none;
}
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(120)}, 1fr)
${pxToRem(90)}
${pxToRem(90)}
${pxToRem(20)};
grid-template-areas: 'title amount contribution last-stretch';
& > [class*='__availability'] {
display: none;
}
}
}
}
`
const ownerSubscriptionStyles = css`
@media ${mq.tabletAndDesktop} {
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(80)}, 1fr)
${pxToRem(80)}
${pxToRem(80)}
${pxToRem(90)}
${pxToRem(110)}
${pxToRem(20)};
grid-template-areas: 'title amount frequency subscription availability last-stretch';
}
&.k-SummaryCard-Wrapper--tablet {
.k-SummaryCard-Wrapper__imageWrapper {
display: none;
}
}
&.k-SummaryCard-Wrapper--medium {
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(80)}, 1fr)
${pxToRem(60)}
${pxToRem(80)}
${pxToRem(80)}
${pxToRem(90)}
${pxToRem(20)};
}
}
}
&.k-SummaryCard-Wrapper--small {
.k-SummaryCard-Wrapper__imageWrapper {
display: none;
}
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(60)}, 1fr)
${pxToRem(90)}
${pxToRem(90)}
${pxToRem(20)};
grid-template-areas: 'title amount subscription last-stretch';
& > [class*='__frequency'],
& > [class*='__availability'] {
display: none;
}
}
}
}
`
const contributorContributionStyles = css`
@media ${mq.tabletAndDesktop} {
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(80)}, 1fr)
minmax(${pxToRem(80)}, 1fr)
${pxToRem(80)}
${pxToRem(80)}
${pxToRem(120)}
${pxToRem(50)};
grid-template-areas: 'title description amount payment shipping last';
}
&.k-SummaryCard-Wrapper--medium {
.k-SummaryCard-Wrapper__imageWrapper {
display: none;
}
}
&.k-SummaryCard-Wrapper--tablet,
&.k-SummaryCard-Wrapper--small,
&.k-SummaryCard-Wrapper--mobile {
.k-SummaryCard-Wrapper__imageWrapper {
display: none;
}
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(80)}, 1fr)
minmax(${pxToRem(80)}, 1fr)
${pxToRem(70)}
${pxToRem(70)}
${pxToRem(50)};
grid-template-areas: 'title description amount payment last';
& > [class*='__shipping'] {
display: none;
}
}
}
}
`
const contributorSubscriptionStyles = css`
@media ${mq.tabletAndDesktop} {
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(100)}, 3fr)
minmax(${pxToRem(80)}, 2fr)
${pxToRem(120)}
${pxToRem(110)}
${pxToRem(80)}
${pxToRem(110)}
${pxToRem(40)};
grid-template-areas: 'title description amount payment status shipping last';
}
&.k-SummaryCard-Wrapper--large,
&.k-SummaryCard-Wrapper--medium {
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(100)}, 3fr)
minmax(${pxToRem(80)}, 2fr)
${pxToRem(100)}
${pxToRem(80)}
${pxToRem(70)}
${pxToRem(100)}
${pxToRem(40)};
grid-template-areas: 'title description amount payment status shipping last';
}
}
&.k-SummaryCard-Wrapper--medium {
.k-SummaryCard-Wrapper__imageWrapper {
display: none;
}
}
&.k-SummaryCard-Wrapper--tablet,
&.k-SummaryCard-Wrapper--small,
&.k-SummaryCard-Wrapper--mobile {
.k-SummaryCard-Wrapper__imageWrapper {
display: none;
}
.k-SummaryCard-Wrapper__gridWrapper {
grid-template-columns:
minmax(${pxToRem(80)}, 1fr)
${pxToRem(80)}
${pxToRem(70)}
${pxToRem(60)}
${pxToRem(70)}
${pxToRem(40)};
grid-template-areas: 'title description amount payment status last';
& > [class*='__shipping'] {
display: none;
}
}
}
}
`
const typeStyle = {
ownerContribution: ownerContributionStyles,
ownerSubscription: ownerSubscriptionStyles,
contributorContribution: contributorContributionStyles,
contributorSubscription: contributorSubscriptionStyles,
}
/* ****************************************
Common styles
****************************************/
const commonStyles = css`
@media ${mq.tabletAndDesktop} {
display: flex;
align-items: center;
.k-SummaryCard-Wrapper__imageWrapper {
align-self: stretch;
flex: 0 0 ${pxToRem(160)};
}
.k-SummaryCard-Wrapper__gridWrapper {
display: grid;
align-items: center;
align-content: flex-start;
width: 100%;
padding-left: ${pxToRem(30)};
padding-right: ${pxToRem(30)};
grid-gap: ${pxToRem(10)} ${pxToRem(20)};
grid-template-rows: 1fr;
& > .k-SummaryCard__cell {
grid-area: var(--summaryCardCell-name);
}
}
}
`
/* ****************************************
Card styles
****************************************/
export const StyledSummaryCard = styled(({ type, ...props }) => (
<div {...props} />
))`
/* CARD STYLE */
max-width: 100%;
position: relative;
display: block;
box-sizing: border-box;
text-decoration: none;
background-color: var(--color-grey-000);
transition: background-color 0.2s ease, border-color 0.2s ease;
border: var(--border);
border-radius: var(--border-radius-m);
&.k-SummaryCard--hasAction {
&:hover {
background-color: var(--color-grey-100);
border-color: var(--color-grey-500);
}
&:active {
background-color: var(--color-grey-200);
border-color: var(--color-grey-600);
}
}
@media ${mq.tabletAndDesktop} {
min-height: ${pxToRem(100)};
}
/* ACTION */
.k-SummaryCard__action {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 100%;
height: 100%;
border-radius: var(--border-radius-m);
cursor: pointer;
z-index: 1;
:focus-visible {
outline: auto;
}
}
/* IMAGE */
.k-SummaryCard__imageWrapper {
position: relative;
overflow: hidden;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
@media ${mq.mobile} {
padding-top: calc(5 / 8 * 100%);
}
img,
figure {
display: block;
position: absolute;
object-fit: cover;
object-position: center center;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
border-top-left-radius: calc(var(--border-radius-m) - ${pxToRem(2)});
border-top-right-radius: calc(var(--border-radius-m) - ${pxToRem(2)});
@media ${mq.tabletAndDesktop} {
border-top-left-radius: calc(var(--border-radius-m) - ${pxToRem(2)});
border-bottom-left-radius: calc(var(--border-radius-m) - ${pxToRem(2)});
border-top-right-radius: 0;
}
}
svg {
width: 80%;
@media ${mq.tabletAndDesktop} {
width: 100%;
}
}
}
/* STRUCTURE */
.k-SummaryCard__gridWrapper {
padding: ${pxToRem(15)} ${pxToRem(20)};
display: grid;
align-items: center;
align-content: flex-start;
grid-gap: ${pxToRem(10)} 0;
grid-template-columns: 1fr auto;
grid-template-rows: 1fr auto;
@media ${mq.mobile} {
& > :not([class*='__last']) {
grid-column: 1 / span 1;
}
& > [class*='__last'] {
grid-column: 2 / span 1;
}
}
}
/* SUBCOMPONENTS */
.k-SummaryCard__titleTag {
display: flex;
align-items: center;
width: fit-content;
max-width: 100%;
gap: ${pxToRem(10)};
color: var(--color-primary-500);
${TYPOGRAPHY.fontStyles.regular}
span {
overflow: hidden;
text-overflow: ellipsis;
}
svg,
path {
color: inherit;
flex: 0 0 auto;
&[fill] {
fill: currentColor;
}
&[stroke] {
stroke: currentColor;
}
}
}
.k-SummaryCard__cell[class*='__last-stretch'] {
place-self: stretch flex-end;
}
.k-SummaryCard__cell[class*='__last-stretch'] {
z-index: 2;
display: flex;
align-items: stretch;
justify-content: stretch;
margin: ${pxToRem(-20)} ${pxToRem(-30)};
.k-DropdownMenu .k-DropdownMenu__button {
box-sizing: border-box;
padding: 0 ${pxToRem(30)};
&:focus-visible .k-DropdownMenu__button__inside {
outline: auto;
outline-offset: ${pxToRem(-2)};
}
}
}
${commonStyles}
${({ type }) => typeStyle[type]}
`
/* ****************************************
Title styles
****************************************/
export const StyledSummaryTitles = styled(({ type, ...props }) => (
<div {...props} />
))`
${commonStyles}
${({ type }) => typeStyle[type]}
`
|
example/examples/MarkerTypes.js | azt3k/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
} from 'react-native';
import MapView from 'react-native-maps';
import flagBlueImg from './assets/flag-blue.png';
import flagPinkImg from './assets/flag-pink.png';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const SPACE = 0.01;
class MarkerTypes extends React.Component {
constructor(props) {
super(props);
this.state = {
marker1: true,
marker2: false,
};
}
render() {
return (
<View style={styles.container}>
<MapView
provider={this.props.provider}
style={styles.map}
initialRegion={{
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}
>
<MapView.Marker
onPress={() => this.setState({ marker1: !this.state.marker1 })}
coordinate={{
latitude: LATITUDE + SPACE,
longitude: LONGITUDE + SPACE,
}}
centerOffset={{ x: -18, y: -60 }}
anchor={{ x: 0.69, y: 1 }}
image={this.state.marker1 ? flagBlueImg : flagPinkImg}
>
<Text style={styles.marker}>X</Text>
</MapView.Marker>
<MapView.Marker
onPress={() => this.setState({ marker2: !this.state.marker2 })}
coordinate={{
latitude: LATITUDE - SPACE,
longitude: LONGITUDE - SPACE,
}}
centerOffset={{ x: -42, y: -60 }}
anchor={{ x: 0.84, y: 1 }}
image={this.state.marker2 ? flagBlueImg : flagPinkImg}
/>
</MapView>
</View>
);
}
}
MarkerTypes.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
marker: {
marginLeft: 46,
marginTop: 33,
fontWeight: 'bold',
},
});
module.exports = MarkerTypes;
|
src/scenes/home/challenge/challenge.js | hollomancer/operationcode_frontend | import React, { Component } from 'react';
import axios from 'axios';
import Section from 'shared/components/section/section';
import namesFile from 'operationcode_challenge/names.txt';
import ForkButton from '../../../images/GitHubForkButton.png';
import ProposeButton from '../../../images/GitHubProposeButton.png';
import PencilIcon from '../../../images/GitHubPencilIcon.png';
import ExampleImage from '../../../images/GitHubExample.png';
import PRButton from '../../../images/GitHubPRButton.png';
import styles from './challenge.css';
const RepoLink = 'https://github.com/OperationCode/operationcode_frontend/';
const ChallengeLink = `${RepoLink}blob/master/src/scenes/home/challenge/challenge.js`;
class Challenge extends Component {
constructor() {
super();
this.state = {
names: ''
};
}
componentDidMount() {
if (!this.state.names) {
axios.get(namesFile).then((response) => {
const names = response.data;
this.setState({ names });
});
}
}
render() {
return (
<div>
<Section title="Operation Code Challenge" theme="white" className={styles.displayBlock}>
<p>
Welcome to the Operation Code challenge! The goal of this challenge is to get you to
easily commit your first change to a program, see the results of the change, and leave
your mark on Operation Code itself! To do this we're going to take a look at a
source code repository, clone the repository, make a change to a file and finally create
a pull request.
</p>
<h6 className={styles.centerText}>Let's get started!</h6>
<br />
<ol className={styles.instructionList}>
<li>
Firstly, visit our GitHub repository for this page. GitHub is a website dedicated to
hosting source code. That's right -
<a href={RepoLink} target="_blank" rel="noopener noreferrer">
the code for this website is publically available!
</a>{' '}
Take a moment to explore GitHub. You can see the code for this specific page via
<a href={ChallengeLink} target="_blank" rel="noopener noreferrer">
this link
</a>.
</li>
<li>
Secondly, fork the repository. Forking a repository takes a snapshot of the repo and
places that snapshot into your personal area. This allows anyone to make changes to
any project and easily contribute them back. Visit
<a href={RepoLink} target="_blank" rel="noopener noreferrer">
this link
</a>{' '}
and click on this button near the top-right corner of the screen:
<img src={ForkButton} alt="the GitHub Fork Button" width="65px" /> In a few moments,
you will be redirected to your own copy of this website's source code.
<br />
<br />
<b>Congratulations! You now have your very own personal copy of our website!</b>
</li>
<li>
Now that you have a fork of the "repo", it's time to edit the necessary
file to add your name to the list below! Inside the <code>/src</code> folder , click
on the <code>operationcode_challenge</code> directory and click on the file called{' '}
<code>names.txt</code>. On the right-hand side, you should see
<img src={PencilIcon} alt="a pencil icon button" width="18px" />
- Click it.
</li>
<li>Add your name to the file.</li>
<li>
Scroll to the bottom for the <b>Commit changes</b> form. There are two input boxes. In
the input field with "Update names.txt", type
<code>Add <YOUR NAME> to challenge list</code>. You will leave the second, large
input field blank. There are two "radio" buttons below the input fields.
Check the one that says "Create a new branch". You screen should now have
something like this:
<br />
<br />
<img
src={ExampleImage}
alt="example of GitHub input thus far"
className={styles.blockImage}
/>
<br />
<br />
Once you confirm the similarities, click
<img src={ProposeButton} alt="the 'Propose file change' button" width="125px" />
</li>
<li>
You should now be at the "<b>Open a pull request</b>" screen. We do not wish
to ask ourselves for permission to merge our new branch into our own fork!
Instead, click{' '}
<a href={`${RepoLink}compare`} target="_blank" rel="noopener noreferrer">
here
</a>
, to open Operation Code's "New pull request" interface. You should see
a "Compare changes" headline. Just below that is a link within the
text: 'compare across forks' - click it. Now, click on the selector
that says ' head fork' at the beginning, and choose your fork. Click the
next selector to the right, and choose your new branch. Now, you're comparing
Operation Code's master branch with your new fork's branch, and you may
click
<img src={PRButton} alt="the 'Create pull request' button" width="115px" />
to create your first Pull Request! We hope you come to love that button...
</li>
<blockquote>
<i>
<u>NOTE:</u>
</i>{' '}
A pull request is how people throughout the world are able to contribute to open
source software - like Operation Code's website! When you submit a pull request
it notifies the maintainers of the project, and runs some automated checks. The
maintainers then look at the new changes, and decide if they want it merged into their
repository.
</blockquote>
<br />
<li>
When you're ready, click the "Create pull request" button. Our staff
will be notified and a few minutes after the pull request is accepted and merged your
name will show up below!
</li>
</ol>
<h6 className={styles.centerText}>
Congratulations - you've made your first open source commit!
</h6>
</Section>
<Section title="Your Name Here">
<h6 className={styles.centerText}>
Here is a list of the people that have completed this before you:
</h6>
<p className={styles.displayLinebreak}>{this.state.names}</p>
</Section>
</div>
);
}
}
export default Challenge;
|
docs/src/app/components/pages/components/List/ExampleFolders.js | lawrence-yu/material-ui | import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import ActionInfo from 'material-ui/svg-icons/action/info';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import Avatar from 'material-ui/Avatar';
import FileFolder from 'material-ui/svg-icons/file/folder';
import ActionAssignment from 'material-ui/svg-icons/action/assignment';
import {blue500, yellow600} from 'material-ui/styles/colors';
import EditorInsertChart from 'material-ui/svg-icons/editor/insert-chart';
const ListExampleFolder = () => (
<MobileTearSheet>
<List>
<Subheader inset={true}>Folders</Subheader>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Photos"
secondaryText="Jan 9, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Recipes"
secondaryText="Jan 17, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Work"
secondaryText="Jan 28, 2014"
/>
</List>
<Divider inset={true} />
<List>
<Subheader inset={true}>Files</Subheader>
<ListItem
leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={blue500} />}
rightIcon={<ActionInfo />}
primaryText="Vacation itinerary"
secondaryText="Jan 20, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<EditorInsertChart />} backgroundColor={yellow600} />}
rightIcon={<ActionInfo />}
primaryText="Kitchen remodel"
secondaryText="Jan 10, 2014"
/>
</List>
</MobileTearSheet>
);
export default ListExampleFolder;
|
src/components/Footer/Footer.js | takahashik/todo-app | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
class Footer extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">Home</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/admin">Admin</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">Privacy</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/not-found">Not Found</Link>
</div>
</div>
);
}
}
export default withStyles(s)(Footer);
|
src/renderer/components/MapEditor/ExportButton.js | digidem/ecuador-map-editor | import React from 'react'
import IconButton from '@material-ui/core/IconButton'
import Tooltip from '@material-ui/core/Tooltip'
import ExportIcon from '@material-ui/icons/MoreVert'
import { defineMessages, useIntl, FormattedMessage } from 'react-intl'
import Menu from '@material-ui/core/Menu'
import MenuItem from '@material-ui/core/MenuItem'
import Dialog from '@material-ui/core/Dialog'
import MuiDialogTitle from '@material-ui/core/DialogTitle'
import DialogActions from '@material-ui/core/DialogActions'
import DialogContent from '@material-ui/core/DialogContent'
import DialogContentText from '@material-ui/core/DialogContentText'
import Button from '@material-ui/core/Button'
import LinearProgress from '@material-ui/core/LinearProgress'
import { makeStyles } from '@material-ui/core/styles'
import { remote } from 'electron'
import ICCAExportDialog from './ICCAExportDialog'
import logger from '../../../logger'
import api from '../../new-api'
const m = defineMessages({
// Button tooltip on iD Editor toolbar
exportButton: 'Export map data',
// Menu item for exporting GeoJSON
exportGeoJson: 'Export Territory Data as GeoJSON…',
// Menu item for exporting ICCA Export Packages
exportICCAPackage: 'Export ICCA Export Package…',
// Menu item for exporting Shapefile
exportShapefile: 'Export Territory Data as Shapefile…',
// OK button after successful export
okButton: 'OK',
// Close button after export error
closeButton: 'Close',
// Export dialog title - shown during export progress and after success/failure
dialogTitle: 'Exporting data',
// Export success message,
dialogSuccess: 'Export complete',
// Expor error message - if there was an error during export
dialogError: 'Export failed due to an internal error',
// Save dialog title
saveTitle: 'Export Territory Data',
// Default filename for map export
defaultFilename: 'mapeo-map-data'
})
const DialogTitle = () => (
<MuiDialogTitle id='dialog-title'>
<FormattedMessage {...m.dialogTitle} />
</MuiDialogTitle>
)
const DialogAction = ({ children, onClick }) => (
<DialogActions>
<Button onClick={onClick} color='primary' variant='contained' autoFocus>
{children}
</Button>
</DialogActions>
)
const ExportButton = ({ icca = false }) => {
const { formatMessage: t } = useIntl()
const [status, setStatus] = React.useState('idle')
const cx = useStyles()
const [menuAnchor, setMenuAnchor] = React.useState(null)
const [dialog, setDialog] = React.useState(null)
const handleExportClick = event => {
setMenuAnchor(event.currentTarget)
}
const closeMenu = () => {
setMenuAnchor(null)
}
const handleMenuItemClick = format => () => {
closeMenu()
if (format === 'icca') {
setDialog('icca')
} else {
const ext = format === 'shapefile' ? 'zip' : 'geojson'
remote.dialog
.showSaveDialog({
title: t(m.saveTitle),
defaultPath: t(m.defaultFilename) + '.' + ext,
filters: [{ name: format, extensions: [ext] }]
})
.then(({ canceled, filePath }) => {
if (!filePath || canceled) return
setStatus('pending')
api
.exportData(filePath, { format })
.then(() => {
setStatus('success')
})
.catch(err => {
setStatus('reject')
logger.error('ExportButton save dialog', err)
})
})
}
}
const close = event => {
setStatus('idle')
}
let dialogContent
switch (status) {
case 'idle':
dialogContent = null
break
case 'pending':
dialogContent = (
<>
<DialogTitle />
<DialogContent>
<LinearProgress indeterminate />
</DialogContent>
</>
)
break
case 'success':
dialogContent = (
<>
<DialogTitle />
<DialogContent>
<DialogContentText>
<FormattedMessage {...m.dialogSuccess} />
</DialogContentText>
</DialogContent>
<DialogAction onClick={close}>
<FormattedMessage {...m.okButton} />
</DialogAction>
</>
)
break
case 'reject':
dialogContent = (
<>
<DialogTitle />
<DialogContent>
<DialogContentText>
<FormattedMessage {...m.dialogError} />
</DialogContentText>
</DialogContent>
<DialogAction onClick={close}>
<FormattedMessage {...m.closeButton} />
</DialogAction>
</>
)
break
}
return (
<>
<Tooltip title={t(m.exportButton)}>
<IconButton
aria-label='export'
onClick={handleExportClick}
aria-controls='export-menu'
aria-haspopup='true'
className={cx.button}
>
<ExportIcon />
</IconButton>
</Tooltip>
<Menu
id='export-menu'
anchorEl={menuAnchor}
open={Boolean(menuAnchor)}
onClose={closeMenu}
>
<MenuItem onClick={handleMenuItemClick('geojson')}>
<FormattedMessage {...m.exportGeoJson} />
</MenuItem>
{icca && (
<MenuItem onClick={handleMenuItemClick('icca')}>
<FormattedMessage {...m.exportICCAPackage} />
</MenuItem>
)}
</Menu>
<Dialog
open={status !== 'idle'}
aria-labelledby='dialog-title'
maxWidth='xs'
fullWidth
disableBackdropClick={status === 'pending'}
disableEscapeKeyDown={status === 'pending'}
onClose={() => setStatus('idle')}
>
{dialogContent}
</Dialog>
<ICCAExportDialog
open={dialog === 'icca'}
onClose={() => setDialog(null)}
/>
</>
)
}
export default ExportButton
const useStyles = makeStyles({
button: {
width: 40,
margin: '0 5px'
}
})
|
src/components/pages/PlayLists/PlayList.js | ArtyomVolkov/music-search | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
// M-UI components
import { Card, CardHeader, CardText } from 'material-ui/Card';
import { Avatar, RaisedButton} from 'material-ui';
// Components
import TrackList from '../../custom-components/TrackList/TrackList';
// actions
import * as playlistActions from '../../../actions/playlists';
import * as playerActions from '../../../actions/player';
import * as system from '../../../actions/system';
// services
import RouterService from '../../../services/RouterService/RouterService';
import TRACK_ACTION_SERVICE from '../../../services/TrackActionService/TrackActionService';
@connect(
state => ({
playLists: state.playLists,
player: state.player
}),
dispatch => ({
playListActions: bindActionCreators(playlistActions, dispatch),
playerActions: bindActionCreators(playerActions, dispatch),
systemActions: bindActionCreators(system, dispatch)
})
)
class PlayList extends React.Component {
constructor (props) {
super(props);
this.styles = {
card: {
paddingBottom: 5
},
cardHeader: {
title: {
fontSize: 24,
fontWeight: 600,
color: 'grey',
marginBottom: 10
},
subtitle: {
fontSize: 18,
marginBottom: 5
},
image: {
borderRadius: 0
}
},
cardText: {
body: {
padding: '0 5px'
}
}
};
}
componentDidMount () {
if (!this.props.playLists.data) {
this.props.playListActions.getPlayLists();
}
}
onAction = (actionName, track, index) => {
if (actionName === 'on-play') {
this.onPlaySong(track, index);
return;
}
if (actionName === 'on-edit') {
this.onEditPlayListTrack(track);
}
};
onPlaySong (track, index) {
const { playListActions, playerActions, playLists, player, params, systemActions } = this.props;
const playListIndex = +params.id;
const tracks = playLists.data[ params.id ].tracks;
if (playLists.activeIndex !== playListIndex) {
playListActions.setActivePlaylist(playListIndex);
playerActions.setPlayListData(tracks);
playerActions.selectSong(track, index);
return;
}
if (track.id === player.trackIdError) {
systemActions.onPushMessage({
type: 'error',
msg: 'Error in audio stream'
});
return;
}
if (player.songData && player.songData.id === track.id) {
playerActions.onTogglePlay();
return;
}
playerActions.selectSong(track, index);
}
goToPlayLists =()=> {
RouterService.goBack();
};
onEditPlayListTrack(track) {
TRACK_ACTION_SERVICE.onEdit(track);
}
render () {
const { params, playLists } = this.props;
const { cardHeader, cardText, card } = this.styles;
const playList = playLists.data && playLists.data[ params.id ];
return (
<div className="playlist-page">
{
!playList && <p>No Available PlayLists</p>
}
{
playList &&
<div className="playlist">
<Card containerStyle={card}>
<CardHeader
title={playList.name}
subtitle={`${playList.tracks.length} track(s)`}
avatar={<Avatar size={70} style={cardHeader.image} src={playList.image}/>}
titleStyle={cardHeader.title}
subtitleStyle={cardHeader.subtitle}
/>
<hr />
<CardText style={cardText.body}>
<RaisedButton
label={'Back to playlists'}
icon={<i className="fa fa-arrow-circle-left" />}
onTouchTap={this.goToPlayLists}
/>
<TrackList
tracks={playList.tracks}
type={'playlist-track'}
onAction={this.onAction}
showActions={true}
actionItems={[
{
action: 'on-edit',
divider: true,
iconClass: 'fa fa-pencil-square-o',
label: 'Edit'
}
]}
/>
</CardText>
</Card>
</div>
}
</div>
);
}
}
export default PlayList; |
milestones/05-webpack-intro-css/After/src/frame.js | jaketrent/react-drift | import React from 'react'
export default function Frame({ children }) {
return <div>{children}</div>
}
|
src/components/atoms/logo.js | jameslutley/jameslutley.com | import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import styled from 'react-emotion'
import t from 'tachyons-js'
const LogoLink = styled(Link)`
${t.dib};
${t.link};
${t.fw7};
padding-top: ${props => props.theme.spacingMediumLarge};
padding-right: ${props => props.theme.spacingMedium};
padding-bottom: calc(${props => props.theme.spacingMediumLarge} - 1px);
font-family: ${props => props.theme.sansSerifDisplay};
font-size: ${props => props.theme.fontSize6};
line-height: calc(24 / 18);
color: ${props => props.theme.nearBlack};
${props => props.theme.Desktop} {
padding-top: ${props => props.theme.spacingLarge};
padding-bottom: calc(${props => props.theme.spacingLarge} - 1px);
font-size: ${props => props.theme.fontSize5};
line-height: calc(24 / 20);
}
`
const Logo = ({ siteTitle }) =>
<LogoLink to="/">
{siteTitle}
</LogoLink>
Logo.propTypes = {
siteTitle: PropTypes.string.isRequired,
}
export default Logo
|
react-fundamentals-es6/lessons/08-lifecycle-mounting/App.js | wandarkaf/React-Bible | // https://jsbin.com/fonore/edit?js,console,output
// problematic in JsBin
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(){
super();
this.state = { val: 0 };
this.update = this.update.bind(this);
}
update(){
this.setState({val: this.state.val + 1 })
}
componentWillMount(){
console.log('mounting')
}
render(){
console.log('rendering!')
return <button onClick={this.update}>{this.state.val}</button>
}
componentDidMount(){
console.log('mounted')
}
componentWillUnmount(){
console.log('bye!')
}
}
class Wrapper extends React.Component {
constructor(){
super();
}
mount(){
ReactDOM.render(<App />, document.getElementById('a'))
}
unmount(){
ReactDOM.unmountComponentAtNode(document.getElementById('a'))
}
render(){
return (
<div>
<button onClick={this.mount.bind(this)}>Mount</button>
<button onClick={this.unmount.bind(this)}>Unmount</button>
<div id="a"></div>
</div>
)
}
}
export default Wrapper
|
src/compoments/PurpleContent.js | purple-net/react-native-purple | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
ScrollView,
PixelRatio,
Dimensions,
TextInput,
TouchableHighlight,
TouchableOpacity,
Image,
} from 'react-native';
import ActionButton from 'react-native-action-button';
import Button from 'react-native-button';
import Icon from 'react-native-vector-icons/FontAwesome';
export class PurpleContent extends Component{
static propTypes = {
};
static defaultProps = {
theme: 'light',
primary: 'paperGrey'
};
constructor(props){
super(props);
}
render(){
return(
<View style={[styles.Item]}>
{this.props.IconLeft?<View style={[styles.ListItemLeft]}>
<Image style={[styles.ListItemLeftImage]} source={{uri:'http://wx.qlogo.cn/mmopen/rLNTeVq14fyjxzs0lDeP2lnqeRts8xYJsV6bpGVv9sPFE6VDYM8MwbwhZ6lS3b18OF6JiaEHCsUXzHamvOc2ZibMHEFiaJIaSCI/0'}}></Image>
</View>:null}
<View style={[styles.ListItemCenter]}>
<Text style={[styles.ListItemCenterTitle]}>{this.props.title}</Text>
</View>
{this.props.IconRight?<View style={[styles.ListItemRight]}>
<Text style={[styles.ListItemRightText]}>{this.props.note}</Text>
<Icon name="angle-right" size={24} color="#999" />
</View>:null}
</View>
);
};
}
const styles = StyleSheet.create({
Item:{
flex:1,
flexDirection:'row',
backgroundColor: '#fff',
borderTopWidth:1/PixelRatio.get(),
borderTopColor:'#ccc',
borderBottomWidth:1/PixelRatio.get(),
borderBottomColor:'#ccc',
paddingLeft:10,
paddingRight:10,
paddingTop:10,
paddingBottom:10,
marginTop:10,
},
ListItemLeft:{
alignItems:'center',
justifyContent:'center'
},
ListItemLeftImage:{
width:50,
height:50,
alignItems:'center',
marginRight:10,
borderRadius:5,
},
ListItemCenter:{
flex:1,
justifyContent:'center',
},
ListItemCenterTitle:{
flex:1,
alignItems:'center',
justifyContent:'center',
fontWeight:'bold',
},
ListItemCenterDescript:{
flex:1,
alignItems:'center'
},
ListItemRight:{
flexDirection:'row',
alignItems:'center',
justifyContent:'center',
paddingRight:10,
},
ListItemRightText:{
marginLeft:10,
alignItems:'flex-end',
justifyContent:'center',
},
ListItemRightIcon:{
marginLeft:10,
alignItems:'flex-end',
justifyContent:'center',
},
});
module.exports=PurpleContent;
|
src/svg-icons/maps/restaurant.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsRestaurant = (props) => (
<SvgIcon {...props}>
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7zm5-3v8h2.5v8H21V2c-2.76 0-5 2.24-5 4z"/>
</SvgIcon>
);
MapsRestaurant = pure(MapsRestaurant);
MapsRestaurant.displayName = 'MapsRestaurant';
MapsRestaurant.muiName = 'SvgIcon';
export default MapsRestaurant;
|
src/index.js | sunplot/sunplot | import React from 'react'
import ReactDOM from 'react-dom'
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
import { Provider } from 'react-redux'
import injectTapEventPlugin from 'react-tap-event-plugin'
import store from './store'
import App from './containers/App';
import SolrList from './containers/SolrList';
injectTapEventPlugin();
ReactDOM.render(
<Provider store={store}>
<Router>
<Switch>
<Route path="/" component={App} />
</Switch>
</Router>
</Provider>,
document.getElementById('root'));
|
participant/Notice.js | xeejp/ultimatum-game | import React from 'react'
import Dialog from 'material-ui/Dialog'
import RaisedButton from 'material-ui/RaisedButton';
import { ReadJSON } from '../util/ReadJSON'
const Notice = ({ open, message, onRequestClose }) => (
<Dialog
actions={[(
<RaisedButton
label={ReadJSON().static_text["close"]}
primary={true}
onClick={onRequestClose}
/>
)]}
modal={true}
open={open}
onRequestClose={onRequestClose}
>
{message}
</Dialog>
)
export default Notice
|
components/main.js | papettoTV/isyo | import React, { Component } from 'react';
import FbLogin from './FacebookLogin';
import { Link } from 'react-router'
import Isyo from '../common/models/isyo';
export default class Main extends Component {
constructor(props) {
super(props);
this.state = {
isLoading : true,
userId : null,
isMounted: false
};
}
updateState(state){
console.log("call updateState",state);
this.setState(state);
//親コンポーネントを更新
// this.props.updateState(state);
}
componentDidMount() {
console.log("componentDidMount main");
// var userId = "599c4a3efca924e3759c7875";
//
// // console.log(Isyo);
// // Isyo.get(userId,function(isyo){
// // // Isyo.getIsyo(userId,function(isyo){
// // console.log("show.js isyo.getIsyo",isyo);
// // });
// // let isyo = new Isyo;
// let isyo = Isyo();
// console.log(isyo);
// // isyo.get(userId,function(isyo){
// Isyo.getIsyo(userId,function(isyo){
// console.log("show.js isyo.getIsyo",isyo);
// });
var that = this;
this.setState({ isMounted: true });
if (this.state.isMounted == true) {
$.ajax({
url: "/logon",
dataType: 'json',
type: 'GET',
success: function(res) {
console.log("get logon",res);
that.setState({isLoading: false,userId:res.userId});
},
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
that.setState({isLoading: false});
}
});
}
}
componentWillUnmount() {
console.log("componentWillUnmount main");
this.setState({ isMounted: false });
}
render(){
let link="/input";
console.log("render main.js");
return(
<header id="top">
<div className="container">
<div className="intro-text">
<div className="intro-heading">遺書を書いてみよう</div>
{/*
<FbLogin updateState={this.updateState.bind(this)} loggedLabel="書いてみる"></FbLogin>
*/}
{this.state.userId ?
<Link to={{pathname:link,state:{'userId':this.state.userId}}}>
<button type="button" className="btn btn-primary btn-lg">
書いてみる
</button>
</Link>
:
<a href="/auth/facebook" title="Facebook" className="btn btn-facebook">
<i className="fa fa-facebook fa-fw"></i>書いてみる(facebookログイン)
</a>
}
</div>
</div>
</header>
)
}
}
|
src/app/components/Parallax/index.js | nhardy/web-scaffold | // @flow
import React, { Component } from 'react';
import type { Node } from 'react';
import cx from 'classnames';
import { noop } from 'lodash-es';
import throttle from 'app/lib/throttle';
import { isScrolledIntoView } from 'app/lib/dom';
import styles from './styles.styl';
type Props = {
className: ?string,
children: Node,
componentRef: (?HTMLDivElement) => void,
src: string,
srcSet: ?string,
sizes: ?string,
alt: string,
};
type State = {
style: {
perspectiveOrigin: string,
},
};
const EVENTS = [
'scroll',
'resize',
];
export default class Parallax extends Component<Props, State> {
static defaultProps = {
componentRef: noop,
};
state = {
style: {
perspectiveOrigin: 'center 0px',
},
};
componentDidMount() {
this.update();
EVENTS.forEach(event => window.addEventListener(event, this.update));
}
componentWillUnmount() {
EVENTS.forEach(event => window.removeEventListener(event, this.update));
this.update.cancel();
}
setRef = (ref: ?HTMLDivElement) => {
this._node = ref;
this.props.componentRef(ref);
};
_node: ?HTMLDivElement;
update = throttle(() => {
if (!this._node || !isScrolledIntoView(this._node)) return;
const perspectiveOrigin = `center ${window.scrollY}px`;
this.setState({ style: { perspectiveOrigin } });
});
render() {
const { className, children, src, srcSet, sizes, alt } = this.props;
return (
<div ref={ref => this.setRef(ref)} className={cx(styles.root, className)} style={this.state.style}>
<img className={styles.background} src={src} srcSet={srcSet} sizes={sizes} alt={alt} />
<div className={styles.foreground}>
{children}
</div>
</div>
);
}
}
|
test/regressions/tests/RadioGroup/RadioGroupWithLabelError.js | dsslimshaddy/material-ui | // @flow
import React from 'react';
import { FormLabel, FormControl, FormControlLabel } from 'material-ui/Form';
import Radio, { RadioGroup } from 'material-ui/Radio';
export default function RadioGroupWithLabelError() {
return (
<FormControl style={{ width: 100 }} required error>
<FormLabel>Location</FormLabel>
<RadioGroup selectedValue="home">
<FormControlLabel value="home" control={<Radio />} label="Home" />
<FormControlLabel value="work" control={<Radio />} label="Work" />
</RadioGroup>
</FormControl>
);
}
|
admin/client/App/components/Footer/index.js | giovanniRodighiero/cms | /**
* The global Footer, displays a link to the website and the current Keystone
* version in use
*/
import React from 'react';
import { css } from 'glamor';
import { Container } from '../../elemental';
import theme from '../../../theme';
var Footer = React.createClass({
displayName: 'Footer',
propTypes: {
appversion: React.PropTypes.string,
backUrl: React.PropTypes.string,
brand: React.PropTypes.string,
user: React.PropTypes.object,
User: React.PropTypes.object, // eslint-disable-line react/sort-prop-types
version: React.PropTypes.string,
},
// Render the user
renderUser () {
const { User, user } = this.props;
if (!user) return null;
return (
<span>
<span> Signed in as </span>
<a href={`${Keystone.adminPath}/${User.path}/${user.id}`} tabIndex="-1" className={css(classes.link)}>
{user.name}
</a>
<span>.</span>
</span>
);
},
render () {
const { backUrl, brand, appversion, version } = this.props;
return (
<footer className={css(classes.footer)} data-keystone-footer>
<Container>
<a
href={backUrl}
tabIndex="-1"
className={css(classes.link)}
>
{brand + (appversion ? (' ' + appversion) : '')}
</a>
<span> powered by </span>
<a
href="http://keystonejs.com"
target="_blank"
className={css(classes.link)}
tabIndex="-1"
>
KeystoneJS
</a>
<span> version {version}.</span>
{this.renderUser()}
</Container>
</footer>
);
},
});
/* eslint quote-props: ["error", "as-needed"] */
const linkHoverAndFocus = {
color: theme.color.gray60,
outline: 'none',
};
const classes = {
footer: {
boxShadow: '0 -1px 0 rgba(0, 0, 0, 0.1)',
color: theme.color.gray40,
fontSize: theme.font.size.small,
paddingBottom: 30,
paddingTop: 40,
textAlign: 'center',
},
link: {
color: theme.color.gray60,
':hover': linkHoverAndFocus,
':focus': linkHoverAndFocus,
},
};
module.exports = Footer;
|
src/js/components/icons/base/BrandHpeStack.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-brand-hpe-stack`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'brand-hpe-stack');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 126 48" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><g fill="none" fillRule="evenodd"><path fill="#333" d="M0,29 L0,17 L3,17 L3,22 L8,22 L8,17 L11,17 L11,29 L8,29 L8,24 L3,24 L3,29 L0,29 Z M16.5,29 C13.5,29 12,27 12,24.5 C12,21.5 14,20 16,20 C19,20 20,22.5 20,24 L20,25 L14.5,25 C14.5,26 15,27 16.5,27 C18,27 18.5,26 18.5,26 L19.5,27.5 C19.5,27.5 18.5,29 16.5,29 Z M17.5,23.5 C17.5,23 17.25,22 16,22 C14.75,22 14.5,23 14.5,23.5 L17.5,23.5 Z M25,28.5 L23,28.5 L20,20 L22.5,20 L24,25 L25.5,20 L27.5,20 L29,25 L30.5,20 L33,20 L30,28.5 L28,28.5 L26.5,24 L25,28.5 Z M34,25.5 L34,17 L37,17 C37,17 37,25 37,26 C37,27 38.5,27 39,26.5 L39,28.5 C39,28.5 38,29 37,29 C34.9791644,29 34,28 34,25.5 Z M45.5,23.5 C45.5,23 45.25,22 44,22 C42.75,22 42.5,23 42.5,23.5 L45.5,23.5 Z M44.5,29 C41.5,29 40,27 40,24.5 C40,21.5 42,20 44,20 C47,20 48,22.5 48,24 L48,25 L42.5,25 C42.5,26 43,27 44.5,27 C46,27 46.5,26 46.5,26 L47.5,27.5 C47.5,27.5 46.5,29 44.5,29 Z M61,20 L61,22 L59,22 L59,26 C59,27 60.5,27 61,26.5 L61,28.5 C61,28.5 60,29 59,29 C57,29 56,28 56,25.5 L56,22 L53,22 L53,26 C53,27 54.5,27 55,26.5 L55,28.5 C55,28.5 54,29 53,29 C51,29 50,28 50,25.5 L50,22 L49,22 L49,20 L50,20 L50,18 L53,18 L53,20 L56,20 L56,18 L59,18 L59,20 L61,20 Z M70,25 C70,25 68,25 68,25 L68.0000001,29 L65,29 L65,17 L70,17 C73.5,17 75,19 75,21 C75,23 73.5,25 70,25 Z M72,21 C72,20 71.5,19.5 69.5,19.5 L68,19.5 L68,22.5 L69.5,22.5 C71.5,22.5 72,22 72,21 Z M78.5,29 C76.4999999,29 75,28 75,26 C75,24 76.5,23 78.5,23 C79.5,23 80.5,23.5 80.5,23.5 C80.5,22.5 80,22 78.5,22 C77,22 76.5,22.5 76.5,22.5 L76,21 C76.5,20.5 77.5,20 78.5,20 C81,20 83,20.5 83,23.5 L82.9999999,29.0000001 L80.9999999,29.0000001 L80.5,28.5 C80.5,28.5 79.5,29 78.5,29 Z M80.5,25.5 C80.5,25.5 80,25 79,25 C78,25 77.5,25.5 77.5,26 C77.5,26.5 78,27 79,27 C80,27 80.5,26.5 80.5,25.5 Z M91,23 C91,23 90,22 89,22 C88,22 86.8571429,22.5 86.8571429,24.5 C86.8571429,26.5 88,27 89,27 C90,27 91,26 91,26 L92,27.5 C92,27.5 91,29 88.5714288,29 C85.5,29 84,27 84,24.5 C84,21.5 86,20 88.5714286,20 C91,20 92,21.5 92,21.5 L91,23 Z M96,25 L96,29 L93.5,29 L93.5,17 L96,17 L96,24 L99,20 L102,20 L98.5,24.5 L102,29 L99,29 L96,25 Z M107.5,25.5 C107.5,25.5 107,25 106,25 C105,25 104.5,25.5 104.5,26 C104.5,26.5 105,27 106,27 C107,27 107.5,26.5 107.5,25.5 Z M105.5,29 C103.5,29 102,28 102,26 C102,24 103.5,23 105.5,23 C106.5,23 107.5,23.5 107.5,23.5 C107.5,22.5 107,22 105.5,22 C104,22 103.5,22.5 103.5,22.5 L103,21 C103.5,20.5 104.5,20 105.5,20 C108,20 110,20.5 110,23.5 L110,29.0000001 L108,29.0000001 L107.5,28.5 C107.5,28.5 106.5,29 105.5,29 Z M114,21.5 C114.5,20.5 115,20 116,20 C116.5,20 117,20.5 117,20.5 L116.5,23 C116.5,23 116,22.5 115.5,22.5 C114.5,22.5 114,23.1685183 114,24 L114,29 L111.5,29 L111.5,20 L114,20 L114,21.5 Z M121,29 C119,29 117.5,27.5 117.5,24.5 C117.5,21.5 119,20 121,20 C122.5,20 123.5,21 123.5,21 L123.5,17.5 L126,17.5 L126,29 L123.5,29 L123.5,28 C123.5,28 122.5,29 121,29 Z M122.5,26.4999999 C123.5,25.9999999 123.5,24.9999999 123.5,24.4999999 C123.5,23.9999999 123.5,23 122.5,22.5 C121.5,22 120,22.5 120,24.5 C120,26.5 121.5,26.9999999 122.5,26.4999999 Z M7,33 L7,35 L2,35 L2,38 L6.5,38 L6.5,40 L2,40 L2,43 L7,43 L7,44.9999998 L0,45 L0,33 L7,33 Z M17,39.5 L17,45 L15,45 L15,39.5 C15,38 14.0298955,37.5 13,37.5 C12,37.5 11,38.5 11,40.5 L11,45 L9,45 L9,36 L11,36 L11,37 C11,37 12,36 13.5,36 C15.5,36 17,37 17,39.5 Z M21,36 L23,36 L23,38 L21,38 L21,42.5 C21,43.5 22.5,43.5 23,43 L23,44.5 C23,44.5 22.5,45 21.5,45 C21,45 19,45 19,42 L19,38 L18,38 L18,36 L19,36 L19,34 L21.0000001,34 L21,36 Z M24,40.5 C24,38 25,36 28,36 C30.5,36 32,38 32,40 L32,41 L26,41 C26,43 27.5,43.5 28.5,43.5 C30,43.5 30.5,42.5 30.5,42.5 L31.5,43.5 C31.5,43.5 30.5,45 28.5,45 C25.5,45 24,43 24,40.5 Z M30,39.5 C30,38 29,37.5 28,37.5 C26.5,37.5 26,38.5 26,39.5 L30,39.5 Z M38,36.0000001 C38.5,36.0000001 39,36.5 39,36.5 L39,38.4999999 C39,38.4999999 38.5,38 37.5,38 C36.5,38 36,38.5 36,40 L36,45.0000001 L34,45.0000001 L34,36.0000001 L36,36.0000001 L36,37.5000001 C36,37.5000001 36.5,36.0000001 38,36.0000001 Z M48.5,40.5 C48.5,43 47.5,45 45,45 C43,45 42,43.5 42,43.5 L42,48 L40,48 L40,36 L42,36 L42,37.5 C42,37.5 43,36 45,36 C47.5,36 48.5,38 48.5,40.5 Z M42,41 C42,42 42.5,43.5 44.5,43.5 C45.5,43.5 46.5,42.5 46.5,40.5 C46.5,38.5 45.5,37.5 44.5,37.5 C43,37.5 42,38.5 42,40 C42,40 42,41 42,41 Z M54,36.0000001 C54.5,36.0000001 55,36.5 55,36.5 L55,38.4999999 C55,38.4999999 54.5,38 53.5,38 C52.5,38 52,38.5 52,40 L52,45.0000001 L50,45.0000001 L50,36.0000001 L52,36.0000001 L52,37.5000001 C52,37.5000001 52.5,36.0000001 54,36.0000001 Z M57,36 L59,36 L59,45 L57,45 L57,36 Z M58,33 C59,33 59,33 59,34.0002128 C59,35.0004257 59,35 58,35 C57,35 57,35.0004257 57,34.0002128 C57,33 57,33 58,33 Z M67.5,37 C67.5,37 66,36 64.5,36 C62.5,36 61,37 61,38.5 C61,41.5 66,40.5 66,42.5 C66,43 65.5,43.5 64,43.5 C62.5,43.5 61.5,43 61.5,43 L61,44 C61,44 62.5,45 64.5,45 C66.5,45 68,44 68,42.5 C68,39.5 63,40 63,38.5 C63,38 63,37.5 65,37.5 C66,37.5 67,38 67,38 L67.5,37 Z M75,39.5 C75,38 74,37.5 73,37.5 C71.5,37.5 71,38.5 71,39.5 L75,39.5 Z M69,40.5 C69,38 70,36 73,36 C75.5,36 77,38 77,40 L77,41 L71,41 C71,43 72.5,43.5 73.5,43.5 C75,43.5 75.5,42.5 75.5,42.5 L76.5,43.5 C76.5,43.5 75.5,45 73.5,45 C70.5,45 69,43 69,40.5 Z" stroke="none"/><path fill="#01A982" d="M0,12 L40,12 L40,0 L0,0 L0,12 Z M3,3 L37,3 L37,9 L3,9 L3,3 Z" stroke="none"/></g></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'BrandHpeStack';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
react-flux-mui/js/material-ui/src/svg-icons/device/usb.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceUsb = (props) => (
<SvgIcon {...props}>
<path d="M15 7v4h1v2h-3V5h2l-3-4-3 4h2v8H8v-2.07c.7-.37 1.2-1.08 1.2-1.93 0-1.21-.99-2.2-2.2-2.2-1.21 0-2.2.99-2.2 2.2 0 .85.5 1.56 1.2 1.93V13c0 1.11.89 2 2 2h3v3.05c-.71.37-1.2 1.1-1.2 1.95 0 1.22.99 2.2 2.2 2.2 1.21 0 2.2-.98 2.2-2.2 0-.85-.49-1.58-1.2-1.95V15h3c1.11 0 2-.89 2-2v-2h1V7h-4z"/>
</SvgIcon>
);
DeviceUsb = pure(DeviceUsb);
DeviceUsb.displayName = 'DeviceUsb';
DeviceUsb.muiName = 'SvgIcon';
export default DeviceUsb;
|
src/components/Dropdown/index.js | antoinejaussoin/mobx-fx | import React from 'react';
import { observer } from 'mobx-react';
import { Dropdown as BaseDropdown } from 'semantic-ui-react';
const Dropdown = ({ placeholder, size, compact, options, value, onChange }) => (
<BaseDropdown
placeholder={placeholder}
compact={compact}
onChange={(e, data) => {
onChange(data.value);
}}
options={options}
value={value} />
);
export default observer(Dropdown); |
actor-apps/app-web/src/app/utils/require-auth.js | suxinde2009/actor-platform | import React from 'react';
import LoginStore from 'stores/LoginStore';
export default (Component) => {
return class Authenticated extends React.Component {
static willTransitionTo(transition) {
if (!LoginStore.isLoggedIn()) {
transition.redirect('/auth', {}, {'nextPath': transition.path});
}
}
render() {
return <Component {...this.props}/>;
}
};
};
|
modules/Route.js | aaron-goshine/react-router | import React from 'react'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { component, components } from './InternalPropTypes'
const { string, func } = React.PropTypes
/**
* A <Route> is used to declare which components are rendered to the
* page when the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is
* requested, the tree is searched depth-first to find a route whose
* path matches the URL. When one is found, all routes in the tree
* that lead to it are considered "active" and their components are
* rendered into the DOM, nested in the same order as in the tree.
*/
const Route = React.createClass({
statics: {
createRouteFromReactElement
},
propTypes: {
path: string,
component,
components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render() {
invariant(
false,
'<Route> elements are for router configuration only and should not be rendered'
)
}
})
export default Route
|
node_modules/react-bootstrap/es/FormControlFeedback.js | caughtclean/but-thats-wrong-blog | import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import Glyphicon from './Glyphicon';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var defaultProps = {
bsRole: 'feedback'
};
var contextTypes = {
$bs_formGroup: React.PropTypes.object
};
var FormControlFeedback = function (_React$Component) {
_inherits(FormControlFeedback, _React$Component);
function FormControlFeedback() {
_classCallCheck(this, FormControlFeedback);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
FormControlFeedback.prototype.getGlyph = function getGlyph(validationState) {
switch (validationState) {
case 'success':
return 'ok';
case 'warning':
return 'warning-sign';
case 'error':
return 'remove';
default:
return null;
}
};
FormControlFeedback.prototype.renderDefaultFeedback = function renderDefaultFeedback(formGroup, className, classes, elementProps) {
var glyph = this.getGlyph(formGroup && formGroup.validationState);
if (!glyph) {
return null;
}
return React.createElement(Glyphicon, _extends({}, elementProps, {
glyph: glyph,
className: classNames(className, classes)
}));
};
FormControlFeedback.prototype.render = function render() {
var _props = this.props,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['className', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
if (!children) {
return this.renderDefaultFeedback(this.context.$bs_formGroup, className, classes, elementProps);
}
var child = React.Children.only(children);
return React.cloneElement(child, _extends({}, elementProps, {
className: classNames(child.props.className, className, classes)
}));
};
return FormControlFeedback;
}(React.Component);
FormControlFeedback.defaultProps = defaultProps;
FormControlFeedback.contextTypes = contextTypes;
export default bsClass('form-control-feedback', FormControlFeedback); |
docs/app/Examples/modules/Dropdown/Usage/DropdownExampleRemoveNoResultsMessage.js | shengnian/shengnian-ui-react | import React from 'react'
import { Dropdown } from 'shengnian-ui-react'
const DropdownExampleRemoveNoResultsMessage = () => (
<Dropdown
options={[]}
search
selection
placeholder='No message...'
noResultsMessage={null}
/>
)
export default DropdownExampleRemoveNoResultsMessage
|
app/jsx/webzip_export/components/ExportList.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - 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 PropTypes from 'prop-types'
import I18n from 'i18n!webzip_exports'
import ExportListItem from './ExportListItem'
class ExportList extends React.Component {
static propTypes = {
exports: PropTypes.arrayOf(
PropTypes.shape({
date: PropTypes.string.isRequired,
link: PropTypes.string,
workflowState: PropTypes.string.isRequired,
newExport: PropTypes.bool.isRequired
})
).isRequired
}
renderExportListItems() {
return this.props.exports.map((webzip, key) => (
<ExportListItem
key={key}
link={webzip.link}
date={webzip.date}
workflowState={webzip.workflowState}
newExport={webzip.newExport}
/>
))
}
render() {
if (this.props.exports.length === 0) {
return <p className="webzipexport__list">{I18n.t('No exports to display')}</p>
}
return <ul className="webzipexport__list">{this.renderExportListItems()}</ul>
}
}
export default ExportList
|
src/index.js | josh-mallett/NICU-Moms-of-Louisiana-Website | import React from 'react';
import ReactDOM from 'react-dom';
import Main from './App';
import './css/index.css';
var container = document.querySelector('.container');
ReactDOM.render(
<Main />, container
);
|
actor-apps/app-web/src/app/components/modals/create-group/ContactItem.react.js | Havi4/actor-platform | import React from 'react';
import AvatarItem from 'components/common/AvatarItem.react';
class ContactItem extends React.Component {
static propTypes = {
contact: React.PropTypes.object,
onToggle: React.PropTypes.func
}
constructor(props) {
super(props);
this.onToggle = this.onToggle.bind(this);
this.state = {
isSelected: false
};
}
onToggle() {
const isSelected = !this.state.isSelected;
this.setState({
isSelected: isSelected
});
this.props.onToggle(this.props.contact, isSelected);
}
render() {
let contact = this.props.contact;
let icon;
if (this.state.isSelected) {
icon = 'check_box';
} else {
icon = 'check_box_outline_blank';
}
return (
<li className="contacts__list__item row">
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
<div className="controls">
<a className="material-icons" onClick={this.onToggle}>{icon}</a>
</div>
</li>
);
}
}
export default ContactItem;
|
client/src/pages/Login.js | ccwukong/lfcommerce-react | import React, { Component } from 'react';
import { Button } from 'reactstrap';
import { FormattedMessage } from 'react-intl';
import LoginForm from './login/LoginForm';
import ResetForm from './login/ResetForm';
import Footer from '../components/Footer';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
isFlipped: false,
};
}
onFlip = () => {
this.setState({
isFlipped: !this.state.isFlipped,
});
}
render() {
return (
<div className="login-page">
<div id="login-box" style={{ transform: `perspective(600px) rotateY(${!this.state.isFlipped ? '0deg' : '-180deg'})` }}>
<p id="login-site-name">
<FormattedMessage id="site.name" />
</p>
<LoginForm /><br />
<Button color="link" id="forgot-pwd" onClick={this.onFlip}>
<FormattedMessage id="sys.forgotPwd" />
</Button>
</div>
<div id="pwd-box" style={{ transform: `perspective(600px) rotateY(${!this.state.isFlipped ? '180deg' : '0deg'})` }}>
<p id="login-site-name">
<FormattedMessage id="sys.forgotPwd" />
</p>
<ResetForm /><br />
<Button color="link" id="forgot-pwd" onClick={this.onFlip}>
<FormattedMessage id="sys.signin" />
</Button>
</div>
<Footer />
</div>
);
}
}
export default Login;
|
packages/reactor-kitchensink/src/examples/Charts/Line/BasicMarkers/BasicMarkers.js | dbuhrman/extjs-reactor | import React, { Component } from 'react';
import { Container } from '@extjs/ext-react';
import { Cartesian } from '@extjs/ext-react-charts';
import ChartToolbar from '../../ChartToolbar';
import generateData from './generateData';
export default class BasicMarkers extends Component {
constructor() {
super();
this.refreshData();
}
store = Ext.create('Ext.data.Store', {
fields: ['id', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'name']
})
state = {
theme: 'default',
numRecords: 10
}
changeTheme = theme => this.setState({ theme })
refreshData = () => {
this.store.loadData(generateData(this.state.numRecords));
}
render() {
const { theme } = this.state;
return (
<Container padding={!Ext.os.is.Phone && 10} layout="fit">
<ChartToolbar
onThemeChange={this.changeTheme}
onRefreshClick={this.refreshData}
theme={theme}
/>
<Cartesian
shadow
insetPadding="20 20 0 10"
theme={theme}
interactions={[{
type: 'panzoom',
}, 'itemhighlight']}
legend={{
type: 'sprite',
position: 'bottom',
marker: { size: 24 }
}}
store={this.store}
axes={[{
type: 'numeric',
position: 'left',
fields: ['g1', 'g2', 'g3'],
minimum: 0
}, {
type: 'category',
position: 'bottom',
visibleRange: [0, 0.5],
fields: 'name'
}]}
series={[{
type: 'line',
xField: 'name',
yField: 'g1',
fill: true,
title: 'Square',
style: {
smooth: true,
miterLimit: 3,
lineCap: 'miter',
opacity: 0.7,
lineWidth: 8
},
highlight: {
scale: 0.9
},
marker: {
type: 'image',
src: 'resources/images/square.png',
width: 46,
height: 46,
x: -23,
y: -23,
scale: 0.7,
fx: {
duration: 200
}
}
}, {
type: 'line',
xField: 'name',
yField: 'g2',
title: 'Circle',
style: {
opacity: 0.7,
lineWidth: 8
},
highlight: {
scale: 0.9
},
marker: {
type: 'image',
src: 'resources/images/circle.png',
width: 46,
height: 46,
x: -23,
y: -23,
scale: 0.7,
fx: {
duration: 200
}
}
}, {
type: 'line',
xField: 'name',
yField: 'g3',
title: 'Polygon',
style: {
opacity: 0.7,
lineWidth: 8
},
highlight: {
scale: 0.9
},
marker: {
type: 'image',
src: 'resources/images/pentagon.png',
width: 48,
height: 48,
x: -24,
y: -24,
scale: 0.7,
fx: {
duration: 200
}
}
}]}
/>
</Container>
)
}
} |
node_modules/@material-ui/core/esm/Hidden/HiddenCss.js | pcclarke/civ-techs | import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import React from 'react';
import PropTypes from 'prop-types';
import warning from 'warning';
import { keys as breakpointKeys } from '../styles/createBreakpoints';
import { capitalize } from '../utils/helpers';
import withStyles from '../styles/withStyles';
var styles = function styles(theme) {
var hidden = {
display: 'none'
};
return breakpointKeys.reduce(function (acc, key) {
acc["only".concat(capitalize(key))] = _defineProperty({}, theme.breakpoints.only(key), hidden);
acc["".concat(key, "Up")] = _defineProperty({}, theme.breakpoints.up(key), hidden);
acc["".concat(key, "Down")] = _defineProperty({}, theme.breakpoints.down(key), hidden);
return acc;
}, {});
};
/**
* @ignore - internal component.
*/
function HiddenCss(props) {
var children = props.children,
classes = props.classes,
className = props.className,
lgDown = props.lgDown,
lgUp = props.lgUp,
mdDown = props.mdDown,
mdUp = props.mdUp,
only = props.only,
smDown = props.smDown,
smUp = props.smUp,
xlDown = props.xlDown,
xlUp = props.xlUp,
xsDown = props.xsDown,
xsUp = props.xsUp,
other = _objectWithoutProperties(props, ["children", "classes", "className", "lgDown", "lgUp", "mdDown", "mdUp", "only", "smDown", "smUp", "xlDown", "xlUp", "xsDown", "xsUp"]);
process.env.NODE_ENV !== "production" ? warning(Object.keys(other).length === 0 || Object.keys(other).length === 1 && other.hasOwnProperty('ref'), "Material-UI: unsupported properties received ".concat(Object.keys(other).join(', '), " by `<Hidden />`.")) : void 0;
var clsx = [];
if (className) {
clsx.push(className);
}
for (var i = 0; i < breakpointKeys.length; i += 1) {
var breakpoint = breakpointKeys[i];
var breakpointUp = props["".concat(breakpoint, "Up")];
var breakpointDown = props["".concat(breakpoint, "Down")];
if (breakpointUp) {
clsx.push(classes["".concat(breakpoint, "Up")]);
}
if (breakpointDown) {
clsx.push(classes["".concat(breakpoint, "Down")]);
}
}
if (only) {
var onlyBreakpoints = Array.isArray(only) ? only : [only];
onlyBreakpoints.forEach(function (breakpoint) {
clsx.push(classes["only".concat(capitalize(breakpoint))]);
});
}
return React.createElement("div", {
className: clsx.join(' ')
}, children);
}
process.env.NODE_ENV !== "production" ? HiddenCss.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Specify which implementation to use. 'js' is the default, 'css' works better for
* server-side rendering.
*/
implementation: PropTypes.oneOf(['js', 'css']),
/**
* If true, screens this size and down will be hidden.
*/
lgDown: PropTypes.bool,
/**
* If true, screens this size and up will be hidden.
*/
lgUp: PropTypes.bool,
/**
* If true, screens this size and down will be hidden.
*/
mdDown: PropTypes.bool,
/**
* If true, screens this size and up will be hidden.
*/
mdUp: PropTypes.bool,
/**
* Hide the given breakpoint(s).
*/
only: PropTypes.oneOfType([PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), PropTypes.arrayOf(PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']))]),
/**
* If true, screens this size and down will be hidden.
*/
smDown: PropTypes.bool,
/**
* If true, screens this size and up will be hidden.
*/
smUp: PropTypes.bool,
/**
* If true, screens this size and down will be hidden.
*/
xlDown: PropTypes.bool,
/**
* If true, screens this size and up will be hidden.
*/
xlUp: PropTypes.bool,
/**
* If true, screens this size and down will be hidden.
*/
xsDown: PropTypes.bool,
/**
* If true, screens this size and up will be hidden.
*/
xsUp: PropTypes.bool
} : void 0;
export default withStyles(styles, {
name: 'PrivateHiddenCss'
})(HiddenCss); |
src/templates/note.js | rachsmithcodes/rachsmith.com | import React from 'react';
import { graphql, Link } from 'gatsby';
import { MDXRenderer } from 'gatsby-plugin-mdx';
import Layout from '../components/Layout';
import TalkyardCommentsIframe from '@debiki/gatsby-plugin-talkyard';
import Seo from '../components/Seo';
import NoteListItem from '../components/NoteListItem';
function formatDate(date) {
return new Date(date.replace(/-/g, '/')).toLocaleDateString('en-US', {
month: 'long',
day: 'numeric',
year: 'numeric',
});
}
export default function note({ data: { mdx }, pageContext: { references } }) {
return (
<Layout page="note">
<Seo title={mdx.fields.title} description={mdx.fields.excerpt} />
<article className="mb-5 border-b p-5">
<h1 className="font-demi text-5xl mb-5">{mdx.fields.title}</h1>
<div className="mb-5 pt-5 pb-5">
<p>
<em>Added:</em> {formatDate(mdx.fields.added)}
</p>
{mdx.fields.updated !== mdx.fields.added && (
<p>
<em>Updated:</em> {formatDate(mdx.fields.updated)}
</p>
)}
<p>
<em>Tags:</em>{' '}
{mdx.fields.tags.map((tag) => (
<Link className="mr-2" to={`/tag/${tag}/`}>
{`#${tag}`}
</Link>
))}
</p>
</div>
<MDXRenderer>{mdx.body}</MDXRenderer>
</article>
{references.length > 0 && (
<section className="p-5 border-b">
<h3 className="mb-3 uppercase tracking-wide">
Referenced by these notes
</h3>
<ul className="list-none">
{references.map(({ title, slug, excerpt, tags }) => (
<NoteListItem
slug={slug}
title={title}
excerpt={excerpt}
tags={tags}
/>
))}
</ul>
</section>
)}
<section className="p-5 border-b">
<h3 className="mb-3 uppercase tracking-wide">Comments</h3>
<TalkyardCommentsIframe />
</section>
</Layout>
);
}
export const query = graphql`
query ($slug: String!) {
mdx(fields: { slug: { eq: $slug } }) {
fields {
title
added
updated
tags
excerpt
}
body
}
}
`;
|
django/webcode/webcode/frontend/node_modules/react-bootstrap/es/Thumbnail.js | OpenKGB/webcode | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import SafeAnchor from './SafeAnchor';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* src property that is passed down to the image inside this component
*/
src: PropTypes.string,
/**
* alt property that is passed down to the image inside this component
*/
alt: PropTypes.string,
/**
* href property that is passed down to the image inside this component
*/
href: PropTypes.string,
/**
* onError callback that is passed down to the image inside this component
*/
onError: PropTypes.func,
/**
* onLoad callback that is passed down to the image inside this component
*/
onLoad: PropTypes.func
};
var Thumbnail = function (_React$Component) {
_inherits(Thumbnail, _React$Component);
function Thumbnail() {
_classCallCheck(this, Thumbnail);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Thumbnail.prototype.render = function render() {
var _props = this.props,
src = _props.src,
alt = _props.alt,
onError = _props.onError,
onLoad = _props.onLoad,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['src', 'alt', 'onError', 'onLoad', 'className', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var Component = elementProps.href ? SafeAnchor : 'div';
var classes = getClassSet(bsProps);
return React.createElement(
Component,
_extends({}, elementProps, {
className: classNames(className, classes)
}),
React.createElement('img', { src: src, alt: alt, onError: onError, onLoad: onLoad }),
children && React.createElement(
'div',
{ className: 'caption' },
children
)
);
};
return Thumbnail;
}(React.Component);
Thumbnail.propTypes = propTypes;
export default bsClass('thumbnail', Thumbnail); |
docs/src/app/components/pages/get-started/Usage.js | rscnt/material-ui | import React from 'react';
import Title from 'react-title-component';
import MarkdownElement from '../../MarkdownElement';
import usageText from './usage.md';
const Usage = () => (
<div>
<Title render={(previousTitle) => `Usage - ${previousTitle}`} />
<MarkdownElement text={usageText} />
</div>
);
export default Usage;
|
example/src/Demo.js | inuscript/redux-candy | import React, { Component } from 'react';
import Source from './Source'
import styled from 'styled-components'
const Flex = styled.div`
display: flex;
box-sizing: border-box;
width: 100vw;
`
const Child = styled.div`
flex: 1;
width: 40vw; /* TODO */
border-radius: 2px;
border: solid #ccc 1px;
margin: 1em;
padding: 1em;
`
export default ({sourceUrl, children}) => {
return <Flex>
<Child>
{children}
</Child>
<Child>
<Source url={sourceUrl} />
</Child>
</Flex>
} |
src/svg-icons/editor/format-color-reset.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatColorReset = (props) => (
<SvgIcon {...props}>
<path d="M18 14c0-4-6-10.8-6-10.8s-1.33 1.51-2.73 3.52l8.59 8.59c.09-.42.14-.86.14-1.31zm-.88 3.12L12.5 12.5 5.27 5.27 4 6.55l3.32 3.32C6.55 11.32 6 12.79 6 14c0 3.31 2.69 6 6 6 1.52 0 2.9-.57 3.96-1.5l2.63 2.63 1.27-1.27-2.74-2.74z"/>
</SvgIcon>
);
EditorFormatColorReset = pure(EditorFormatColorReset);
EditorFormatColorReset.displayName = 'EditorFormatColorReset';
EditorFormatColorReset.muiName = 'SvgIcon';
export default EditorFormatColorReset;
|
httpdocs/theme/react/hooks-app/pling-section/entry-pling-section.js | KDE/ocs-webserver | import React from 'react';
import ReactDOM from 'react-dom';
import PlingSection from './components/PlingSection';
ReactDOM.render(<PlingSection />, document.getElementById('pling-section-content'));
|
src/components/Tags.js | thundernixon/blog2017 | import React from 'react';
import Link from 'gatsby-link';
export default function Tags({ list = [] }) {
return (
<ul className="tag-list">
{list.map(tag =>
<li key={tag}>
<Link className="tag" to={`/tags/${tag}`}>
{tag}
</Link>
</li>
)}
</ul>
);
}
|
lib/codemod/src/transforms/__testfixtures__/csf-hoist-story-annotations/basic.input.js | kadirahq/react-storybook | import React from 'react';
import Button from './Button';
import { action } from '@storybook/addon-actions';
export default {
title: 'Button',
};
export const story1 = () => <Button label="Story 1" />;
export const story2 = () => <Button label="Story 2" onClick={action('click')} />;
story2.story = { name: 'second story' };
export const story3 = () => (
<div>
<Button label="The Button" onClick={action('onClick')} />
<br />
</div>
);
const baz = 17;
story3.story = {
name: 'complex story',
parameters: { foo: { bar: baz } },
decorators: [(storyFn) => <bar>{storyFn}</bar>],
};
|
hw7/frontend/src/components/auth/register.js | yusong-shen/comp531-web-development | /**
* Created by yusong on 10/20/16.
*/
import React from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm } from 'redux-form';
import * as AuthActions from '../../actions/authActions'
const validate = values => {
const errors = {}
if (!values.username) {
errors.username = "Please enter a username."
}
if (!values.email) {
errors.email = "Please enter an email."
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address'
}
if (!values.zipcode) {
errors.zipcode = "Please enter zipcode"
} else if (!/^\d{5}/i.test(values.zipcode)) {
errors.zipcode = 'Zipcode should be 5 digits'
}
if (!values.dob) {
errors.dob = "please enter your date of birth"
} else {
const d = new Date(values.dob)
if (!!d.valueOf()) {
if (d.getFullYear() >= 1998) {
errors.dob = 'must be at least 18 years old to register'
}
} else {
errors.dob = 'Date format is incorrect'
}
}
if (!values.password) {
errors.password = "Please enter a password."
}
if (!values.passwordConfirmation) {
errors.passwordConfirmation = "Please enter a password confirmation."
}
if (values.password !== values.passwordConfirmation ) {
errors.password = 'Passwords do not match'
}
return errors
}
class RegisterForm extends React.Component {
handleFormSubmit = (values) => {
// alert(JSON.stringify(values, null, 4));
const dob = new Date(values.dob).getTime()
this.props.register(values.username, values.password,
values.email, dob, values.zipcode)
}
renderField = ({ id, input, label, placeholder, type, meta: { touched, error } }) => (
<fieldset className={`form-group ${touched && error ? 'has-error' : ''}`}>
<label className="control-label">{label}</label>
<div>
<input id={id} {...input} placeholder={placeholder} className="form-control" type={type} />
{touched && error && <div className="help-block">{error}</div>}
</div>
</fieldset>
)
render() {
return (
<div className="container">
<div className="col-md-6 col-md-offset-3">
<h2 className="text-center">Register</h2>
<form onSubmit={this.props.handleSubmit(this.handleFormSubmit)}>
<Field id="rg_username" name="username" type="text" component={this.renderField} label="Username"/>
<Field id="rg_email" name="email" type="text" component={this.renderField} label="Email" placeholder="a@b.com"/>
<Field id="rg_zipcode" name="zipcode" type="text" component={this.renderField} label="Zipcode" placeholder="77005"/>
<Field id="rg_dob" name="dob" type="date" component={this.renderField} label="Date of Birth" placeholder="mm/dd/yyyy"/>
<Field id="rg_password" name="password" type="password" component={this.renderField} label="Password" />
<Field id="rg_passwordConfirmation" name="passwordConfirmation" type="password" component={this.renderField} label="Password Confirmation" />
<button id="register_btn" action="submit" className="btn btn-primary">Register</button>
</form>
</div>
</div>
)
}
}
// export default RegisterForm
export default connect(
null,
{...AuthActions}
)(reduxForm({
form: 'register',
validate
})(RegisterForm))
|
src/components/Dashboard/CountUpCard.js | kennylbj/kiwi-blog | import React from 'react'
import { Icon, Card } from 'antd'
import CountUp from 'react-countup'
const CountUpCard = ({ icon, title, number, color, handleClick }) => {
return (
<Card style={{padding: '32px', marginBottom: '24px', cursor: 'pointer'}}
bordered={false} bodyStyle={{ padding: 0 }} onClick={handleClick}>
<Icon style={{fontSize: '54px', float: 'left', color: color}} type={icon} />
<div style={{width: '100%', paddingLeft: '78px'}}>
<p style={{lineHeight: '16px', fontSize: '16px', marginBottom: '8px', height: '16px'}}>{title}</p>
<p style={{lineHeight: '32px', fontSize: '24px', height: '32px'}}>
<CountUp
start={0}
end={number}
duration={2.75}
useEasing
useGrouping
separator=","
/>
</p>
</div>
</Card>
)
}
export default CountUpCard
|
src/parser/rogue/outlaw/modules/core/Energy.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import resourceSuggest from 'parser/shared/modules/resourcetracker/ResourceSuggest';
import EnergyTracker from '../../../shared/resources/EnergyTracker';
class Energy extends Analyzer {
static dependencies = {
energyTracker: EnergyTracker,
};
suggestions(when) {
resourceSuggest(when, this.energyTracker, {
spell: SPELLS.COMBAT_POTENCY,
minor: 0.05,
avg: 0.1,
major: 0.15,
extraSuggestion: <>Try to keep energy below max to avoid waisting <SpellLink id={SPELLS.COMBAT_POTENCY.id} /> procs.</>,
});
}
}
export default Energy;
|
demo/src/svg_group.js | RinconStrategies/react-web-animation | import React, { Component } from 'react';
import { AnimationGroup, Animatable } from 'react-web-animation';
export default class SvgGroup extends Component {
getKeyFrames() {
return [
{ transform: 'scale(.1) rotate(0deg)', opacity: 0.1, offset: 0 },
{ transform: 'scale(1.3) rotate(90deg)', opacity: 1, offset: 0.5 },
{ transform: 'scale(1) rotate(0deg)', opacity: 1, offset: 1 },
];
}
getTiming(duration) {
return {
duration,
easing: 'ease-in',
delay: 0,
iterations: 10,
direction: 'alternate',
fill: 'forwards',
};
}
render() {
return (
<div style={{ padding: '12px' }}>
<a href="https://github.com/RinconStrategies/react-web-animation/blob/master/demo/src/svg_group.js">
View Source
</a>
<div
style={{
display: 'flex',
flexDirection: 'column',
pointerEvents: 'none',
fontWeight: 'bold',
fontSize: '4rem',
alignItems: 'center',
justifyContent: 'center',
padding: '12px',
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
}}
>
<AnimationGroup
component="svg"
viewBox="0 0 60 60"
className="svg-group"
>
<Animatable.circle
cx="30"
cy="30"
r="10"
strokeDasharray="0.001, 1.745"
stroke="hsl(120, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4000)}
/>
<Animatable.circle
cx="30"
cy="30"
r="12"
strokeDasharray="0.001, 2.094"
stroke="hsl(108, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4100)}
/>
<Animatable.circle
cx="30"
cy="30"
r="14"
strokeDasharray="0.001, 2.443"
stroke="hsl(96, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4200)}
/>
<Animatable.circle
cx="30"
cy="30"
r="16"
strokeDasharray="0.001, 2.793"
stroke="hsl(84, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4300)}
/>
<Animatable.circle
cx="30"
cy="30"
r="18"
strokeDasharray="0.001, 3.142"
stroke="hsl(72, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4400)}
/>
<Animatable.circle
cx="30"
cy="30"
r="20"
strokeDasharray="0.001, 3.491"
stroke="hsl(60, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4500)}
/>
<Animatable.circle
cx="30"
cy="30"
r="22"
strokeDasharray="0.001, 3.840"
stroke="hsl(48, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4600)}
/>
<Animatable.circle
cx="30"
cy="30"
r="24"
strokeDasharray="0.001, 4.189"
stroke="hsl(36, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4700)}
/>
<Animatable.circle
cx="30"
cy="30"
r="26"
strokeDasharray="0.001, 4.538"
stroke="hsl(24, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4800)}
/>
<Animatable.circle
cx="30"
cy="30"
r="28"
strokeDasharray="0.001, 4.887"
stroke="hsl(12, 100%, 50%)"
keyframes={this.getKeyFrames()}
timing={this.getTiming(4900)}
/>
</AnimationGroup>
</div>
</div>
);
}
}
|
pootle/static/js/admin/components/User/UserAdd.js | iafan/zing | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import UserForm from './UserForm';
const UserAdd = React.createClass({
propTypes: {
collection: React.PropTypes.object.isRequired,
model: React.PropTypes.func.isRequired,
onCancel: React.PropTypes.func.isRequired,
onSuccess: React.PropTypes.func.isRequired,
},
render() {
const Model = this.props.model;
return (
<div className="item-add">
<div className="hd">
<h2>{gettext('Add User')}</h2>
<button
onClick={this.props.onCancel}
className="btn btn-primary"
>
{gettext('Cancel')}
</button>
</div>
<div className="bd">
<UserForm
model={new Model()}
collection={this.props.collection}
onSuccess={this.props.onSuccess}
/>
</div>
</div>
);
},
});
export default UserAdd;
|
src/svg-icons/image/crop-square.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCropSquare = (props) => (
<SvgIcon {...props}>
<path d="M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H6V6h12v12z"/>
</SvgIcon>
);
ImageCropSquare = pure(ImageCropSquare);
ImageCropSquare.displayName = 'ImageCropSquare';
ImageCropSquare.muiName = 'SvgIcon';
export default ImageCropSquare;
|
ui/src/js/password/forgotPassword/SendRequest.js | Dica-Developer/weplantaforest | import axios from 'axios';
import counterpart from 'counterpart';
import React, { Component } from 'react';
import IconButton from '../../common/components/IconButton';
import InputText from '../../common/components/InputText';
import Notification from '../../common/components/Notification';
export default class SendRequest extends Component {
constructor() {
super();
this.state = {
name: ''
};
}
updateValue(toUpdate, value) {
this.setState({
[toUpdate]: value
});
}
sendPasswortResetMail() {
if (this.state.name != '') {
var that = this;
axios
.post('http://localhost:8081/password_request?userName=' + encodeURIComponent(this.state.name) + '&language=' + localStorage.getItem('language'))
.then(function(response) {
that.props.setResetted();
})
.catch(function(error) {
that.refs.notification.handleError(error);
});
} else {
this.refs.notification.addNotification(counterpart.translate('NO_USERNAME.TITLE'), counterpart.translate('NO_USERNAME.TEXT'), 'error');
}
}
render() {
return (
<div className="col-md-12">
<h1>{counterpart.translate('PASSWORD_FORGOT')}</h1>
<div className="form">
{counterpart.translate('PASSWORD_FORGOT_TEXT')}
<br />
<InputText toUpdate="name" updateValue={this.updateValue.bind(this)} />
<br />
<IconButton text={counterpart.translate('SEND_PASSWORD_RESET_MAIL')} glyphIcon="glyphicon-envelope" onClick={this.sendPasswortResetMail.bind(this)} />
</div>
<Notification ref="notification" />
</div>
);
}
}
/* vim: set softtabstop=2:shiftwidth=2:expandtab */
|
client/views/setupWizard/Step.js | Sing-Li/Rocket.Chat | import React from 'react';
import './Step.css';
export const Step = ({ active, working = false, ...props }) =>
<form
data-qa={active ? 'active-step' : undefined}
className={[
'SetupWizard__Step',
active && 'SetupWizard__Step--active',
working && 'SetupWizard__Step--working',
].filter(Boolean).join(' ')}
disabled={working}
{...props}
/>;
|
examples/js/manipulation/export-csv-column-table.js | prajapati-parth/react-bootstrap-table | /* eslint max-len: 0 */
/* eslint no-unused-vars: 0*/
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
class ActionFormatter extends React.Component {
render() {
return (
<button className='btn btn-info'>Action</button>
);
}
}
function actionFormatter(cell, row) {
return <ActionFormatter />;
}
export default class ExportCSVTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } exportCSV={ true }>
<TableHeaderColumn dataField='id' isKey hidden export>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
<TableHeaderColumn dataField='action' dataFormat={ actionFormatter } export={ false }>Action</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/components/Accordion/Accordion.Skeleton.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import SkeletonText from '../SkeletonText';
import ChevronRight16 from '@carbon/icons-react/lib/chevron--right/16';
import { settings } from 'carbon-components';
const { prefix } = settings;
export default function AccordionSkeleton(props) {
const Item = () => (
<li className={`${prefix}--accordion__item`}>
<button type="button" className={`${prefix}--accordion__heading`}>
<ChevronRight16 className={`${prefix}--accordion__arrow`} />
<SkeletonText className={`${prefix}--accordion__title`} />
</button>
</li>
);
return (
<ul className={`${prefix}--accordion ${prefix}--skeleton`}>
{props.open ? (
<li
className={`${prefix}--accordion__item ${prefix}--accordion__item--active`}>
<button type="button" className={`${prefix}--accordion__heading`}>
<ChevronRight16 className={`${prefix}--accordion__arrow`} />
<SkeletonText className={`${prefix}--accordion__title`} />
</button>
<div className={`${prefix}--accordion__content`}>
<SkeletonText width="90%" />
<SkeletonText width="80%" />
<SkeletonText width="95%" />
</div>
</li>
) : (
<Item />
)}
{Array.from({
length: props.count
? props.count - 1
: AccordionSkeleton.defaultProps.count,
}).map((v, i) => (
<Item key={`skeleton-accordion-item-${props.uid}-${i}`} />
))}
</ul>
);
}
AccordionSkeleton.propTypes = {
/**
* `false` to not display the first item opened
*/
open: PropTypes.bool,
/**
* Set number of items to render
*/
count: PropTypes.number,
/**
* Set unique identifier to generate unique item keys
*/
uid: PropTypes.any,
};
AccordionSkeleton.defaultProps = {
open: true,
count: 4,
uid: '',
};
|
node_modules/react-router/es/Route.js | lousanna/sinatrademo | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import warning from 'warning';
import React from 'react';
import PropTypes from 'prop-types';
import matchPath from './matchPath';
/**
* The public API for matching a single path and rendering.
*/
var Route = function (_React$Component) {
_inherits(Route, _React$Component);
function Route() {
var _temp, _this, _ret;
_classCallCheck(this, Route);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
match: _this.computeMatch(_this.props, _this.context.router)
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Route.prototype.getChildContext = function getChildContext() {
return {
router: _extends({}, this.context.router, {
route: {
location: this.props.location || this.context.router.route.location,
match: this.state.match
}
})
};
};
Route.prototype.computeMatch = function computeMatch(_ref, _ref2) {
var computedMatch = _ref.computedMatch,
location = _ref.location,
path = _ref.path,
strict = _ref.strict,
exact = _ref.exact;
var route = _ref2.route;
if (computedMatch) return computedMatch; // <Switch> already computed the match for us
var pathname = (location || route.location).pathname;
return path ? matchPath(pathname, { path: path, strict: strict, exact: exact }) : route.match;
};
Route.prototype.componentWillMount = function componentWillMount() {
var _props = this.props,
component = _props.component,
render = _props.render,
children = _props.children;
warning(!(component && render), 'You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored');
warning(!(component && children), 'You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored');
warning(!(render && children), 'You should not use <Route render> and <Route children> in the same route; <Route children> will be ignored');
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps, nextContext) {
warning(!(nextProps.location && !this.props.location), '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.');
warning(!(!nextProps.location && this.props.location), '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.');
this.setState({
match: this.computeMatch(nextProps, nextContext.router)
});
};
Route.prototype.render = function render() {
var match = this.state.match;
var _props2 = this.props,
children = _props2.children,
component = _props2.component,
render = _props2.render;
var _context$router = this.context.router,
history = _context$router.history,
route = _context$router.route,
staticContext = _context$router.staticContext;
var location = this.props.location || route.location;
var props = { match: match, location: location, history: history, staticContext: staticContext };
return component ? // component prop gets first priority, only called if there's a match
match ? React.createElement(component, props) : null : render ? // render prop is next, only called if there's a match
match ? render(props) : null : children ? // children come last, always called
typeof children === 'function' ? children(props) : !Array.isArray(children) || children.length ? // Preact defaults to empty children array
React.Children.only(children) : null : null;
};
return Route;
}(React.Component);
Route.propTypes = {
computedMatch: PropTypes.object, // private, from <Switch>
path: PropTypes.string,
exact: PropTypes.bool,
strict: PropTypes.bool,
component: PropTypes.func,
render: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
location: PropTypes.object
};
Route.contextTypes = {
router: PropTypes.shape({
history: PropTypes.object.isRequired,
route: PropTypes.object.isRequired,
staticContext: PropTypes.object
})
};
Route.childContextTypes = {
router: PropTypes.object.isRequired
};
export default Route; |
app/coffeescripts/ember/screenreader_gradebook/controllers/screenreader_gradebook_controller.js | djbender/canvas-lms | //
// Copyright (C) 2013 - 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 ajax from 'ic-ajax'
import round from '../../../util/round'
import userSettings from '../../../userSettings'
import fetchAllPages from '../../shared/xhr/fetch_all_pages'
import parseLinkHeader from '../../shared/xhr/parse_link_header'
import I18n from 'i18n!sr_gradebook'
import Ember from 'ember'
import _ from 'underscore'
import tz from 'timezone'
import AssignmentDetailsDialog from '../../../AssignmentDetailsDialog'
import CourseGradeCalculator from 'jsx/gradebook/CourseGradeCalculator'
import {updateWithSubmissions, scopeToUser} from 'jsx/gradebook/EffectiveDueDates'
import outcomeGrid from '../../../gradebook/OutcomeGradebookGrid'
import ic_submission_download_dialog from '../../shared/components/ic_submission_download_dialog_component'
import CalculationMethodContent from '../../../models/grade_summary/CalculationMethodContent'
import SubmissionStateMap from 'jsx/gradebook/SubmissionStateMap'
import GradeOverrideEntry from '../../../../jsx/grading/GradeEntry/GradeOverrideEntry'
import GradingPeriodsApi from '../../../api/gradingPeriodsApi'
import GradingPeriodSetsApi from '../../../api/gradingPeriodSetsApi'
import GradebookSelector from 'jsx/gradebook/individual-gradebook/components/GradebookSelector'
import {updateFinalGradeOverride} from '../../../../jsx/gradebook/default_gradebook/FinalGradeOverrides/FinalGradeOverrideApi'
import 'jquery.instructure_date_and_time'
import 'vendor/jquery.ba-tinypubsub'
const {get, set, setProperties} = Ember
// http://emberjs.com/guides/controllers/
// http://emberjs.com/api/classes/Ember.Controller.html
// http://emberjs.com/api/classes/Ember.ArrayController.html
// http://emberjs.com/api/classes/Ember.ObjectController.html
function studentsUniqByEnrollments(...args) {
let hiddenNameCounter = 1
const options = {
initialize(array, changeMeta, instanceMeta) {
return (instanceMeta.students = {})
},
addedItem(array, enrollment, changeMeta, iMeta) {
const student = iMeta.students[enrollment.user_id] || enrollment.user
if (student.hiddenName == null) {
student.hiddenName = I18n.t('student_hidden_name', 'Student %{position}', {
position: hiddenNameCounter
})
hiddenNameCounter += 1
}
if (!student.sections) {
student.sections = []
}
student.sections.push(enrollment.course_section_id)
if (!student.role) {
student.role = enrollment.role
}
if (iMeta.students[student.id]) {
return array
}
iMeta.students[student.id] = student
array.pushObject(student)
return array
},
removedItem(array, enrollment, _, instanceMeta) {
const student = array.findBy('id', enrollment.user_id)
student.sections.removeObject(enrollment.course_section_id)
if (student.sections.length === 0) {
delete instanceMeta.students[student.id]
array.removeObject(student)
hiddenNameCounter -= 1
}
return array
}
}
args.push(options)
return Ember.arrayComputed.apply(null, args)
}
const contextUrl = get(window, 'ENV.GRADEBOOK_OPTIONS.context_url')
const ScreenreaderGradebookController = Ember.ObjectController.extend({
init() {
this.set('effectiveDueDates', Ember.ObjectProxy.create({content: {}}))
return this.set(
'assignmentsFromGroups',
Ember.ArrayProxy.create({content: [], isLoaded: false})
)
},
checkForCsvExport: function() {
const currentProgress = get(window, 'ENV.GRADEBOOK_OPTIONS.gradebook_csv_progress')
const attachment = get(window, 'ENV.GRADEBOOK_OPTIONS.attachment')
if (
currentProgress &&
currentProgress.progress.workflow_state !== 'completed' &&
currentProgress.progress.workflow_state !== 'failed'
) {
const attachmentProgress = {
progress_id: currentProgress.progress.id,
attachment_id: attachment.attachment.id
}
$('#gradebook-export').prop('disabled', true)
$('#last-exported-gradebook').hide()
this.pollGradebookCsvProgress(attachmentProgress)
}
}.on('init'),
contextUrl,
uploadCsvUrl: `${contextUrl}/gradebook_upload/new`,
lastGeneratedCsvAttachmentUrl: get(window, 'ENV.GRADEBOOK_OPTIONS.attachment_url'),
downloadOutcomeCsvUrl: `${contextUrl}/outcome_rollups.csv`,
gradingHistoryUrl: `${contextUrl}/gradebook/history`,
submissionsUrl: get(window, 'ENV.GRADEBOOK_OPTIONS.submissions_url'),
has_grading_periods: get(window, 'ENV.GRADEBOOK_OPTIONS.grading_period_set') != null,
getGradingPeriodSet() {
const grading_period_set = get(window, 'ENV.GRADEBOOK_OPTIONS.grading_period_set')
if (grading_period_set) {
return GradingPeriodSetsApi.deserializeSet(grading_period_set)
} else {
return null
}
},
gradingPeriods: (function() {
const periods = get(window, 'ENV.GRADEBOOK_OPTIONS.active_grading_periods')
const deserializedPeriods = GradingPeriodsApi.deserializePeriods(periods)
const optionForAllPeriods = {
id: '0',
title: I18n.t('all_grading_periods', 'All Grading Periods')
}
return _.compact([optionForAllPeriods].concat(deserializedPeriods))
})(),
lastGeneratedCsvLabel: (() => {
if (get(window, 'ENV.GRADEBOOK_OPTIONS.gradebook_csv_progress')) {
const gradebook_csv_export_date = get(
window,
'ENV.GRADEBOOK_OPTIONS.gradebook_csv_progress.progress.updated_at'
)
return I18n.t('Download Scores Generated on %{date}', {
date: $.datetimeString(gradebook_csv_export_date)
})
}
})(),
selectedGradingPeriod: function(key, newValue) {
let savedGP
const savedGradingPeriodId = userSettings.contextGet('gradebook_current_grading_period')
if (savedGradingPeriodId) {
savedGP = this.get('gradingPeriods').findBy('id', savedGradingPeriodId)
}
if (newValue) {
userSettings.contextSet('gradebook_current_grading_period', newValue.id)
return newValue
} else if (savedGP != null) {
return savedGP
} else {
// default to current grading period, but don't change saved setting
return this.get('gradingPeriods').findBy(
'id',
ENV.GRADEBOOK_OPTIONS.current_grading_period_id
)
}
}.property(),
speedGraderUrl: function() {
return `${contextUrl}/gradebook/speed_grader?assignment_id=${this.get('selectedAssignment.id')}`
}.property('selectedAssignment'),
studentUrl: function() {
return `${contextUrl}/grades/${this.get('selectedStudent.id')}`
}.property('selectedStudent'),
showTotalAsPoints: (() => ENV.GRADEBOOK_OPTIONS.show_total_grade_as_points).property(),
publishToSisEnabled: (() => ENV.GRADEBOOK_OPTIONS.publish_to_sis_enabled).property(),
publishToSisURL: (() => ENV.GRADEBOOK_OPTIONS.publish_to_sis_url).property(),
teacherNotes: (() => ENV.GRADEBOOK_OPTIONS.teacher_notes).property().volatile(),
changeGradebookVersionUrl: (() =>
`${get(window, 'ENV.GRADEBOOK_OPTIONS.change_gradebook_version_url')}`).property(),
hideOutcomes: (() => !get(window, 'ENV.GRADEBOOK_OPTIONS.outcome_gradebook_enabled')).property(),
showDownloadSubmissionsButton: function() {
const hasSubmittedSubmissions = this.get('selectedAssignment.has_submitted_submissions')
const whitelist = ['online_upload', 'online_text_entry', 'online_url']
const submissionTypes = this.get('selectedAssignment.submission_types')
const submissionTypesOnWhitelist = _.intersection(submissionTypes, whitelist)
return hasSubmittedSubmissions && _.some(submissionTypesOnWhitelist)
}.property('selectedAssignment'),
hideStudentNames: false,
showConcludedEnrollments: function() {
if (!ENV.GRADEBOOK_OPTIONS.settings) {
return false
}
return ENV.GRADEBOOK_OPTIONS.settings.show_concluded_enrollments === 'true'
}
.property()
.volatile(),
updateShowConcludedEnrollmentsSetting: function() {
ajax.request({
dataType: 'json',
type: 'put',
url: ENV.GRADEBOOK_OPTIONS.settings_update_url,
data: {
gradebook_settings: {
show_concluded_enrollments: this.get('showConcludedEnrollments')
}
}
})
}.observes('showConcludedEnrollments'),
finalGradeOverrideEnabled: (() => ENV.GRADEBOOK_OPTIONS.final_grade_override_enabled).property(),
allowFinalGradeOverride: function() {
if (!ENV.GRADEBOOK_OPTIONS.course_settings) {
return false
}
return ENV.GRADEBOOK_OPTIONS.course_settings.allow_final_grade_override
}
.property()
.volatile(),
updateAllowFinalGradeOverride: function() {
ajax.request({
dataType: 'json',
type: 'put',
url: `/api/v1/courses/${ENV.GRADEBOOK_OPTIONS.context_id}/settings`,
data: {
allow_final_grade_override: this.get('allowFinalGradeOverride')
}
})
}.observes('allowFinalGradeOverride'),
selectedStudentFinalGradeOverrideChanged: function() {
const student = this.get('selectedStudent')
if (!student) {
return
}
const gradingPeriodId = this.get('selectedGradingPeriod.id')
const studentOverrides = this.overridesForStudent(student.id)
if (!studentOverrides) {
this.set('selectedStudentFinalGradeOverride', null)
return
}
if (gradingPeriodId === '0' || gradingPeriodId == null) {
this.set('selectedStudentFinalGradeOverride', {...studentOverrides.courseGrade})
} else {
this.set('selectedStudentFinalGradeOverride', {
...studentOverrides.gradingPeriodGrades[gradingPeriodId]
})
}
}
.observes(
'selectedStudent',
'selectedGradingPeriod',
'final_grade_overrides',
'final_grade_overrides.content'
)
.on('init'),
selectedAssignmentPointsPossible: function() {
return I18n.n(this.get('selectedAssignment.points_possible'))
}.property('selectedAssignment'),
selectedStudent: null,
selectedStudentFinalGradeOverride: null,
selectedSection: null,
selectedAssignment: null,
weightingScheme: null,
ariaAnnounced: null,
assignmentInClosedGradingPeriod: null,
disableAssignmentGrading: null,
actions: {
columnUpdated(columnData, columnID) {
return this.updateColumnData(columnData, columnID)
},
exportGradebookCsv() {
$('#gradebook-export').prop('disabled', true)
$('#last-exported-gradebook').hide()
return $.ajaxJSON(
ENV.GRADEBOOK_OPTIONS.export_gradebook_csv_url,
'GET'
).then(attachment_progress => this.pollGradebookCsvProgress(attachment_progress))
},
gradeUpdated(submissions) {
return this.updateSubmissionsFromExternal(submissions)
},
onEditFinalGradeOverride(grade) {
const options = {}
if (ENV.GRADEBOOK_OPTIONS.grading_standard) {
options.gradingScheme = {data: ENV.GRADEBOOK_OPTIONS.grading_standard}
}
const gradeOverrideEntry = new GradeOverrideEntry(options)
const currentOverride = this.get('selectedStudentFinalGradeOverride') || {}
const enteredGrade = gradeOverrideEntry.parseValue(grade)
const existingGrade = gradeOverrideEntry.parseValue(currentOverride.percentage)
if (!enteredGrade.valid || !gradeOverrideEntry.hasGradeChanged(existingGrade, enteredGrade)) {
return
}
const gradingPeriodId = this.get('selectedGradingPeriod.id')
const records = this.get('final_grade_overrides')
const overrides = records.get('content.finalGradeOverrides')
const student = this.get('selectedStudent')
const studentOverrides = this.overridesForStudent(student.id)
const studentEnrollment = this.get('enrollments').content.find(
enrollment => enrollment.user_id === student.id
)
if (gradingPeriodId === '0' || gradingPeriodId == null) {
studentOverrides.courseGrade.percentage = enteredGrade.grade.percentage
updateFinalGradeOverride(studentEnrollment.id, null, enteredGrade.grade)
} else {
studentOverrides.gradingPeriodGrades[gradingPeriodId].percentage =
enteredGrade.grade.percentage
updateFinalGradeOverride(studentEnrollment.id, gradingPeriodId, enteredGrade.grade)
}
records.set('content', {finalGradeOverrides: overrides})
},
selectItem(property, item) {
return this.announce(property, item)
}
},
overridesForStudent(studentId) {
const records = this.get('final_grade_overrides')
if (!records || !records.get('isLoaded')) {
return null
}
const overrides = records.get('content.finalGradeOverrides')
const studentOverrides = overrides[studentId] || {}
studentOverrides.courseGrade = studentOverrides.courseGrade || {}
studentOverrides.gradingPeriodGrades = studentOverrides.gradingPeriodGrades || {}
this.get('gradingPeriods').forEach(gp => {
studentOverrides.gradingPeriodGrades[gp.id] =
studentOverrides.gradingPeriodGrades[gp.id] || {}
})
overrides[studentId] = studentOverrides
records.set('content.finalGradeOverrides', {...overrides})
return studentOverrides
},
pollGradebookCsvProgress(attachmentProgress) {
let pollingProgress
const self = this
return (pollingProgress = setInterval(
() =>
$.ajaxJSON(`/api/v1/progress/${attachmentProgress.progress_id}`, 'GET').then(response => {
if (response.workflow_state === 'completed') {
$.ajaxJSON(
`/api/v1/users/${ENV.current_user_id}/files/${attachmentProgress.attachment_id}`,
'GET'
).then(attachment => {
self.updateGradebookExportOptions(pollingProgress)
document.getElementById('gradebook-export-iframe').src = attachment.url
return $('#last-exported-gradebook').attr('href', attachment.url)
})
}
if (response.workflow_state === 'failed') {
return self.updateGradebookExportOptions(pollingProgress)
}
}),
2000
))
},
updateGradebookExportOptions: pollingProgress => {
clearInterval(pollingProgress)
$('#gradebook-export').prop('disabled', false)
return $('#last-exported-gradebook').show()
},
announce(prop, item) {
return Ember.run.next(() => {
let text_to_announce
if (prop === 'student' && this.get('hideStudentNames')) {
text_to_announce = get(item, 'hiddenName')
} else if (prop === 'outcome') {
text_to_announce = get(item, 'title')
} else {
text_to_announce = get(item, 'name')
}
this.set('ariaAnnounced', text_to_announce)
})
},
hideStudentNamesChanged: function() {
this.set('ariaAnnounced', null)
}.observes('hideStudentNames'),
setupSubmissionCallback: function() {
Ember.$.subscribe('submissions_updated', this.updateSubmissionsFromExternal.bind(this))
}.on('init'),
setupAssignmentWeightingScheme: function() {
this.set('weightingScheme', ENV.GRADEBOOK_OPTIONS.group_weighting_scheme)
}.on('init'),
renderGradebookMenu: function() {
const mountPoint = document.querySelector('[data-component="GradebookSelector"]')
if (!mountPoint) {
return
}
const props = {
courseUrl: ENV.GRADEBOOK_OPTIONS.context_url,
learningMasteryEnabled: ENV.GRADEBOOK_OPTIONS.outcome_gradebook_enabled
}
const component = React.createElement(GradebookSelector, props)
return ReactDOM.render(component, mountPoint)
}.on('init'),
willDestroy() {
Ember.$.unsubscribe('submissions_updated')
return this._super()
},
updateSubmissionsFromExternal(submissions) {
const subs_proxy = this.get('submissions')
const selected = this.get('selectedSubmission')
const studentsById = this.groupById(this.get('students'))
const assignmentsById = this.groupById(this.get('assignments'))
return submissions.forEach(submission => {
const student = studentsById[submission.user_id]
const submissionsForStudent = subs_proxy.findBy('user_id', submission.user_id)
const oldSubmission = submissionsForStudent.submissions.findBy(
'assignment_id',
submission.assignment_id
)
// check for DA visibility
if (submission.assignment_visible != null) {
set(submission, 'hidden', !submission.assignment_visible)
this.updateAssignmentVisibilities(
assignmentsById[submission.assignment_id],
submission.user_id
)
}
submissionsForStudent.submissions.removeObject(oldSubmission)
submissionsForStudent.submissions.addObject(submission)
this.updateSubmission(submission, student)
this.calculateStudentGrade(student)
if (
selected &&
selected.assignment_id === submission.assignment_id &&
selected.user_id === submission.user_id
) {
set(this, 'selectedSubmission', submission)
}
})
},
updateAssignmentVisibilities(assignment, userId) {
const visibilities = get(assignment, 'assignment_visibility')
const filteredVisibilities =
visibilities != null ? visibilities.filter(id => id !== userId) : undefined
return set(assignment, 'assignment_visibility', filteredVisibilities)
},
subtotalByGradingPeriod() {
const selectedPeriodID = this.get('selectedGradingPeriod.id')
return selectedPeriodID && selectedPeriodID === '0' && this.periodsAreWeighted()
},
calculate(student) {
const submissions = this.submissionsForStudent(student)
const assignmentGroups = this.assignmentGroupsHash()
const weightingScheme = this.get('weightingScheme')
const gradingPeriodSet = this.getGradingPeriodSet()
const effectiveDueDates = this.get('effectiveDueDates.content')
const hasGradingPeriods = gradingPeriodSet && effectiveDueDates
return CourseGradeCalculator.calculate(
submissions,
assignmentGroups,
weightingScheme,
hasGradingPeriods ? gradingPeriodSet : undefined,
hasGradingPeriods ? scopeToUser(effectiveDueDates, student.id) : undefined
)
},
submissionsForStudent(student) {
const allSubmissions = (() => {
const result = []
for (const key in student) {
const value = student[key]
if (key.match(/^assignment_(?!group)/)) {
result.push(value)
}
}
return result
})()
if (!this.get('has_grading_periods')) {
return allSubmissions
}
const selectedPeriodID = this.get('selectedGradingPeriod.id')
if (!selectedPeriodID || selectedPeriodID === '0') {
return allSubmissions
}
return _.filter(allSubmissions, submission => {
const studentPeriodInfo = __guard__(
this.get('effectiveDueDates').get(submission.assignment_id),
x => x[submission.user_id]
)
return studentPeriodInfo && studentPeriodInfo.grading_period_id === selectedPeriodID
})
},
calculateSingleGrade(student, key, gradeFinalOrCurrent) {
set(student, key, gradeFinalOrCurrent)
if (gradeFinalOrCurrent != null ? gradeFinalOrCurrent.submissions : undefined) {
return Array.from(gradeFinalOrCurrent.submissions).map(submissionData =>
set(submissionData.submission, 'drop', submissionData.drop)
)
}
},
calculateStudentGrade(student) {
if (student.isLoaded) {
let grade
let grades = this.calculate(student)
const selectedPeriodID = this.get('selectedGradingPeriod.id')
if (selectedPeriodID && selectedPeriodID !== '0') {
grades = grades.gradingPeriods[selectedPeriodID]
}
const finalOrCurrent = this.get('includeUngradedAssignments') ? 'final' : 'current'
if (this.subtotalByGradingPeriod()) {
for (const gradingPeriodId in grades.gradingPeriods) {
grade = grades.gradingPeriods[gradingPeriodId]
this.calculateSingleGrade(
student,
`grading_period_${gradingPeriodId}`,
grade[finalOrCurrent]
)
}
} else {
for (const assignmentGroupId in grades.assignmentGroups) {
grade = grades.assignmentGroups[assignmentGroupId]
this.calculateSingleGrade(
student,
`assignment_group_${assignmentGroupId}`,
grade[finalOrCurrent]
)
}
}
grades = grades[finalOrCurrent]
let percent = round((grades.score / grades.possible) * 100, 2)
if (isNaN(percent)) {
percent = 0
}
return setProperties(student, {
total_grade: grades,
total_percent: percent
})
}
},
calculateAllGrades: function() {
return this.get('students').forEach(student => this.calculateStudentGrade(student))
}.observes(
'includeUngradedAssignments',
'groupsAreWeighted',
'assignment_groups.@each.group_weight',
'selectedGradingPeriod',
'gradingPeriods.@each.weight'
),
sectionSelectDefaultLabel: I18n.t('all_sections', 'All Sections'),
studentSelectDefaultLabel: I18n.t('no_student', 'No Student Selected'),
assignmentSelectDefaultLabel: I18n.t('no_assignment', 'No Assignment Selected'),
outcomeSelectDefaultLabel: I18n.t('no_outcome', 'No Outcome Selected'),
submissionStateMap: null,
assignment_groups: [],
assignment_subtotals: [],
subtotal_by_period: false,
fetchAssignmentGroups: function() {
const params = {exclude_response_fields: ['in_closed_grading_period']}
const gpId = this.get('selectedGradingPeriod.id')
if (this.get('has_grading_periods') && gpId !== '0') {
params.grading_period_id = gpId
}
this.set('assignment_groups', [])
this.get('assignmentsFromGroups').setProperties({content: [], isLoaded: false})
return Ember.run.once(() =>
fetchAllPages(get(window, 'ENV.GRADEBOOK_OPTIONS.assignment_groups_url'), {
data: params,
records: this.get('assignment_groups')
})
)
}
.observes('selectedGradingPeriod')
.on('init'),
pushAssignmentGroups(subtotals) {
this.set('subtotal_by_period', false)
const weighted = this.get('groupsAreWeighted')
return (() => {
const result = []
for (const group of Array.from(this.get('assignment_groups'))) {
const subtotal = {
name: group.name,
key: `assignment_group_${group.id}`,
weight: weighted && group.group_weight
}
result.push(subtotals.push(subtotal))
}
return result
})()
},
pushGradingPeriods(subtotals) {
this.set('subtotal_by_period', true)
const weighted = this.periodsAreWeighted()
return (() => {
const result = []
for (const period of Array.from(this.get('gradingPeriods'))) {
if (period.id > 0) {
const subtotal = {
name: period.title,
key: `grading_period_${period.id}`,
weight: weighted && period.weight
}
result.push(subtotals.push(subtotal))
} else {
result.push(undefined)
}
}
return result
})()
},
assignmentSubtotals: function() {
const subtotals = []
if (this.subtotalByGradingPeriod()) {
this.pushGradingPeriods(subtotals)
} else {
this.pushAssignmentGroups(subtotals)
}
return this.set('assignment_subtotals', subtotals)
}
.observes(
'assignment_groups',
'gradingPeriods',
'selectedGradingPeriod',
'students.@each',
'selectedStudent'
)
.on('init'),
students: studentsUniqByEnrollments('enrollments'),
studentsHash() {
const students = {}
this.get('students').forEach(s => {
if (s.role !== 'StudentViewEnrollment') {
students[s.id] = s
}
})
return students
},
processLoadingSubmissions(submissionGroups) {
const submissions = []
_.forEach(submissionGroups, submissionGroup => {
submissions.push(...Array.from(submissionGroup.submissions || []))
})
this.updateEffectiveDueDatesFromSubmissions(submissions)
const assignmentIds = _.uniq(_.pluck(submissions, 'assignment_id'))
const assignmentMap = _.keyBy(this.get('assignmentsFromGroups.content'), 'id')
assignmentIds.forEach(assignmentId => {
const assignment = assignmentMap[assignmentId]
if (assignment) {
this.updateEffectiveDueDatesOnAssignment(assignment)
}
})
return submissionGroups
},
fetchStudentSubmissions: function() {
return Ember.run.once(() => {
const notYetLoaded = this.get('students').filter(student => {
if (get(student, 'isLoaded') || get(student, 'isLoading')) {
return false
}
set(student, 'isLoading', true)
return student
})
if (!notYetLoaded.length) {
return
}
const studentIds = notYetLoaded.mapBy('id')
while (studentIds.length) {
const chunk = studentIds.splice(0, ENV.GRADEBOOK_OPTIONS.chunk_size || 20)
fetchAllPages(ENV.GRADEBOOK_OPTIONS.submissions_url, {
data: {student_ids: chunk},
process: submissions => this.processLoadingSubmissions(submissions),
records: this.get('submissions')
})
}
})
}
.observes('students.@each', 'selectedGradingPeriod')
.on('init'),
showNotesColumn: function() {
const notes = this.get('teacherNotes')
if (notes) {
return !notes.hidden
} else {
return false
}
}
.property()
.volatile(),
shouldCreateNotes: function() {
return !this.get('teacherNotes') && this.get('showNotesColumn')
}.property('teacherNotes', 'showNotesColumn', 'custom_columns.@each'),
notesURL: function() {
if (this.get('shouldCreateNotes')) {
return window.ENV.GRADEBOOK_OPTIONS.custom_columns_url
} else {
const notesID = __guard__(this.get('teacherNotes'), x => x.id)
return window.ENV.GRADEBOOK_OPTIONS.custom_column_url.replace(/:id/, notesID)
}
}.property('shouldCreateNotes', 'custom_columns.@each'),
notesParams: function() {
if (this.get('shouldCreateNotes')) {
return {
'column[title]': I18n.t('notes', 'Notes'),
'column[position]': 1,
'column[teacher_notes]': true
}
} else {
return {'column[hidden]': !this.get('showNotesColumn')}
}
}.property('shouldCreateNotes', 'showNotesColumn'),
notesVerb: function() {
if (this.get('shouldCreateNotes')) {
return 'POST'
} else {
return 'PUT'
}
}.property('shouldCreateNotes'),
updateOrCreateNotesColumn: function() {
return ajax
.request({
dataType: 'json',
type: this.get('notesVerb'),
url: this.get('notesURL'),
data: this.get('notesParams')
})
.then(this.boundNotesSuccess)
}.observes('showNotesColumn'),
bindNotesSuccess: function() {
return (this.boundNotesSuccess = this.onNotesUpdateSuccess.bind(this))
}.on('init'),
onNotesUpdateSuccess(col) {
const customColumns = this.get('custom_columns')
const method = col.hidden ? 'removeObject' : 'unshiftObject'
const column = customColumns.findBy('id', col.id) || col
customColumns[method](column)
if (col.teacher_notes) {
this.set('teacherNotes', col)
}
if (!col.hidden) {
return ajax.request({
url: ENV.GRADEBOOK_OPTIONS.reorder_custom_columns_url,
type: 'POST',
data: {
order: customColumns.mapBy('id')
}
})
}
},
groupsAreWeighted: function() {
return this.get('weightingScheme') === 'percent'
}.property('weightingScheme'),
periodsAreWeighted() {
return !!__guard__(this.getGradingPeriodSet(), x => x.weighted)
},
gradesAreWeighted: function() {
return this.get('groupsAreWeighted') || this.periodsAreWeighted()
}.property('weightingScheme'),
hidePointsPossibleForFinalGrade: function() {
return !!(this.get('groupsAreWeighted') || this.subtotalByGradingPeriod())
}.property('weightingScheme', 'selectedGradingPeriod'),
updateShowTotalAs: function() {
this.set('showTotalAsPoints', this.get('showTotalAsPoints'))
return ajax.request({
dataType: 'json',
type: 'PUT',
url: ENV.GRADEBOOK_OPTIONS.setting_update_url,
data: {
show_total_grade_as_points: this.get('showTotalAsPoints')
}
})
}.observes('showTotalAsPoints', 'gradesAreWeighted'),
studentColumnData: {},
updateColumnData(columnDatum, columnID) {
const studentData = this.get('studentColumnData')
const dataForStudent = studentData[columnDatum.user_id] || Ember.A()
const columnForStudent = dataForStudent.findBy('column_id', columnID)
if (columnForStudent) {
columnForStudent.set('content', columnDatum.content)
} else {
dataForStudent.push(
Ember.Object.create({
column_id: columnID,
content: columnDatum.content
})
)
}
return (studentData[columnDatum.user_id] = dataForStudent)
},
fetchColumnData(col, url) {
if (!url) {
url = ENV.GRADEBOOK_OPTIONS.custom_column_data_url.replace(/:id/, col.id)
}
return ajax.raw(url, {dataType: 'json'}).then(result => {
for (const datum of Array.from(result.response)) {
this.updateColumnData(datum, col.id)
}
const meta = parseLinkHeader(result.jqXHR)
if (meta.next) {
return this.fetchColumnData(col, meta.next)
} else {
return setProperties(col, {
isLoading: false,
isLoaded: true
})
}
})
},
dataForStudent: function() {
const selectedStudent = this.get('selectedStudent')
if (selectedStudent == null) {
return
}
return this.get('studentColumnData')[selectedStudent.id]
}.property('selectedStudent', 'custom_columns.@each.isLoaded'),
loadCustomColumnData: function() {
if (!this.get('enrollments.isLoaded')) {
return
}
return this.get('custom_columns')
.filter(col => {
if (get(col, 'isLoaded') || get(col, 'isLoading')) {
return false
}
set(col, 'isLoading', true)
return col
})
.forEach(col => this.fetchColumnData(col))
}.observes('enrollments.isLoaded', 'custom_columns.@each'),
studentsInSelectedSection: function() {
const students = this.get('students')
const currentSection = this.get('selectedSection')
if (!currentSection) {
return students
}
return students.filter(s => s.sections.contains(currentSection.id))
}.property('students.@each', 'selectedSection'),
groupById(array) {
return array.reduce((obj, item) => {
obj[get(item, 'id')] = item
return obj
}, {})
},
submissionsLoaded: function() {
const assignments = this.get('assignmentsFromGroups')
const assignmentsByID = this.groupById(assignments)
const studentsByID = this.groupById(this.get('students'))
const submissions = this.get('submissions') || []
submissions.forEach(function(submission) {
const student = studentsByID[submission.user_id]
if (student) {
submission.submissions.forEach(function(s) {
const assignment = assignmentsByID[s.assignment_id]
set(s, 'hidden', !this.differentiatedAssignmentVisibleToStudent(assignment, s.user_id))
return this.updateSubmission(s, student)
}, this)
// fill in hidden ones
assignments.forEach(function(a) {
if (!this.differentiatedAssignmentVisibleToStudent(a, student.id)) {
const sub = {
user_id: student.id,
assignment_id: a.id,
hidden: true
}
return this.updateSubmission(sub, student)
}
}, this)
setProperties(student, {
isLoading: false,
isLoaded: true
})
this.calculateStudentGrade(student)
}
}, this)
}.observes('submissions.@each', 'assignmentsFromGroups.isLoaded'),
updateSubmission(submission, student) {
submission.submitted_at = tz.parse(submission.submitted_at)
return set(student, `assignment_${submission.assignment_id}`, submission)
},
updateEffectiveDueDatesOnAssignment(assignment) {
assignment.effectiveDueDates = this.get('effectiveDueDates.content')[assignment.id] || {}
return (assignment.inClosedGradingPeriod = _.some(
assignment.effectiveDueDates,
date => date.in_closed_grading_period
))
},
updateEffectiveDueDatesFromSubmissions(submissions) {
const effectiveDueDates = this.get('effectiveDueDates.content')
const gradingPeriods = __guard__(this.getGradingPeriodSet(), x => x.gradingPeriods)
updateWithSubmissions(effectiveDueDates, submissions, gradingPeriods)
return this.set('effectiveDueDates.content', effectiveDueDates)
},
assignments: Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
content: [],
sortProperties: ['ag_position', 'position']
}),
processAssignment(as, assignmentGroups) {
const assignmentGroup = assignmentGroups.findBy('id', as.assignment_group_id)
set(as, 'sortable_name', as.name.toLowerCase())
set(as, 'ag_position', assignmentGroup.position)
set(as, 'noPointsPossibleWarning', assignmentGroup.invalid)
this.updateEffectiveDueDatesOnAssignment(as)
if (as.due_at) {
const due_at = tz.parse(as.due_at)
set(as, 'due_at', due_at)
return set(as, 'sortable_date', +due_at / 1000)
} else {
return set(as, 'sortable_date', Number.MAX_VALUE)
}
},
differentiatedAssignmentVisibleToStudent(assignment, student_id) {
if (assignment == null) {
return false
}
if (!assignment.only_visible_to_overrides) {
return true
}
return _.includes(assignment.assignment_visibility, student_id)
},
studentsThatCanSeeAssignment(assignment) {
const students = this.studentsHash()
if (!(assignment != null ? assignment.only_visible_to_overrides : undefined)) {
return students
}
return assignment.assignment_visibility.reduce((result, id) => {
result[id] = students[id]
return result
}, {})
},
checkForNoPointsWarning(ag) {
const pointsPossible = _.reduce(ag.assignments, (sum, a) => sum + (a.points_possible || 0), 0)
return pointsPossible === 0
},
checkForInvalidGroups: function() {
return this.get('assignment_groups').forEach(ag =>
set(ag, 'invalid', this.checkForNoPointsWarning(ag))
)
}.observes('assignment_groups.@each'),
invalidAssignmentGroups: function() {
return this.get('assignment_groups').filterProperty('invalid', true)
}.property('assignment_groups.@each.invalid'),
showInvalidGroupWarning: function() {
return (
this.get('invalidAssignmentGroups').length > 0 && this.get('weightingScheme') === 'percent'
)
}.property('invalidAssignmentGroups', 'weightingScheme'),
invalidGroupNames: function() {
let names
return (names = this.get('invalidAssignmentGroups').map(group => group.name))
}
.property('invalidAssignmentGroups')
.readOnly(),
invalidGroupsWarningPhrases: function() {
return I18n.t(
'invalid_group_warning',
{
one:
'Note: Score does not include assignments from the group %{list_of_group_names} because it has no points possible.',
other:
'Note: Score does not include assignments from the groups %{list_of_group_names} because they have no points possible.'
},
{
count: this.get('invalidGroupNames').length,
list_of_group_names: this.get('invalidGroupNames').join(' or ')
}
)
}.property('invalidGroupNames'),
populateAssignmentsFromGroups: function() {
if (!this.get('assignment_groups.isLoaded') || !!this.get('assignment_groups.isLoading')) {
return
}
const assignmentGroups = this.get('assignment_groups')
const assignments = _.flatten(assignmentGroups.mapBy('assignments'))
const assignmentList = []
assignments.forEach(as => {
this.processAssignment(as, assignmentGroups)
const shouldRemoveAssignment =
as.published === false ||
as.submission_types.contains(
'not_graded' || as.submission_types.contains('attendance' && !this.get('showAttendance'))
)
if (shouldRemoveAssignment) {
return assignmentGroups.findBy('id', as.assignment_group_id).assignments.removeObject(as)
} else {
return assignmentList.push(as)
}
})
return this.get('assignmentsFromGroups').setProperties({
content: assignmentList,
isLoaded: true
})
}.observes('assignment_groups.isLoaded', 'assignment_groups.isLoading'),
populateAssignments: function() {
const assignmentsFromGroups = this.get('assignmentsFromGroups.content')
const selectedStudent = this.get('selectedStudent')
const submissionStateMap = this.get('submissionStateMap')
const proxy = Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {content: []})
if (selectedStudent) {
assignmentsFromGroups.forEach(assignment => {
const submissionCriteria = {assignment_id: assignment.id, user_id: selectedStudent.id}
if (
!__guard__(
submissionStateMap != null
? submissionStateMap.getSubmissionState(submissionCriteria)
: undefined,
x => x.hideGrade
)
) {
return proxy.addObject(assignment)
}
})
} else {
proxy.addObjects(assignmentsFromGroups)
}
proxy.set('sortProperties', this.get('assignments.sortProperties'))
this.set('assignments', proxy)
}.observes('assignmentsFromGroups.isLoaded', 'selectedStudent'),
populateSubmissionStateMap: function() {
const map = new SubmissionStateMap({
hasGradingPeriods: !!this.has_grading_periods,
selectedGradingPeriodID: this.get('selectedGradingPeriod.id') || '0',
isAdmin: ENV.current_user_roles && _.includes(ENV.current_user_roles, 'admin')
})
map.setup(this.get('students').toArray(), this.get('assignmentsFromGroups.content').toArray())
this.set('submissionStateMap', map)
}.observes(
'enrollments.isLoaded',
'assignmentsFromGroups.isLoaded',
'submissions.content.length'
),
includeUngradedAssignments: (() =>
userSettings.contextGet('include_ungraded_assignments') || false)
.property()
.volatile(),
showAttendance: (() => userSettings.contextGet('show_attendance')).property().volatile(),
updateIncludeUngradedAssignmentsSetting: function() {
userSettings.contextSet('include_ungraded_assignments', this.get('includeUngradedAssignments'))
}.observes('includeUngradedAssignments'),
assignmentGroupsHash() {
const ags = {}
if (!this.get('assignment_groups')) {
return ags
}
this.get('assignment_groups').forEach(ag => (ags[ag.id] = ag))
return ags
},
assignmentSortOptions: [
{
label: I18n.t('assignment_order_assignment_groups', 'By Assignment Group and Position'),
value: 'assignment_group'
},
{
label: I18n.t('assignment_order_alpha', 'Alphabetically'),
value: 'alpha'
},
{
label: I18n.t('assignment_order_due_date', 'By Due Date'),
value: 'due_date'
}
],
assignmentSort: function(key, value) {
const savedSortType = userSettings.contextGet('sort_grade_columns_by')
const savedSortOption = this.get('assignmentSortOptions').findBy(
'value',
savedSortType != null ? savedSortType.sortType : undefined
)
if (value) {
userSettings.contextSet('sort_grade_columns_by', {sortType: value.value})
return value
} else if (savedSortOption) {
return savedSortOption
} else {
// default to assignment group, but don't change saved setting
return this.get('assignmentSortOptions').findBy('value', 'assignment_group')
}
}.property(),
sortAssignments: function() {
const sort = this.get('assignmentSort')
if (!sort) {
return
}
const sort_props = (() => {
switch (sort.value) {
case 'assignment_group':
case 'custom':
return ['ag_position', 'position']
case 'alpha':
return ['sortable_name']
case 'due_date':
return ['sortable_date', 'sortable_name']
default:
return ['ag_position', 'position']
}
})()
return this.get('assignments').set('sortProperties', sort_props)
}
.observes('assignmentSort')
.on('init'),
updateAssignmentStatusInGradingPeriod: function() {
const assignment = this.get('selectedAssignment')
if (!assignment) {
this.set('assignmentInClosedGradingPeriod', null)
this.set('disableAssignmentGrading', null)
return
}
this.set('assignmentInClosedGradingPeriod', assignment.inClosedGradingPeriod)
// Calculate whether the current user is able to grade assignments given their role and the
// result of the calculations above
if (ENV.current_user_roles != null && _.includes(ENV.current_user_roles, 'admin')) {
this.set('disableAssignmentGrading', false)
} else {
this.set('disableAssignmentGrading', assignment.inClosedGradingPeriod)
}
}.observes('selectedAssignment'),
selectedSubmission: function(key, selectedSubmission) {
if (arguments.length > 1) {
this.set('selectedStudent', this.get('students').findBy('id', selectedSubmission.user_id))
this.set(
'selectedAssignment',
this.get('assignments').findBy('id', selectedSubmission.assignment_id)
)
} else {
if (this.get('selectedStudent') == null || this.get('selectedAssignment') == null) {
return null
}
const student = this.get('selectedStudent')
const assignment = this.get('selectedAssignment')
const sub = get(student, `assignment_${assignment.id}`)
selectedSubmission = sub || {
user_id: student.id,
assignment_id: assignment.id,
hidden: !this.differentiatedAssignmentVisibleToStudent(assignment, student.id),
grade_matches_current_submission: true
}
}
const submissionState =
(this.submissionStateMap != null
? this.submissionStateMap.getSubmissionState(selectedSubmission)
: undefined) || {}
selectedSubmission.gradeLocked = submissionState.locked
return selectedSubmission
}.property('selectedStudent', 'selectedAssignment'),
selectedSubmissionHidden: function() {
return this.get('selectedSubmission.hidden') || false
}.property('selectedStudent', 'selectedAssignment'),
anonymizeStudents: function() {
return this.get('selectedAssignment.anonymize_students')
}.property('selectedAssignment'),
selectedSubmissionLate: function() {
return (this.get('selectedSubmission.points_deducted') || 0) > 0
}.property('selectedStudent', 'selectedAssignment'),
selectedOutcomeResult: function() {
if (this.get('selectedStudent') == null || this.get('selectedOutcome') == null) {
return null
}
const student = this.get('selectedStudent')
const outcome = this.get('selectedOutcome')
const result = this.get('outcome_rollups').find(
x => x.user_id === student.id && x.outcome_id === outcome.id
)
if (result) {
result.mastery_points = round(outcome.mastery_points, 2)
}
return (
result || {
user_id: student.id,
outcome_id: outcome.id
}
)
}.property('selectedStudent', 'selectedOutcome'),
outcomeResultIsDefined: function() {
return __guard__(this.get('selectedOutcomeResult'), x => x.score) != null
}.property('selectedOutcomeResult'),
showAssignmentPointsWarning: function() {
return this.get('selectedAssignment.noPointsPossibleWarning') && this.get('groupsAreWeighted')
}.property('selectedAssignment', 'groupsAreWeighted'),
selectedStudentSections: function() {
const student = this.get('selectedStudent')
const sections = this.get('sections')
if (!sections.isLoaded || student == null) {
return null
}
const sectionNames = student.sections.map(id => sections.findBy('id', id).name)
return sectionNames.join(', ')
}.property('selectedStudent', 'sections.isLoaded'),
assignmentDetails: function() {
if (this.get('selectedAssignment') == null) {
return null
}
const {locals} = AssignmentDetailsDialog.prototype.compute.call(
AssignmentDetailsDialog.prototype,
{
students: this.studentsHash(),
assignment: this.get('selectedAssignment')
}
)
return locals
}.property('selectedAssignment', 'students.@each.total_grade'),
outcomeDetails: function() {
let details
if (this.get('selectedOutcome') == null) {
return null
}
const rollups = this.get('outcome_rollups').filterBy(
'outcome_id',
this.get('selectedOutcome').id
)
const scores = _.filter(_.pluck(rollups, 'score'), _.isNumber)
return (details = {
average: outcomeGrid.Math.mean(scores),
max: outcomeGrid.Math.max(scores),
min: outcomeGrid.Math.min(scores),
cnt: outcomeGrid.Math.cnt(scores)
})
}.property('selectedOutcome', 'outcome_rollups'),
calculationDetails: function() {
if (this.get('selectedOutcome') == null) {
return null
}
const outcome = this.get('selectedOutcome')
return _.extend(
{
calculation_method: outcome.calculation_method,
calculation_int: outcome.calculation_int
},
new CalculationMethodContent(outcome).present()
)
}.property('selectedOutcome'),
assignmentSubmissionTypes: function() {
const types = this.get('selectedAssignment.submission_types')
const submissionTypes = this.get('submissionTypes')
if (types === undefined || types.length === 0) {
return submissionTypes.none
} else if (types.length === 1) {
return submissionTypes[types[0]]
} else {
const result = []
types.forEach(type => result.push(submissionTypes[type]))
return result.join(', ')
}
}.property('selectedAssignment'),
submissionTypes: {
discussion_topic: I18n.t('discussion_topic', 'Discussion topic'),
online_quiz: I18n.t('online_quiz', 'Online quiz'),
on_paper: I18n.t('on_paper', 'On paper'),
none: I18n.t('none', 'None'),
external_tool: I18n.t('external_tool', 'External tool'),
online_text_entry: I18n.t('online_text_entry', 'Online text entry'),
online_url: I18n.t('online_url', 'Online URL'),
online_upload: I18n.t('online_upload', 'Online upload'),
media_recording: I18n.t('media_recordin', 'Media recording')
},
assignmentIndex: function() {
const selected = this.get('selectedAssignment')
if (selected) {
return this.get('assignments').indexOf(selected)
} else {
return -1
}
}.property('selectedAssignment', 'assignmentSort'),
studentIndex: function() {
const selected = this.get('selectedStudent')
if (selected) {
return this.get('studentsInSelectedSection').indexOf(selected)
} else {
return -1
}
}.property('selectedStudent', 'selectedSection'),
outcomeIndex: function() {
const selected = this.get('selectedOutcome')
if (selected) {
return this.get('outcomes').indexOf(selected)
} else {
return -1
}
}.property('selectedOutcome'),
displayName: function() {
if (this.get('hideStudentNames')) {
return 'hiddenName'
} else if (ENV.GRADEBOOK_OPTIONS.list_students_by_sortable_name_enabled) {
return 'sortable_name'
} else {
return 'name'
}
}.property('hideStudentNames'),
fetchCorrectEnrollments: function() {
let url
if (this.get('enrollments.isLoading')) {
return
}
if (this.get('showConcludedEnrollments')) {
url = ENV.GRADEBOOK_OPTIONS.enrollments_with_concluded_url
} else {
url = ENV.GRADEBOOK_OPTIONS.enrollments_url
}
const enrollments = this.get('enrollments')
enrollments.clear()
return fetchAllPages(url, {records: enrollments})
}.observes('showConcludedEnrollments'),
omitFromFinalGrade: function() {
return this.get('selectedAssignment.omit_from_final_grade')
}.property('selectedAssignment')
})
export default ScreenreaderGradebookController
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null ? transform(value) : undefined
}
|
src/components/Image/index.js | d-amit/in-di-go | import React from 'react';
export default class Image extends React.Component {
render() {
let {mode, src, height, width, style, ...props} = this.props;
let modes = {
'fill': 'cover',
'fit': 'contain'
};
let size = modes[mode] || 'contain';
let defaults = {
height: height || 100,
width: width || 100,
};
let important = {
backgroundImage: `url("${src}")`,
backgroundSize: size,
backgroundPosition: 'center center',
backgroundRepeat: 'no-repeat'
};
return <div {...props} style={{...defaults, ...style, ...important}} />
}
}
|
server/server.js | GTDev87/stylizer | import Express from 'express';
import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
import IntlWrapper from '../client/modules/Intl/IntlWrapper';
// Webpack Requirements
import webpack from 'webpack';
import config from '../webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
// Initialize the Express App
const app = new Express();
// Run Webpack dev server in development mode
if (process.env.NODE_ENV === 'development') {
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
}
// React And Redux Setup
import { configureStore } from '../client/store';
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import Helmet from 'react-helmet';
// Import required modules
import routes from '../client/routes';
import { fetchComponentData } from './util/fetchData';
import posts from './routes/post.routes';
import dummyData from './dummyData';
import serverConfig from './config';
// Set native promises as mongoose promise
mongoose.Promise = global.Promise;
// MongoDB Connection
mongoose.connect(serverConfig.mongoURL, (error) => {
if (error) {
console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console
throw error;
}
// feed some dummy data in DB.
dummyData();
});
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../dist')));
app.use('/api', posts);
// Render Initial HTML
const renderFullPage = (html, initialState) => {
const head = Helmet.rewind();
// Import Manifests
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets);
const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets);
return `
<!doctype html>
<html>
<head>
${head.base.toString()}
${head.title.toString()}
${head.meta.toString()}
${head.link.toString()}
${head.script.toString()}
${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''}
<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/>
<link href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.0.0/codemirror.min.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.0.0/theme/monokai.min.css" rel="stylesheet"/>
<link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" />
</head>
<body>
<div id="root">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
${process.env.NODE_ENV === 'production' ?
`//<![CDATA[
window.webpackManifest = ${JSON.stringify(chunkManifest)};
//]]>` : ''}
</script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script>
</body>
</html>
`;
};
const renderError = err => {
const softTab = '    ';
const errTrace = process.env.NODE_ENV !== 'production' ?
`:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : '';
return renderFullPage(`Server Error${errTrace}`, {});
};
// Server Side Rendering based on routes matched by React-router.
app.use((req, res, next) => {
match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
if (err) {
return res.status(500).end(renderError(err));
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
if (!renderProps) {
return next();
}
const store = configureStore();
return fetchComponentData(store, renderProps.components, renderProps.params)
.then(() => {
const initialView = renderToString(
<Provider store={store}>
<IntlWrapper>
<RouterContext {...renderProps} />
</IntlWrapper>
</Provider>
);
const finalState = store.getState();
res
.set('Content-Type', 'text/html')
.status(200)
.end(renderFullPage(initialView, finalState));
})
.catch((error) => next(error));
});
});
// start app
app.listen(serverConfig.port, (error) => {
if (!error) {
console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line
}
});
export default app;
|
app/javascript/mastodon/features/ui/components/upload_area.js | Toootim/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Motion from 'react-motion/lib/Motion';
import spring from 'react-motion/lib/spring';
import { FormattedMessage } from 'react-intl';
export default class UploadArea extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
onClose: PropTypes.func,
};
handleKeyUp = (e) => {
e.preventDefault();
e.stopPropagation();
const keyCode = e.keyCode;
if (this.props.active) {
switch(keyCode) {
case 27:
this.props.onClose();
break;
}
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
}
render () {
const { active } = this.props;
return (
<Motion defaultStyle={{ backgroundOpacity: 0, backgroundScale: 0.95 }} style={{ backgroundOpacity: spring(active ? 1 : 0, { stiffness: 150, damping: 15 }), backgroundScale: spring(active ? 1 : 0.95, { stiffness: 200, damping: 3 }) }}>
{({ backgroundOpacity, backgroundScale }) =>
<div className='upload-area' style={{ visibility: active ? 'visible' : 'hidden', opacity: backgroundOpacity }}>
<div className='upload-area__drop'>
<div className='upload-area__background' style={{ transform: `translateZ(0) scale(${backgroundScale})` }} />
<div className='upload-area__content'><FormattedMessage id='upload_area.title' defaultMessage='Drag & drop to upload' /></div>
</div>
</div>
}
</Motion>
);
}
}
|
actor-apps/app-web/src/app/components/activity/GroupProfile.react.js | cnbin/actor-platform | import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import ReactZeroClipboard from 'react-zeroclipboard';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, Snackbar } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import classnames from 'classnames';
//import { Experiment, Variant } from 'react-ab';
//import mixpanel from 'utils/Mixpanel';
import DialogActionCreators from 'actions/DialogActionCreators';
import GroupProfileActionCreators from 'actions/GroupProfileActionCreators';
import LoginStore from 'stores/LoginStore';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import GroupStore from 'stores/GroupStore';
import InviteUserActions from 'actions/InviteUserActions';
import AvatarItem from 'components/common/AvatarItem.react';
import InviteUser from 'components/modals/InviteUser.react';
import InviteByLink from 'components/modals/invite-user/InviteByLink.react';
import GroupProfileMembers from 'components/activity/GroupProfileMembers.react';
import Fold from 'components/common/Fold.React';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = (groupId) => {
const thisPeer = PeerStore.getGroupPeer(groupId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer),
integrationToken: GroupStore.getIntegrationToken()
};
};
@ReactMixin.decorate(IntlMixin)
class GroupProfile extends React.Component {
static propTypes = {
group: React.PropTypes.object.isRequired
};
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = _.assign({
isMoreDropdownOpen: false
}, getStateFromStores(props.group.id));
ThemeManager.setTheme(ActorTheme);
DialogStore.addNotificationsListener(this.onChange);
GroupStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.onChange);
GroupStore.addChangeListener(this.onChange);
}
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.group.id));
}
onAddMemberClick = group => {
InviteUserActions.show(group);
};
onLeaveGroupClick = groupId => {
DialogActionCreators.leaveGroup(groupId);
};
onNotificationChange = event => {
DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked);
};
onChange = () => {
this.setState(getStateFromStores(this.props.group.id));
};
selectToken = (event) => {
event.target.select();
};
onIntegrationTokenCopied = () => {
this.refs.integrationTokenCopied.show();
};
toggleMoreDropdown = () => {
const isMoreDropdownOpen = this.state.isMoreDropdownOpen;
if (!isMoreDropdownOpen) {
this.setState({isMoreDropdownOpen: true});
document.addEventListener('click', this.closeMoreDropdown, false);
} else {
this.closeMoreDropdown();
}
};
closeMoreDropdown = () => {
this.setState({isMoreDropdownOpen: false});
document.removeEventListener('click', this.closeMoreDropdown, false);
};
render() {
const group = this.props.group;
const myId = LoginStore.getMyId();
const isNotificationsEnabled = this.state.isNotificationsEnabled;
const integrationToken = this.state.integrationToken;
const admin = GroupProfileActionCreators.getUser(group.adminId);
const isMember = DialogStore.isGroupMember(group);
const snackbarStyles = ActorTheme.getSnackbarStyles();
let adminControls;
if (group.adminId === myId) {
adminControls = [
<li className="dropdown__menu__item hide">
<i className="material-icons">photo_camera</i>
<FormattedMessage message={this.getIntlMessage('setGroupPhoto')}/>
</li>
,
<li className="dropdown__menu__item hide">
<svg className="icon icon--dropdown"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#integration"/>'}}/>
<FormattedMessage message={this.getIntlMessage('addIntegration')}/>
</li>
,
<li className="dropdown__menu__item hide">
<i className="material-icons">mode_edit</i>
<FormattedMessage message={this.getIntlMessage('editGroup')}/>
</li>
,
<li className="dropdown__menu__item hide">
<FormattedMessage message={this.getIntlMessage('deleteGroup')}/>
</li>
];
}
let members = <FormattedMessage message={this.getIntlMessage('members')} numMembers={group.members.length}/>;
let dropdownClassNames = classnames('dropdown pull-right', {
'dropdown--opened': this.state.isMoreDropdownOpen
});
const iconElement = (
<svg className="icon icon--green"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#members"/>'}}/>
);
const groupMeta = [
<header>
<AvatarItem image={group.bigAvatar}
placeholder={group.placeholder}
size="big"
title={group.name}/>
<h3 className="group_profile__meta__title">{group.name}</h3>
<div className="group_profile__meta__created">
<FormattedMessage admin={admin.name} message={this.getIntlMessage('createdBy')}/>
</div>
</header>
,
<div className="group_profile__meta__description hide">
Description here
</div>
];
if (isMember) {
return (
<div className="activity__body group_profile">
<ul className="profile__list">
<li className="profile__list__item group_profile__meta">
{groupMeta}
<footer>
<button className="button button--light-blue pull-left"
onClick={this.onAddMemberClick.bind(this, group)}>
<i className="material-icons">person_add</i>
<FormattedMessage message={this.getIntlMessage('addPeople')}/>
</button>
<div className={dropdownClassNames}>
<button className="dropdown__button button button--light-blue" onClick={this.toggleMoreDropdown}>
<i className="material-icons">more_horiz</i>
<FormattedMessage message={this.getIntlMessage('more')}/>
</button>
<ul className="dropdown__menu dropdown__menu--right">
{adminControls}
<li className="dropdown__menu__item dropdown__menu__item--light"
onClick={this.onLeaveGroupClick.bind(this, group.id)}>
<FormattedMessage message={this.getIntlMessage('leaveGroup')}/>
</li>
</ul>
</div>
</footer>
</li>
<li className="profile__list__item group_profile__media no-p hide">
<Fold icon="attach_file" iconClassName="icon--gray" title={this.getIntlMessage('sharedMedia')}>
<ul>
<li><a>230 Shared Photos and Videos</a></li>
<li><a>49 Shared Links</a></li>
<li><a>49 Shared Files</a></li>
</ul>
</Fold>
</li>
<li className="profile__list__item group_profile__notifications no-p">
<label htmlFor="notifications">
<i className="material-icons icon icon--squash">notifications_none</i>
<FormattedMessage message={this.getIntlMessage('notifications')}/>
<div className="switch pull-right">
<input checked={isNotificationsEnabled}
id="notifications"
onChange={this.onNotificationChange}
type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</label>
</li>
<li className="profile__list__item group_profile__members no-p">
<Fold iconElement={iconElement}
title={members}>
<GroupProfileMembers groupId={group.id} members={group.members}/>
</Fold>
</li>
<li className="profile__list__item group_profile__integration no-p">
<Fold icon="power" iconClassName="icon--pink" title="Integration Token">
<div className="info info--light">
If you have programming chops, or know someone who does,
this integration token allow the most flexibility and communication
with your own systems.
<a href="https://actor.readme.io/docs/simple-integration" target="_blank">Learn how to integrate</a>
<ReactZeroClipboard onCopy={this.onIntegrationTokenCopied}
text={integrationToken}>
<a>Copy integration link</a>
</ReactZeroClipboard>
</div>
<textarea className="token" onClick={this.selectToken} readOnly row="3" value={integrationToken}/>
</Fold>
</li>
</ul>
<InviteUser/>
<InviteByLink/>
<Snackbar autoHideDuration={3000}
message={this.getIntlMessage('integrationTokenCopied')}
ref="integrationTokenCopied"
style={snackbarStyles}/>
</div>
);
} else {
return (
<div className="activity__body group_profile">
<ul className="profile__list">
<li className="profile__list__item group_profile__meta">
{groupMeta}
</li>
</ul>
</div>
);
}
}
}
export default GroupProfile;
|
src/js/pages/EditThreadPage.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import * as ThreadActionCreators from '../actions/ThreadActionCreators';
import AuthenticatedComponent from '../components/AuthenticatedComponent';
import translate from '../i18n/Translate';
import connectToStores from '../utils/connectToStores';
import FilterStore from '../stores/FilterStore';
import TagSuggestionsStore from '../stores/TagSuggestionsStore';
import ThreadStore from '../stores/ThreadStore';
import Input from '../components/ui/Input';
import TextRadios from '../components/ui/TextRadios';
import CreateContentThread from '../components/threads/CreateContentThread';
import CreateUsersThread from '../components/threads/CreateUsersThread';
import TopNavBar from '../components/ui/TopNavBar';
import EmptyMessage from '../components/ui/EmptyMessage/EmptyMessage';
import Framework7Service from '../services/Framework7Service';
function parseThreadId(params) {
return params.threadId;
}
/**
* Requests data from server for current props.
*/
function requestData(props) {
const userId = props.user.id;
ThreadActionCreators.requestFilters(userId);
ThreadActionCreators.requestThreads(userId);
}
/**
* Retrieves state from stores for current props.
*/
function getState(props) {
const filters = FilterStore.filters;
const tags = TagSuggestionsStore.tags;
const threadId = parseThreadId(props.params);
const thread = ThreadStore.get(threadId);
const categories = ThreadStore.getCategories();
const errors = ThreadStore.getErrors();
return {
tags,
filters,
thread,
categories,
errors
};
}
@AuthenticatedComponent
@translate('EditThreadPage')
@connectToStores([ThreadStore, FilterStore, TagSuggestionsStore], getState)
export default class EditThreadPage extends Component {
static contextTypes = {
router: PropTypes.object.isRequired
};
static propTypes = {
// Injected by @connectToStores:
filters : PropTypes.object,
tags : PropTypes.array,
thread : PropTypes.object.isRequired,
categories: PropTypes.array,
errors : PropTypes.string,
// Injected by @AuthenticatedComponent
user : PropTypes.object.isRequired,
// Injected by @translate:
strings : PropTypes.object
};
constructor(props) {
super(props);
this._onChange = this._onChange.bind(this);
this.handleClickCategory = this.handleClickCategory.bind(this);
this.onEdit = this.onEdit.bind(this);
this.state = {
threadName: '',
category : null,
updating : false,
};
}
componentWillMount() {
requestData(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.thread) {
this.setState({
threadName: nextProps.thread.name,
category : nextProps.thread.category == 'ThreadUsers' ? 'persons' : 'contents'
});
}
if (nextProps.errors) {
Framework7Service.nekunoApp().alert(nextProps.errors);
}
}
_onChange(event) {
this.setState({
threadName: event.target.value
});
}
handleClickCategory(category) {
this.setState({
category: category
});
}
onEdit(data) {
let threadId = this.props.thread.id;
ThreadActionCreators.updateThread(threadId, data)
.then(() => {
this.setState({updating: false});
this.context.router.push(`discover`);
}, () => {
this.setState({updating: false});
});
this.setState({updating: true});
}
render() {
const {user, filters, tags, thread, categories, strings} = this.props;
const {category, threadName, updating} = this.state;
return (
<div className="views">
<TopNavBar centerText={strings.edit} leftText={strings.cancel}/>
<div className="view view-main">
<div className="page create-thread-page">
<div id="page-content">
{updating ? <EmptyMessage text={strings.updating} loadingGif={true}/> :
thread && threadName && filters && categories ?
<div>
<div className="thread-title list-block">
<ul>
<Input placeholder={strings.placeholder} onChange={this._onChange} defaultValue={threadName}/>
</ul>
</div>
<div key={1} className={category + '-first-vertical-line'}></div>
<div key={2} className={category + '-last-vertical-line'}></div>
<div className="main-filter-wprapper">
<div className="thread-filter radio-filter">
<div className="thread-filter-dot">
<span className={category ? "icon-circle active" : "icon-circle"}></span>
</div>
<TextRadios labels={[{key: 'persons', text: strings.people}, {key: 'contents', text: strings.contents}]} onClickHandler={this.handleClickCategory} value={category} forceTwoLines={true}/>
</div>
</div>
{category === 'contents' ? <CreateContentThread userId={user.id} defaultFilters={filters['contentFilters']} threadName={threadName} tags={tags} thread={thread} onSave={this.onEdit}/> : ''}
{category === 'persons' ? <CreateUsersThread userId={user.id} defaultFilters={filters['userFilters']} threadName={threadName} tags={tags} thread={thread} categories={categories} onSave={this.onEdit}/> : ''}
</div>
: ''}
</div>
</div>
</div>
</div>
);
}
}
EditThreadPage.defaultProps = {
strings: {
edit : 'Edit yarn',
cancel : 'Cancel',
placeholder: 'Title',
people : 'Users of Nekuno',
contents : 'Links of Internet',
updating : 'Updating yarn',
}
};
|
src/index.js | SpencerCDixon/BleedingEdge | import React from 'react';
import App from './App';
import TodoContainer from './containers/TodoContainer';
import ReactDOM from 'react-dom';
import * as reducers from './reducers/index';
// React Router
import { Route } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
// Redux
import {
ReduxRouter,
reduxReactRouter,
routerStateReducer,
} from 'redux-router';
import {
createStore,
applyMiddleware,
combineReducers,
compose,
} from 'redux';
import createLogger from 'redux-logger';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import { persistState } from 'redux-devtools';
import DevTools from './containers/DevTools';
const logger = createLogger();
// Combine all my personal reducers with the Redux Router reducer
const rootReducer = combineReducers(
{router: routerStateReducer, ...reducers }
);
const store = compose(
reduxReactRouter({ createHistory: createBrowserHistory }),
applyMiddleware(thunkMiddleware, logger),
DevTools.instrument(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)),
)(createStore)(rootReducer);
const routes = (
<ReduxRouter>
<Route path="/" component={App}>
<Route path="todos" component={TodoContainer} />
</Route>
</ReduxRouter>
);
class Root extends React.Component {
render() {
return (
<div>
<Provider store={store}>
<div>
{routes}
<DevTools />
</div>
</Provider>
</div>
);
}
}
ReactDOM.render(<Root />, document.getElementById('root'));
|
src/TableEditColumn.js | opensourcegeek/react-bootstrap-table | import React from 'react';
import Const from './Const';
import Editor from './Editor'
import Notifier from './Notification.js';
import classSet from 'classnames';
class TableEditColumn extends React.Component{
constructor(props){
super(props);
this.timeouteClear=0;
this.state={
shakeEditor:false
};
}
handleKeyPress(e){
if (e.keyCode == 13) { //Pressed ENTER
let value = e.currentTarget.type == 'checkbox'?
this._getCheckBoxValue(e):e.currentTarget.value;
if(!this.validator(value)){
return;
}
this.props.completeEdit(
value, this.props.rowIndex, this.props.colIndex);
}else if(e.keyCode == 27){
this.props.completeEdit(
null, this.props.rowIndex, this.props.colIndex);
}
}
handleBlur(e){
if(this.props.blurToSave){
let value = e.currentTarget.type == 'checkbox'?
this._getCheckBoxValue(e):e.currentTarget.value;
if(!this.validator(value)){
return;
}
this.props.completeEdit(
value, this.props.rowIndex, this.props.colIndex);
}
}
validator(value){
var ts=this;
if(ts.props.editable.validator){
var valid=ts.props.editable.validator(value);
if(valid!==true){
ts.refs.notifier.notice('error',valid,"Pressed ESC can cancel");
var input = ts.refs.inputRef;
//animate input
ts.clearTimeout();
ts.setState({shakeEditor:true});
ts.timeouteClear=setTimeout(function(){ts.setState({shakeEditor:false});},300);
input.focus();
return false;
}
}
return true;
}
clearTimeout(){
if(this.timeouteClear!=0){
clearTimeout(this.timeouteClear);
this.timeouteClear=0;
}
}
componentDidMount(){
var input = this.refs.inputRef;
// input.value = this.props.children||'';
input.focus();
}
componentWillUnmount() {
this.clearTimeout();
}
render(){
var editable=this.props.editable,
format=this.props.format,
attr={
ref:"inputRef",
onKeyDown:this.handleKeyPress.bind(this),
onBlur:this.handleBlur.bind(this)
};
//put placeholder if exist
editable.placeholder&&(attr.placeholder=editable.placeholder);
var editorClass=classSet({'animated':this.state.shakeEditor,'shake':this.state.shakeEditor});
return(
<td ref="td" style={{position:'relative'}}>
{Editor(editable,attr,format,editorClass,this.props.children||'')}
<Notifier ref="notifier"></Notifier>
</td>
)
}
_getCheckBoxValue(e){
let value = '';
let values = e.currentTarget.value.split(':');
value = e.currentTarget.checked?values[0]:values[1];
return value;
}
}
TableEditColumn.propTypes = {
completeEdit: React.PropTypes.func,
rowIndex: React.PropTypes.number,
colIndex: React.PropTypes.number,
blurToSave: React.PropTypes.bool
};
export default TableEditColumn;
|
index.android.js | leechuanjun/TLRNProjectTemplate | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class TLRNProjectTemplate extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('TLRNProjectTemplate', () => TLRNProjectTemplate);
|
src/components/admin/PendingRegistrations.js | Atypon-OpenSource/wayf-admin | import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { createRefetchContainer, graphql } from 'react-relay';
import CreatePublisherModal from './CreatePublisherModal'
import DenyPublisherRegistrationModal from './DenyPublisherRegistrationModal'
import {
Grid,
Table,
Col,
Button,
Glyphicon,
Row} from 'react-bootstrap';
class PendingRegistrations extends React.Component {
static propTypes = {
viewer: PropTypes.object.isRequired,
relay: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.pendingRegistrationsRowMapper = this.pendingRegistrationsRowMapper.bind(this);
this.approveClick = this.approveClick.bind(this);
this.clearApproval = this.clearApproval.bind(this);
this.denyClick = this.denyClick.bind(this);
this.clearDenyRequest = this.clearDenyRequest.bind(this);
this.clearDenyAndRefetch = this.clearDenyAndRefetch.bind(this);
this.refetch = this.refetch.bind(this);
this.clearApprovalAndRefetch = this.clearApprovalAndRefetch.bind(this);
this.state = {
publisherRegistrationToApprove: null,
publisherRegistrationToDeny: null
};
}
subscribeToForget() {
this.fetchedHistory = false;
this.toggleShow();
}
toggleShow() {
if (!this.fetchedHistory) {
const refetchVariables = () => ({
fetchPendingRegistrations: true
});
this.fetchedHistory = true;
this.props.relay.refetch(refetchVariables, null);
}
}
refetch() {
const refetchVariables = () => ({
fetchPendingRegistrations: true
});
this.fetchedHistory = true;
this.props.relay.refetch(refetchVariables, null);
}
approveClick(publisherRegistration) {
var state = this.state;
state.publisherRegistrationToApprove = publisherRegistration;
this.setState(state);
}
denyClick(publisherRegistration) {
var state = this.state;
state.publisherRegistrationToDeny = publisherRegistration;
this.setState(state);
}
clearApproval() {
var state = this.state;
state.publisherRegistrationToApprove = null;
this.setState(state);
}
clearApprovalAndRefetch() {
this.clearApproval();
this.refetch();
}
clearDenyRequest() {
var state = this.state;
state.publisherRegistrationToDeny = null;
this.setState(state);
}
clearDenyAndRefetch() {
this.clearDenyRequest();
this.refetch();
}
pendingRegistrationsRowMapper(pendingPublisherRegistrations) {
if (!pendingPublisherRegistrations || pendingPublisherRegistrations.length <= 0) {
return <tr><td colSpan="6" >No pending registrations</td></tr>
}
return pendingPublisherRegistrations.map(
(publisherRegistration, i) => {
return (
<tr key={i}>
<td>
{publisherRegistration.publisherName}
</td>
<td>
{publisherRegistration.contact.firstName} {publisherRegistration.contact.lastName}
</td>
<td>
<a href={`mailto:${publisherRegistration.contact.email}`}>{publisherRegistration.contact.email}</a>
</td>
<td>
{publisherRegistration.contact.phoneNumber}
</td>
<td>
{moment(publisherRegistration.applicationDate).format('LLL')}
</td>
<td>
<Button bsStyle="success" value={publisherRegistration} onClick={() => this.approveClick(publisherRegistration)} ><Glyphicon glyph="ok" /></Button>
<Button bsStyle="danger" onClick={() => this.denyClick(publisherRegistration)} ><Glyphicon glyph="remove" /></Button>
</td>
</tr>
)
}
);
}
render() {
var actionModal;
if (this.state.publisherRegistrationToApprove) {
actionModal = <CreatePublisherModal relay={this.props.relay} onClose={this.clearApprovalAndRefetch} onCancel={this.clearApproval} publisherRegistration={this.state.publisherRegistrationToApprove}/>;
} else if (this.state.publisherRegistrationToDeny) {
actionModal = <DenyPublisherRegistrationModal relay={this.props.relay} onClose={this.clearDenyAndRefetch} onCancel={this.clearDenyRequest} publisherRegistration={this.state.publisherRegistrationToDeny}/>;
} else {
actionModal = <div></div>;
}
return (
<Grid>
{actionModal}
<Table striped bordered condensed hover>
<thead>
<tr>
<th>Publisher Name</th>
<th>Contact Name</th>
<th>Contact Email</th>
<th>Contact Phone Number</th>
<th>Application Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.pendingRegistrationsRowMapper(this.props.viewer.pendingPublisherRegistrations)}
</tbody>
</Table>
</Grid>);
}
}
export default createRefetchContainer(
PendingRegistrations,
graphql.experimental`
fragment PendingRegistrations_viewer on viewer
@argumentDefinitions(
fetchPendingRegistrations: {type: "Boolean!", defaultValue: true}
) {
pendingPublisherRegistrations @include(if: $fetchPendingRegistrations) {
publisherRegistrationId: id,
publisherName,
status,
contact {
firstName,
lastName,
email,
phoneNumber
},
applicationDate
}
}
`,
graphql.experimental`
query PendingRegistrationsRefetchQuery($fetchPendingRegistrations: Boolean!) {
viewer {
...PendingRegistrations_viewer @arguments(fetchPendingRegistrations: $fetchPendingRegistrations)
}
}
`,
);
|
src/svg-icons/maps/directions-boat.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsDirectionsBoat = (props) => (
<SvgIcon {...props}>
<path d="M20 21c-1.39 0-2.78-.47-4-1.32-2.44 1.71-5.56 1.71-8 0C6.78 20.53 5.39 21 4 21H2v2h2c1.38 0 2.74-.35 4-.99 2.52 1.29 5.48 1.29 8 0 1.26.65 2.62.99 4 .99h2v-2h-2zM3.95 19H4c1.6 0 3.02-.88 4-2 .98 1.12 2.4 2 4 2s3.02-.88 4-2c.98 1.12 2.4 2 4 2h.05l1.89-6.68c.08-.26.06-.54-.06-.78s-.34-.42-.6-.5L20 10.62V6c0-1.1-.9-2-2-2h-3V1H9v3H6c-1.1 0-2 .9-2 2v4.62l-1.29.42c-.26.08-.48.26-.6.5s-.15.52-.06.78L3.95 19zM6 6h12v3.97L12 8 6 9.97V6z"/>
</SvgIcon>
);
MapsDirectionsBoat = pure(MapsDirectionsBoat);
MapsDirectionsBoat.displayName = 'MapsDirectionsBoat';
export default MapsDirectionsBoat;
|
react/features/base/toolbox/components/AbstractButton.js | gpolitis/jitsi-meet | // @flow
import React, { Component } from 'react';
import { NOTIFY_CLICK_MODE } from '../../../toolbox/constants';
import { combineStyles } from '../../styles';
import type { Styles } from './AbstractToolboxItem';
import ToolboxItem from './ToolboxItem';
export type Props = {|
/**
* Function to be called after the click handler has been processed.
*/
afterClick: ?Function,
/**
* The button's key.
*/
buttonKey?: string,
/**
* Whether or not the button is displayed in a context menu.
*/
contextMenu?: boolean,
/**
* An extra class name to be added at the end of the element's class name
* in order to enable custom styling.
*/
customClass?: string,
/**
* Extra styles which will be applied in conjunction with `styles` or
* `toggledStyles` when the button is disabled;.
*/
disabledStyles: ?Styles,
/**
* External handler for click action.
*/
handleClick?: Function,
/**
* Notify mode for `toolbarButtonClicked` event -
* whether to only notify or to also prevent button click routine.
*/
notifyMode?: string,
/**
* Whether to show the label or not.
*/
showLabel: boolean,
/**
* Collection of styles for the button.
*/
styles: ?Styles,
/**
* Collection of styles for the button, when in toggled state.
*/
toggledStyles: ?Styles,
/**
* From which direction the tooltip should appear, relative to the button.
*/
tooltipPosition: string,
/**
* Whether this button is visible or not.
*/
visible: boolean
|};
declare var APP: Object;
/**
* Default style for disabled buttons.
*/
export const defaultDisabledButtonStyles = {
iconStyle: {
opacity: 0.5
},
labelStyle: {
opacity: 0.5
},
style: undefined,
underlayColor: undefined
};
/**
* An abstract implementation of a button.
*/
export default class AbstractButton<P: Props, S: *> extends Component<P, S> {
static defaultProps = {
afterClick: undefined,
disabledStyles: defaultDisabledButtonStyles,
showLabel: false,
styles: undefined,
toggledStyles: undefined,
tooltipPosition: 'top',
visible: true
};
/**
* A succinct description of what the button does. Used by accessibility
* tools and torture tests.
*
* @abstract
*/
accessibilityLabel: string;
/**
* The icon of this button.
*
* @abstract
*/
icon: Object;
/**
* The text associated with this button. When `showLabel` is set to
* {@code true}, it will be displayed alongside the icon.
*
* @abstract
*/
label: string;
/**
* The label for this button, when toggled.
*/
toggledLabel: string;
/**
* The icon of this button, when toggled.
*
* @abstract
*/
toggledIcon: Object;
/**
* The text to display in the tooltip. Used only on web.
*
* @abstract
*/
tooltip: ?string;
/**
* Initializes a new {@code AbstractButton} instance.
*
* @param {Props} props - The React {@code Component} props to initialize
* the new {@code AbstractButton} instance with.
*/
constructor(props: P) {
super(props);
// Bind event handlers so they are only bound once per instance.
this._onClick = this._onClick.bind(this);
}
/**
* Helper function to be implemented by subclasses, which should be used
* to handle a key being down.
*
* @protected
* @returns {void}
*/
_onKeyDown() {
// To be implemented by subclass.
}
/**
* Helper function to be implemented by subclasses, which should be used
* to handle the button being clicked / pressed.
*
* @protected
* @returns {void}
*/
_handleClick() {
// To be implemented by subclass.
}
/**
* Helper function to be implemented by subclasses, which may return a
* new React Element to be appended at the end of the button.
*
* @protected
* @returns {ReactElement|null}
*/
_getElementAfter() {
return null;
}
/**
* Gets the current icon, taking the toggled state into account. If no
* toggled icon is provided, the regular icon will also be used in the
* toggled state.
*
* @private
* @returns {string}
*/
_getIcon() {
return (
this._isToggled() ? this.toggledIcon : this.icon
) || this.icon;
}
/**
* Gets the current label, taking the toggled state into account. If no
* toggled label is provided, the regular label will also be used in the
* toggled state.
*
* @private
* @returns {string}
*/
_getLabel() {
return (this._isToggled() ? this.toggledLabel : this.label)
|| this.label;
}
/**
* Gets the current styles, taking the toggled state into account. If no
* toggled styles are provided, the regular styles will also be used in the
* toggled state.
*
* @private
* @returns {?Styles}
*/
_getStyles(): ?Styles {
const { disabledStyles, styles, toggledStyles } = this.props;
const buttonStyles
= (this._isToggled() ? toggledStyles : styles) || styles;
if (this._isDisabled() && buttonStyles && disabledStyles) {
return {
iconStyle: combineStyles(
buttonStyles.iconStyle, disabledStyles.iconStyle),
labelStyle: combineStyles(
buttonStyles.labelStyle, disabledStyles.labelStyle),
style: combineStyles(
buttonStyles.style, disabledStyles.style),
underlayColor:
disabledStyles.underlayColor || buttonStyles.underlayColor
};
}
return buttonStyles;
}
/**
* Get the tooltip to display when hovering over the button.
*
* @private
* @returns {string}
*/
_getTooltip() {
return this.tooltip || '';
}
/**
* Helper function to be implemented by subclasses, which must return a
* boolean value indicating if this button is disabled or not.
*
* @protected
* @returns {boolean}
*/
_isDisabled() {
return false;
}
/**
* Helper function to be implemented by subclasses, which must return a
* {@code boolean} value indicating if this button is toggled or not or
* undefined if the button is not toggleable.
*
* @protected
* @returns {?boolean}
*/
_isToggled() {
return undefined;
}
_onClick: (*) => void;
/**
* Handles clicking / pressing the button.
*
* @param {Object} e - Event.
* @private
* @returns {void}
*/
_onClick(e) {
const { afterClick, handleClick, notifyMode, buttonKey } = this.props;
if (typeof APP !== 'undefined' && notifyMode) {
APP.API.notifyToolbarButtonClicked(
buttonKey, notifyMode === NOTIFY_CLICK_MODE.PREVENT_AND_NOTIFY
);
}
if (notifyMode !== NOTIFY_CLICK_MODE.PREVENT_AND_NOTIFY) {
if (handleClick) {
handleClick();
}
this._handleClick();
}
afterClick && afterClick(e);
// blur after click to release focus from button to allow PTT.
e?.currentTarget?.blur && e.currentTarget.blur();
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {React$Node}
*/
render(): React$Node {
const props = {
...this.props,
accessibilityLabel: this.accessibilityLabel,
elementAfter: this._getElementAfter(),
icon: this._getIcon(),
label: this._getLabel(),
styles: this._getStyles(),
toggled: this._isToggled(),
tooltip: this._getTooltip()
};
return (
<ToolboxItem
disabled = { this._isDisabled() }
onClick = { this._onClick }
onKeyDown = { this._onKeyDown }
{ ...props } />
);
}
}
|
src/js/components/Camera.js | ngokevin/audioworld | import {Entity} from 'aframe-react';
import React from 'react';
export default props => (
<Entity position="0 1.8 0">
<Entity camera look-controls {...props}/>
</Entity>
);
|
app/src/components/NotFound/index.js | AlexandreBourdeaudhui/abourdeaudhui.fr | /*
* Package Import
*/
import React from 'react';
/*
* Local Import
*/
/*
* Code
*/
const NotFound = () => (
<div id="notfound">
<h2 style={{ fontSize: '5em' }}>
404 | Not Found
</h2>
<p style={{ lineHeight: '1.5', textAlign: 'center' }}>
Oh non, qui s'est trompé de page? <br />
Mais pas de panique, vous pouvez reprendre votre navigation sans problème.
</p>
</div>
);
/*
* Export
*/
export default NotFound;
|
js/components/ViewContainer.js | wraithyz/reactNative-menu | import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class ViewContainer extends Component {
render() {
return {
<View style={styles.viewContainer}>
{this.props.children}
</View>
}
}
}
const styles = React.StyleSheet.create({
viewContainer: {
flex: 1,
flexDirection: "column",
justifyContent: "flex-start",
alignItems: "stretch",
}
});
module.exports = ViewContainer;
|
RN/RNFluxDemo/DetailExample.js | puyanLiu/LPYFramework | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
import {
Router,
Scene,
Reducer,
Modal,
Switch,
Actions,
ActionConst
} from 'react-native-router-flux';
import Button from "react-native-button";
import EchoView from './components/EchoView';
import Error from './components/Error';
import Home from './components/Home';
import Launch from './components/Launch';
import Login from './components/Login';
import Login2 from './components/Login2';
import Login3 from './components/Login3';
import NavigationDrawer from './components/NavigationDrawer';
import Register from './components/Register';
import TabIcon from './components/TabIcon';
import TabView from './components/TabView';
const reducerCreate = params => {
const defaultReducer = new Reducer(params);
console.log('params: ', params);
return (state, action) => {
console.log('action: ', action);
return defaultReducer(state, action);
};
};
const getSceneStyle = (props, computedProps) => {
console.log('getSceneStyle', props, computedProps);
const style = {
flex: 1,
backgroundColor: 'red',
shadowColor: null,
shadowOffset: null,
shadowOpacity: null,
shadowRadius: null,
};
if (computedProps.isActive) {
style.marginTop = computedProps.hideNavBar ? 0 : 64;
style.marginBottom = computedProps.hideTabBar ? 0 : 50;
}
return style;
};
let currentSwitchPage = 'text1';
const SwitcherPage = (props) => (
<View>
<Text style={{ marginTop: 100, textAlign: 'center'}}>咚咚咚,当前为文本内容是: {props.text}</Text>
<Button onPress={() => {
currentSwitchPage = (currentSwitchPage === 'text1' ? 'text2' : 'text1');
Actions.refresh({ key: 'switcher' });
}}>点我看看有啥好玩的</Button>
<Button onPress={() => {
Actions.launch({ type: ActionConst.RESET });
}}>Exit</Button>
</View>
);
class DetailExample extends Component {
render() {
return (
<Router createReducer={reducerCreate} getSceneStyle={getSceneStyle}>
<Scene key="modal" component={Modal} >
<Scene key="root" hideNavBar hideTabBar>
<Scene key="echo" component={EchoView} clone getTitle={(navState) => navState.key} />
<Scene key="launch" component={Launch} title="Launch" />
{
/*Switch有问题*/
}
<Scene key="switcher" component={Switch} selector={() => { return 'text1';}} >
<Scene key="text1" text="text1" component={(props) => <SwitcherPage {...props} text={currentSwitchPage} />} />
<Scene key="text2" text="text2" component={(props) => <SwitcherPage {...props} text={currentSwitchPage} />} />
</Scene>
<Scene key="register" component={Register} title="Register" />
<Scene key="register2" component={Register} title="Register" duration={1} />
<Scene key="register3" component={Register} title="Register" direction="vertical" />
<Scene key="register4" component={Register} title="Register" direction="leftToRight" />
<Scene key="home" component={Home} title="Home" type={ActionConst.REPLACE} />
<Scene key="login" direction="vertical" hideTabBar>
<Scene key="loginModal" component={Login} title="Login" direction="vertical" />
<Scene key="loginModal2" component={Login2} title="Login2" hideNavBar panHandles={null} />
<Scene key="loginModal3" component={Login3} title="Login3" hideNavBar panHandles={null} />
</Scene>
<Scene key="tabbar" component={NavigationDrawer}>
<Scene key="main" tabs tabBarStyle={styles.tabBarStyle} tabBarSelectedItemStyle={styles.tabBarSelectedItemStyle} >
<Scene key="tab1" title="tab1 title1" icon={TabIcon} navigationBarStyle={{backgroundColor: 'purple'}} titleStyle={{color: 'white'}}>
<Scene key="tab1_1" component={TabView} title="tab1_1 title1_1" onRight={() => alert('right button')} rightTitle="right" />
<Scene key="tab1_2" component={TabView} title="tab1_2 title1_2" titleStyle={{color: 'black'}} />
</Scene>
<Scene key="tab2" title="tab2 title2" icon={TabIcon} initial>
<Scene key="tab2_1" component={TabView} title="tab2_1 title2_1" renderRightButton={() => <Text>Right</Text>} />
<Scene key="tab2_2" component={TabView} title="tab2_2 title2_2" hideBackImage onBack={() => alert('left button')} backTitle="left" duration={1} panHandles={null} />
</Scene>
<Scene key="tab3" component={TabView} title="tab3 title3" icon={TabIcon}></Scene>
<Scene key="tab4" component={TabView} title="tab4 title4" icon={TabIcon}></Scene>
<Scene key="tab5" component={TabView} title="tab5 title5" icon={TabIcon} hideNavBar></Scene>
</Scene>
</Scene>
</Scene>
<Scene key="error" component={Error} />
</Scene>
</Router>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
tabBarStyle: {
backgroundColor: 'orange',
},
tabBarSelectedItemStyle: {
backgroundColor: 'green'
},
});
export default DetailExample;
|
examples/with-noscript/pages/index.js | BlancheXu/test | import React from 'react'
import Noscript from '../components/Noscript'
export default function IndexPage () {
return (
<>
<h1>noscript</h1>
<p>Disable JavaScript to see it in action:</p>
<hr />
<Noscript>Noscript is enabled!</Noscript>
</>
)
}
|
app/react-icons/fa/facebook.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaFacebook extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m29.4 0.3v5.9h-3.5q-1.9 0-2.6 0.8t-0.7 2.4v4.2h6.6l-0.9 6.6h-5.7v16.9h-6.8v-16.9h-5.7v-6.6h5.7v-4.9q0-4.1 2.3-6.4t6.2-2.3q3.3 0 5.1 0.3z"/></g>
</IconBase>
);
}
}
|
blog/src/components/app.js | simplanapp/course | import React from 'react';
import { Component } from 'react';
import SearchCurses from './search_bar';
import CurseItem from './curse_item'
export default class App extends Component {
render() {
//console.log(this);
return (
<div >
{this.props.children}
{/* <div>
<SearchCurses />
<CurseItem />
</div>
<h1>
gggggggggg
</h1> */}
</div>
);
}
}
|
src/index.js | rikukissa/webpack-project-template | 'use strict';
import React from 'react';
import App from 'components/App';
React.render(<App />, document.body);
|
src/yearpicker/YearPickerTop.js | buildo/react-semantic-datepicker | import React from 'react';
import t from 'tcomb';
import { props } from 'tcomb-react';
import { pure, skinnable } from '../utils';
import { MomentDate } from '../utils/model';
import PickerTop from '../PickerTop';
@pure
@skinnable()
@props({
visibleDate: MomentDate,
changeYear: t.Function,
prevIconClassName: t.String,
nextIconClassName: t.String
})
export default class YearPickerTop extends React.Component {
getYear = () => this.props.visibleDate.year()
previousDate = () => this.props.changeYear(this.getYear() - 10)
nextDate = () => this.props.changeYear(this.getYear() + 10)
getLocals({ prevIconClassName, nextIconClassName }) {
const year = this.getYear();
const startDecadeYear = parseInt(year / 10, 10) * 10;
const endDecadeYear = startDecadeYear + 9;
return {
prevIconClassName,
nextIconClassName,
fixed: true,
previousDate: this.previousDate,
nextDate: this.nextDate,
value: `${startDecadeYear}-${endDecadeYear}`
};
}
template(locals) {
return <PickerTop {...locals} />;
}
}
|
src/components/Feedback/Feedback.js | rameshrr/dicomviewer | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Feedback.css';
class Feedback extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<a
className={s.link}
href="https://gitter.im/kriasoft/react-starter-kit"
>
Ask a question
</a>
<span className={s.spacer}>|</span>
<a
className={s.link}
href="https://github.com/kriasoft/react-starter-kit/issues/new"
>
Report an issue
</a>
</div>
</div>
);
}
}
export default withStyles(s)(Feedback);
|
src/docs/examples/ProgressBar/Example70Percent.js | noumanberlas/prime-react | import React from 'react';
import ProgressBar from 'prime-react/ProgressBar';
/** 70% progress */
export default function Example70Percent() {
return <ProgressBar percent={70} width={150} />
}
|
template/src/routes/count/components/Increase.js | likun7981/react-template-router | import React from 'react'
import { Button } from 'antd'
export const Increase = props => {
return (
<div>
<h2>reduxStateCount: {props.increaseResult}</h2>
<h3>reactStateCount: {props.count}</h3>
<Button onClick={props.addState}>addStateCount</Button>
<Button className="btn btn-default" onClick={props.increase}>
Increment
</Button>
<Button className="btn btn-default" onClick={props.doubleAsync}>
Double (Async)
</Button>
</div>
)
}
export default Increase
|
src/js/Components/Score/ScoreBoard.js | gabsprates/facomp-quiz | import React, { Component } from 'react';
import Team from './Team';
export default function ScoreBoard(props) {
return (
<div className='scoreboard'>
<h1 className="title h1 has-text-centered">FACOMP QUIZ</h1>
<Team score={ props.teamA } team='t1' />
<Team score={ props.teamB } team='t2' />
</div>
);
}
|
src/widget/DetailCell.js | Cowboy1995/JZWXZ | /**
* Copyright (c) 2017-present, Liu Jinyong
* All rights reserved.
*
* https://github.com/huanxsd/MeiTuan
* @flow
*/
//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native';
import { Heading1, Heading2, Paragraph } from './Text'
import Separator from './Separator'
import { screen, system, tool } from '../common'
// create a component
class DetailCell extends Component {
render() {
let icon = this.props.image && <Image style={styles.icon} source={this.props.image} />
return (
<View style={styles.container}>
<TouchableOpacity>
<View style={[styles.content, this.props.style]}>
{icon}
<Heading2>{this.props.title}</Heading2>
<View style={{ flex: 1, backgroundColor: 'blue' }} />
<Paragraph style={{ color: '#999999' }}>{this.props.subtitle}</Paragraph>
<Image style={styles.arrow} source={require('../img/Public/cell_arrow.png')} />
</View>
<Separator />
</TouchableOpacity>
</View>
);
}
}
// define your styles
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
},
content: {
height: 44,
flexDirection: 'row',
alignItems: 'center',
paddingLeft: 15,
paddingRight: 10,
},
icon: {
width: 25,
height: 25,
marginRight: 10,
},
subtitleContainer: {
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
},
arrow: {
width: 14,
height: 14,
marginLeft: 5,
}
});
//make this component available to the app
export default DetailCell;
|
packages/react-scripts/template/src/App.js | timlogemann/create-react-app | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
|
react/LightbulbIcon/LightbulbIcon.js | seekinternational/seek-asia-style-guide | import svgMarkup from './LightbulbIcon.svg';
import React from 'react';
import Icon from '../private/Icon/Icon';
export default function LightbulbIcon(props) {
return <Icon markup={svgMarkup} {...props} />;
}
LightbulbIcon.displayName = 'LightbulbIcon';
|
src/views/Part/Part.js | asithagihan03/alankara-hapi | import React, { Component } from 'react';
class Part extends Component {
render() {
return (
<div className="animated fadeIn">
Hello Part
</div>
)
}
}
export default Part;
|
src/parser/hunter/beastmastery/modules/checklist/Component.js | FaideWW/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Checklist from 'parser/shared/modules/features/Checklist2';
import Rule from 'parser/shared/modules/features/Checklist2/Rule';
import Requirement from 'parser/shared/modules/features/Checklist2/Requirement';
import PreparationRule from 'parser/shared/modules/features/Checklist2/PreparationRule';
import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist2/GenericCastEfficiencyRequirement';
import ResourceIcon from 'common/ResourceIcon';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import SpellIcon from 'common/SpellIcon';
class BeastMasteryChecklist extends React.PureComponent {
static propTypes = {
castEfficiency: PropTypes.object.isRequired,
combatant: PropTypes.shape({
hasTalent: PropTypes.func.isRequired,
hasTrinket: PropTypes.func.isRequired,
}).isRequired,
thresholds: PropTypes.object.isRequired,
};
render() {
const { combatant, castEfficiency, thresholds } = this.props;
const AbilityRequirement = props => (
<GenericCastEfficiencyRequirement
castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)}
{...props}
/>
);
return (
<Checklist>
<Rule
name="Use core abilities as often as possible"
description={(
<>
Using your core abilities as often as possible can help raise your dps significantly. Some help more than others, but as a general rule of thumb you should be looking to use most of your damaging abilities and damage cooldowns as often as possible, unless you need to save them for a prioirty burst phase that is coming up soon.
{' '}
<a href="https://www.icy-veins.com/wow/beast-mastery-hunter-pve-dps-rotation-cooldowns-abilities" target="_blank" rel="noopener noreferrer">More info.</a>
</>
)}
>
<AbilityRequirement spell={SPELLS.KILL_COMMAND.id} />
<AbilityRequirement spell={SPELLS.BARBED_SHOT.id} />
<AbilityRequirement spell={SPELLS.BESTIAL_WRATH.id} />
<AbilityRequirement spell={SPELLS.ASPECT_OF_THE_WILD.id} />
{combatant.hasTalent(SPELLS.DIRE_BEAST_TALENT.id) && <AbilityRequirement spell={SPELLS.DIRE_BEAST_TALENT.id} />}
{combatant.hasTalent(SPELLS.CHIMAERA_SHOT_TALENT.id) && <AbilityRequirement spell={SPELLS.CHIMAERA_SHOT_TALENT.id} />}
{combatant.hasTalent(SPELLS.A_MURDER_OF_CROWS_TALENT.id) && <AbilityRequirement spell={SPELLS.A_MURDER_OF_CROWS_TALENT.id} />}
{combatant.hasTalent(SPELLS.BARRAGE_TALENT.id) && <AbilityRequirement spell={SPELLS.BARRAGE_TALENT.id} />}
{combatant.hasTalent(SPELLS.STAMPEDE_TALENT.id) && <AbilityRequirement spell={SPELLS.STAMPEDE_TALENT.id} />}
{combatant.hasTalent(SPELLS.SPITTING_COBRA_TALENT.id) && <AbilityRequirement spell={SPELLS.SPITTING_COBRA_TALENT.id} />}
</Rule>
<Rule
name="Barbed Shot usage"
description={(
<>
Using <SpellLink id={SPELLS.BARBED_SHOT.id} /> properly is a key to achieving high dps. This means maintaining the pet buff from <SpellLink id={SPELLS.BARBED_SHOT.id} /> as long as possible, and using it to reduce the cooldown of <SpellLink id={SPELLS.BESTIAL_WRATH.id} /> as much as possible, to ensure high uptime on <SpellLink id={SPELLS.BESTIAL_WRATH.id} />.
</>
)}
>
<Requirement name={<>Uptime of <SpellLink id={SPELLS.BARBED_SHOT_PET_BUFF.id} /> </>} thresholds={thresholds.frenzyUptimeSuggestionThreshold} />
<Requirement name={<>3 stack uptime of <SpellLink id={SPELLS.BARBED_SHOT_PET_BUFF.id} /> </>} thresholds={thresholds.frenzy3StackSuggestionThreshold} />
<Requirement name={<><SpellLink id={SPELLS.BESTIAL_WRATH.id} /> CDR Efficiency</>} thresholds={thresholds.bestialWrathCDREfficiencyThreshold} />
</Rule>
<Rule
name="Talent, cooldown and spell efficiency"
description={(
<>
You want to be using your baseline spells as efficiently as possible, as well as choosing the right talents for the given scenario. If a talent isn't being used optimally for the encounter, you should consider swapping to a different talent.
</>
)}
>
<Requirement name={<><ResourceIcon id={RESOURCE_TYPES.FOCUS.id} /> Average focus on <SpellIcon id={SPELLS.BESTIAL_WRATH.id} /> cast </>} thresholds={thresholds.bestialWrathFocusThreshold} />
<Requirement name={<><SpellIcon id={SPELLS.COBRA_SHOT.id} /><SpellLink id={SPELLS.KILL_COMMAND.id} icon={false} /> CDR efficiency</>} thresholds={thresholds.cobraShotCDREfficiencyThreshold} />
{combatant.hasTalent(SPELLS.KILLER_COBRA_TALENT.id) && <Requirement name={<> Wasted <SpellLink id={SPELLS.KILLER_COBRA_TALENT.id} /> resets </>} thresholds={thresholds.wastedKillerCobraThreshold} />}
</Rule>
<Rule
name={<>Downtime & <ResourceIcon id={RESOURCE_TYPES.FOCUS.id} /> focus capping</>}
description={(
<>
As a DPS, you should try to reduce the delay between casting spells, and stay off resource capping as much as possible. If everything is on cooldown, try and use <SpellLink id={SPELLS.COBRA_SHOT.id} /> to stay off the focus cap and do some damage.
</>
)}
>
<Requirement name={<> Active time</>} thresholds={thresholds.downtimeSuggestionThresholds} />
<Requirement name={<><ResourceIcon id={RESOURCE_TYPES.FOCUS.id} /> Time focus capped</>} thresholds={thresholds.focusCappedSuggestionThresholds} />
</Rule>
<PreparationRule thresholds={thresholds} />
</Checklist>
);
}
}
export default BeastMasteryChecklist;
|
src/app/components/annotations/Annotation.js | meedan/check-web | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, FormattedHTMLMessage, injectIntl, intlShape } from 'react-intl';
import Relay from 'react-relay/classic';
import RCTooltip from 'rc-tooltip';
import styled from 'styled-components';
import { stripUnit } from 'polished';
import { Link } from 'react-router';
import Lightbox from 'react-image-lightbox';
import 'react-image-lightbox/style.css';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import { withStyles } from '@material-ui/core/styles';
import MoreHoriz from '@material-ui/icons/MoreHoriz';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Typography from '@material-ui/core/Typography';
import config from 'config'; // eslint-disable-line require-path-exists/exists
import EmbedUpdate from './EmbedUpdate';
import EmbedCreate from './EmbedCreate';
import TaskUpdate from './TaskUpdate';
import { can } from '../Can';
import { withSetFlashMessage } from '../FlashMessage';
import ParsedText from '../ParsedText';
import TimeBefore from '../TimeBefore';
import SourcePicture from '../source/SourcePicture';
import ProfileLink from '../layout/ProfileLink';
import DatetimeTaskResponse from '../task/DatetimeTaskResponse';
import UserTooltip from '../user/UserTooltip';
import DeleteAnnotationMutation from '../../relay/mutations/DeleteAnnotationMutation';
import DeleteVersionMutation from '../../relay/mutations/DeleteVersionMutation';
import UpdateTaskMutation from '../../relay/mutations/UpdateTaskMutation';
import VideoAnnotationIcon from '../../../assets/images/video-annotation/video-annotation';
import {
getErrorMessage,
getStatus,
getStatusStyle,
emojify,
parseStringUnixTimestamp,
safelyParseJSON,
} from '../../helpers';
import globalStrings from '../../globalStrings';
import { stringHelper } from '../../customHelpers';
import CheckArchivedFlags from '../../CheckArchivedFlags';
import {
units,
white,
opaqueBlack16,
black38,
black54,
black87,
checkBlue,
borderWidthLarge,
caption,
breakWordStyles,
Row,
defaultBorderRadius,
} from '../../styles/js/shared';
const dotSize = borderWidthLarge;
const dotOffset = stripUnit(units(4)) - stripUnit(dotSize);
const StyledDefaultAnnotation = styled.div`
color: ${black87};
display: flex;
font: ${caption};
width: 100%;
${props => (props.theme.dir === 'rtl' ? 'padding-right' : 'padding-left')}: ${units(10)};
.annotation__default-content {
width: 100%;
@extend ${breakWordStyles};
display: block;
margin-${props => (props.theme.dir === 'rtl' ? 'left' : 'right')}: ${units(2)};
}
`;
const StyledAnnotationCardWrapper = styled.div`
width: 100%;
z-index: initial !important;
> div > div {
padding-bottom: 0 !important;
}
img {
cursor: pointer;
}
`;
const StyledAvatarColumn = styled.div`
margin-${props => (props.theme.dir === 'rtl' ? 'left' : 'right')}: ${units(3)};
`;
const StyledPrimaryColumn = styled.div`
flex: 1;
.annotation__card-content {
${breakWordStyles}
display: flex;
width: 100%;
& > span:first-child {
flex: 1;
}
}
.annotation__card-thumbnail {
padding: ${units(1)};
}
.annotation__status {
font: ${caption};
margin: 0 3px;
}
`;
const StyledAnnotationWrapper = styled.section`
position: relative;
display: flex;
padding: ${units(1)} 0;
position: relative;
&:not(.annotation--card) {
// The timeline dot
&::before {
background-color: ${opaqueBlack16};
border-radius: 100%;
content: '';
height: ${units(1)};
outline: ${dotSize} solid ${white};
position: absolute;
top: ${units(2)};
width: ${units(1)};
${props => (props.theme.dir === 'rtl' ? 'right' : 'left')}: ${dotOffset}px;
}
}
.annotation__card-text {
display: flex;
padding: ${units(3)} ${units(2)} ${units(1)} !important;
}
.annotation__card-activity-move-to-trash {
background: ${checkBlue};
color: #fff;
border-radius: ${defaultBorderRadius};
.annotation__timestamp {
color: #fff;
}
}
.annotation__timestamp {
color: ${black38};
display: inline;
flex: 1;
white-space: pre;
margin-${props => (props.theme.dir === 'rtl' ? 'left' : 'right')}: ${units(1)};
}
.annotation__actions {
align-self: flex-start;
display: none;
flex: 1;
text-align: ${props => (props.theme.dir === 'rtl' ? 'left' : 'right')};
}
.annotation__body {
${breakWordStyles}
}
.annotation__embedded-media {
padding-bottom: ${units(1)};
padding-top: ${units(1)};
}
.annotation__tag {
&::before {
content: '#';
}
}
.annotation__update-task > span {
display: block;
}
.annotation__card-embedded-medias {
clear: both;
margin-top: ${units(0.5)};
}
.annotation__keep a {
text-decoration: underline;
}
`;
const StyledAnnotationMetadata = styled(Row)`
color: ${black54};
flex-flow: wrap row;
font: ${caption};
margin-top: ${units(3)};
.annotation__card-author {
color: ${black87};
padding-${props => (props.theme.dir === 'rtl' ? 'left' : 'right')}: ${units(1)};
}
`;
const StyledAnnotationActionsWrapper = styled.div`
margin-${props => (props.theme.dir === 'rtl' ? 'right' : 'left')}: auto;
`;
const FlagName = ({ flag }) => {
switch (flag) {
case 'adult': return <FormattedMessage id="annotation.flagAdult" defaultMessage="Adult" />;
case 'medical': return <FormattedMessage id="annotation.flagMedical" defaultMessage="Medical" />;
case 'violence': return <FormattedMessage id="annotation.flagViolence" defaultMessage="Violence" />;
case 'racy': return <FormattedMessage id="annotation.flagRacy" defaultMessage="Racy" />;
case 'spam': return <FormattedMessage id="annotation.flagSpam" defaultMessage="Spam" />;
default: return null;
}
};
FlagName.propTypes = {
flag: PropTypes.oneOf(['adult', 'medical', 'violence', 'racy', 'spam']).isRequired,
};
const FlagLikelihood = ({ likelihood }) => {
switch (likelihood) {
case 0: return <FormattedMessage id="annotation.flagLikelihood0" defaultMessage="Unknown" />;
case 1: return <FormattedMessage id="annotation.flagLikelihood1" defaultMessage="Very unlikely" />;
case 2: return <FormattedMessage id="annotation.flagLikelihood2" defaultMessage="Unlikely" />;
case 3: return <FormattedMessage id="annotation.flagLikelihood3" defaultMessage="Possible" />;
case 4: return <FormattedMessage id="annotation.flagLikelihood4" defaultMessage="Likely" />;
case 5: return <FormattedMessage id="annotation.flagLikelihood5" defaultMessage="Very likely" />;
default: return null;
}
};
FlagLikelihood.propTypes = {
likelihood: PropTypes.oneOf([0, 1, 2, 3, 4, 5]).isRequired,
};
// TODO Fix a11y issues
/* eslint jsx-a11y/click-events-have-key-events: 0 */
class Annotation extends Component {
constructor(props) {
super(props);
this.state = {
zoomedCommentImage: false,
};
}
handleCloseCommentImage() {
this.setState({ zoomedCommentImage: false });
}
handleOpenCommentImage(image) {
this.setState({ zoomedCommentImage: image });
}
handleOpenMenu = (e) => {
e.stopPropagation();
this.setState({ anchorEl: e.currentTarget });
};
handleCloseMenu = () => {
this.setState({ anchorEl: null });
};
handleDelete(id) {
const onSuccess = () => {};
// Either to destroy versions or annotations
const destroy_attr = {
parent_type: this.props.annotatedType.replace(/([a-z])([A-Z])/, '$1_$2').toLowerCase(),
annotated: this.props.annotated,
id,
};
if (this.props.annotation.annotation.version === null) {
Relay.Store.commitUpdate(
new DeleteAnnotationMutation(destroy_attr),
{ onSuccess, onFailure: this.fail },
);
} else {
destroy_attr.id = this.props.annotation.annotation.version.id;
Relay.Store.commitUpdate(
new DeleteVersionMutation(destroy_attr),
{ onSuccess, onFailure: this.fail },
);
}
}
fail = (transaction) => {
const message = getErrorMessage(
transaction,
(
<FormattedMessage
{...globalStrings.unknownError}
values={{ supportEmail: stringHelper('SUPPORT_EMAIL') }}
/>
),
);
this.props.setFlashMessage(message, 'error');
};
handleSuggestion(vid, accept) {
const onSuccess = () => {};
const task = { id: this.props.annotated.id };
if (accept) {
task.accept_suggestion = vid;
} else {
task.reject_suggestion = vid;
}
const parentType = this.props.annotatedType.replace(/([a-z])([A-Z])/, '$1_$2').toLowerCase();
Relay.Store.commitUpdate(
new UpdateTaskMutation({
operation: 'suggest',
annotated: this.props.annotated.project_media,
parent_type: parentType,
task,
}),
{ onSuccess, onFailure: this.fail },
);
}
static renderTaskResponse(type, object) {
if (type === 'multiple_choice') {
const response = JSON.parse(object.value);
const selected = response.selected || [];
if (response.other) {
selected.push(response.other);
}
return <ul>{selected.map(s => <li><ParsedText text={s} /></li>)}</ul>;
} else if (type === 'geolocation') {
const geojson = JSON.parse(object.value);
const { geometry: { coordinates }, properties: { name } } = geojson;
if (!coordinates[0] || !coordinates[1]) {
return (
<a
style={{ textDecoration: 'underline' }}
href={`http://www.openstreetmap.org/?mlat=${coordinates[0]}&mlon=${coordinates[1]}&zoom=12#map=12/${coordinates[0]}/${coordinates[1]}`}
target="_blank"
rel="noreferrer noopener"
>
<ParsedText text={name} block />
</a>
);
}
return <ParsedText text={name} block />;
} else if (type === 'datetime') {
return <DatetimeTaskResponse response={object.value} />;
}
return <ParsedText text={object.value} block />;
}
render() {
const {
annotation: activity, annotated, annotation: { annotation }, classes,
} = this.props;
let annotationActions = null;
if (annotation && annotation.annotation_type) {
const permission = `destroy ${annotation.annotation_type
.charAt(0)
.toUpperCase()}${annotation.annotation_type.slice(1)}`;
// TODO: Improve hide when item is archived logic. Not all annotated types have archived flag.
const canDoAnnotationActions = can(annotation.permissions, permission) &&
annotated.archived === CheckArchivedFlags.NONE;
annotationActions = canDoAnnotationActions ? (
<div>
<Tooltip title={
<FormattedMessage id="annotation.menuTooltip" defaultMessage="Annotation actions" />
}
>
<IconButton
className="menu-button"
onClick={this.handleOpenMenu}
>
<MoreHoriz />
</IconButton>
</Tooltip>
<Menu
id="customized-menu"
anchorEl={this.state.anchorEl}
keepMounted
open={Boolean(this.state.anchorEl)}
onClose={this.handleCloseMenu}
>
{can(annotation.permissions, permission) ? (
<MenuItem
className="annotation__delete"
onClick={this.handleDelete.bind(this, annotation.id)}
>
<FormattedMessage id="annotation.deleteButton" defaultMessage="Delete" />
</MenuItem>
) : null}
<MenuItem>
<a
href={`#annotation-${activity.dbid}`}
style={{ textDecoration: 'none', color: black87 }}
>
<FormattedMessage
id="annotation.permalink"
defaultMessage="Permalink"
/>
</a>
</MenuItem>
</Menu>
</div>)
: null;
}
const updatedAt = parseStringUnixTimestamp(activity.created_at);
const timestamp = updatedAt
? <span className="annotation__timestamp"><TimeBefore date={updatedAt} /></span>
: null;
let authorName = activity.user
? <ProfileLink className="annotation__author-name" teamUser={activity.user.team_user} /> : null;
const object = JSON.parse(activity.object_after);
const content = object.data;
const isVideoAnno = object.fragment !== undefined;
let activityType = activity.event_type;
let contentTemplate = null;
let showCard = false;
switch (activityType) {
case 'create_comment': {
const commentText = content.text;
const commentContent = JSON.parse(annotation.content);
contentTemplate = (
<div>
<div className="annotation__card-content">
<div className={isVideoAnno ? classes.videoAnnoText : ''} onClick={isVideoAnno ? () => this.props.onTimelineCommentOpen(object.fragment) : null}>
{isVideoAnno ? <VideoAnnotationIcon fontSize="small" className={classes.VideoAnnotationIcon} /> : null} <ParsedText text={commentText} />
</div>
{/* thumbnail */}
{commentContent.original ?
<div onClick={this.handleOpenCommentImage.bind(this, commentContent.original)}>
<img
src={commentContent.thumbnail}
className="annotation__card-thumbnail"
alt=""
/>
</div> : null}
</div>
{/* lightbox */}
{commentContent.original && !!this.state.zoomedCommentImage
? <Lightbox
onCloseRequest={this.handleCloseCommentImage.bind(this)}
mainSrc={this.state.zoomedCommentImage}
/>
: null}
</div>
);
break;
}
case 'create_tag':
if (activity.tag && activity.tag.tag_text) {
contentTemplate = (
<span>
<FormattedMessage
id="annotation.taggedHeader"
defaultMessage="Tagged #{tag} by {author}"
values={{
tag: activity.tag.tag_text.replace(/^#/, ''),
author: authorName,
}}
/>
</span>
);
}
break;
case 'destroy_comment': {
let commentRemoved = null;
if (content === null) {
const changes = safelyParseJSON(activity.object_changes_json);
commentRemoved = changes.data[0].text;
} else {
commentRemoved = content.text;
}
contentTemplate = (
<em className="annotation__deleted">
<FormattedMessage
id="annotation.deletedComment"
defaultMessage="Comment deleted by {author}: {comment}"
values={{
author: authorName,
comment: <ParsedText text={commentRemoved} block />,
}}
/>
</em>);
break;
}
case 'create_task':
if (content.fieldset === 'tasks') {
contentTemplate = (
<span className="annotation__task-created">
<FormattedMessage
id="annotation.taskCreated"
defaultMessage="Task created by {author}: {task}"
values={{
task: content.label,
author: authorName,
}}
/>
</span>
);
}
if (content.fieldset === 'metadata') {
contentTemplate = (
<span className="annotation__metadata-created">
<FormattedMessage
id="annotation.metadataCreated"
defaultMessage="Annotation field created by {author}: {fieldLabel}"
values={{
fieldLabel: content.label,
author: authorName,
}}
/>
</span>
);
}
break;
case 'create_relationship': {
const meta = JSON.parse(activity.meta);
if (meta) {
const { target } = meta;
const type = object.relationship_type;
contentTemplate = (
<span>
{ /parent/.test(type) ?
<FormattedMessage
id="annotation.relationshipCreated"
defaultMessage="Related item added by {author}: {title}"
values={{
title: emojify(target.title),
author: authorName,
}}
/> : null }
{ /confirmed_sibling/.test(type) ?
<FormattedMessage
id="annotation.similarCreated"
defaultMessage="Confirmed similar by {author}: {title}"
values={{
title: emojify(target.title),
author: authorName,
}}
/> : null }
{ /suggested/.test(type) ?
<FormattedMessage
id="annotation.suggestionCreated"
defaultMessage="Suggested match by {author}: {title}"
values={{
title: emojify(target.title),
author: authorName,
}}
/> : null }
</span>
);
}
break;
}
case 'destroy_relationship': {
const meta = JSON.parse(activity.meta);
if (meta) {
const { target } = meta;
const type = object.relationship_type;
contentTemplate = (
<span>
{ /parent/.test(type) ?
<FormattedMessage
id="annotation.relationshipDestroyed"
defaultMessage="Related item removed by {author}: {title}"
values={{
title: emojify(target.title),
author: authorName,
}}
/> : null }
{ /confirmed_sibling/.test(type) ?
<FormattedMessage
id="annotation.similarDestroyed"
defaultMessage="Confirmed similar detached by {author}: {title}"
description="Tells that one item previously confirmed as similar has been detached from current item."
values={{
title: emojify(target.title),
author: authorName,
}}
/> : null }
{ /suggested_sibling/.test(type) ?
<FormattedMessage
id="annotation.suggestionDestroyed"
defaultMessage="Suggested match rejected by {author}: {title}"
values={{
title: emojify(target.title),
author: authorName,
}}
/> : null }
</span>
);
}
break;
}
case 'create_assignment': {
const meta = JSON.parse(activity.meta);
if (meta) {
const { type, title, user_name } = meta;
const values = {
title,
name: user_name,
author: authorName,
};
if (type === 'task') {
contentTemplate = (
<span>
<FormattedMessage
id="annotation.taskAssignmentCreated"
defaultMessage="Task assigned to {name} by {author}: {title}"
values={values}
/>
</span>
);
}
if (type === 'media') {
contentTemplate = (
<span>
<FormattedMessage
id="annotation.mediaAssignmentCreated"
defaultMessage="Item assigned to {name} by {author}"
values={values}
/>
</span>
);
}
}
break;
}
case 'destroy_assignment': {
const meta = JSON.parse(activity.meta);
if (meta) {
const { type, title, user_name } = meta;
const values = {
title,
name: user_name,
author: authorName,
};
if (type === 'task') {
contentTemplate = (
<span>
<FormattedMessage
id="annotation.taskAssignmentDeleted"
defaultMessage="Task unassigned from {name} by {author}: {title}"
values={values}
/>
</span>
);
}
if (type === 'media') {
contentTemplate = (
<span>
<FormattedMessage
id="annotation.mediaAssignmentDeleted"
defaultMessage="Item unassigned from {name} by {author}"
values={values}
/>
</span>
);
}
}
break;
}
case 'create_dynamic':
case 'update_dynamic':
if (object.annotation_type === 'flag') {
showCard = true;
const { flags } = object.data;
// #8220 remove "spam" until we get real values for it.
const flagsContent = (
<ul>
{ Object.keys(flags).filter(flag => flag !== 'spam').map(flag => (
<li style={{ margin: units(1), listStyle: 'disc' }}>
<FlagName flag={flag} />
{': '}
<FlagLikelihood likelihood={flags[flag]} />
</li>
))}
</ul>
);
contentTemplate = (
<div>
<FormattedMessage
id="annotation.flag"
defaultMessage="Classification result:"
/>
{flagsContent}
</div>
);
} else if (object.annotation_type === 'verification_status') {
const statusChanges = JSON.parse(activity.object_changes_json);
if (statusChanges.locked) {
if (statusChanges.locked[1]) {
contentTemplate = (
<FormattedMessage
id="annotation.statusLocked"
defaultMessage="Item status locked by {author}"
values={{ author: authorName }}
/>
);
} else {
contentTemplate = (
<FormattedMessage
id="annotation.statusUnlocked"
defaultMessage="Item status unlocked by {author}"
values={{ author: authorName }}
/>
);
}
} else if (statusChanges.assigned_to_id) {
const assignment = JSON.parse(activity.meta);
if (assignment.assigned_to_name) {
contentTemplate = (
<FormattedMessage
id="annotation.mediaAssigned"
defaultMessage="Item assigned to {name} by {author}"
values={{
name: assignment.assigned_to_name,
author: authorName,
}}
/>
);
} else {
contentTemplate = (
<FormattedMessage
id="annotation.mediaUnassigned"
defaultMessage="Item unassigned from {name} by {author}"
values={{
name: assignment.assigned_from_name,
author: authorName,
}}
/>
);
}
}
}
break;
case 'create_dynamicannotationfield':
case 'update_dynamicannotationfield':
{
if (object.field_name === 'metadata_value' && activityType === 'update_dynamicannotationfield') {
contentTemplate = (
<EmbedUpdate
activity={activity}
authorName={authorName}
/>);
}
if (object.field_name === 'verification_status_status' && config.appName === 'check' && activityType === 'update_dynamicannotationfield') {
const statusValue = object.value;
const statusCode = statusValue.toLowerCase().replace(/[ _]/g, '-');
const status = getStatus(this.props.team.verification_statuses, statusValue);
contentTemplate = (
<span>
<FormattedMessage
id="annotation.statusSetHeader"
defaultMessage="Status set to {status} by {author}"
values={{
status: (
<span
className={`annotation__status annotation__status--${statusCode}`}
style={{ color: getStatusStyle(status, 'color') }}
>
{status.label}
</span>
),
author: authorName,
}}
/>
</span>
);
}
if (object.field_name === 'team_bot_response_formatted_data') {
activityType = 'bot_response';
const botResponse = JSON.parse(object.value);
contentTemplate = (
<div>
<div className="annotation__card-content annotation__bot-response">
<span>
<b>{botResponse.title}</b><br />
<ParsedText text={botResponse.description} />
</span>
<div>
{ botResponse.image_url ?
<div
style={{
background: `transparent url('${botResponse.image_url}') top left no-repeat`,
backgroundSize: 'cover',
border: '1px solid #ccc',
width: 80,
height: 80,
cursor: 'pointer',
display: 'inline-block',
}}
className="annotation__card-thumbnail annotation__bot-response-thumbnail"
onClick={this.handleOpenCommentImage.bind(this, botResponse.image_url)}
/> : null }
</div>
</div>
{ botResponse.image_url && !!this.state.zoomedCommentImage ?
<Lightbox
onCloseRequest={this.handleCloseCommentImage.bind(this)}
mainSrc={this.state.zoomedCommentImage}
/> : null}
</div>
);
}
if (/^suggestion_/.test(object.field_name)) {
activityType = 'task_answer_suggestion';
const suggestion = JSON.parse(object.value);
const review = activity.meta ? JSON.parse(activity.meta) : null;
contentTemplate = (
<div>
<div className="annotation__card-content annotation__task-answer-suggestion">
<ParsedText text={suggestion.comment} />
</div>
<br />
<p>
<small>
<Link to={`/check/bot/${activity.user.bot.dbid}`}>
<FormattedMessage
id="annotation.seeHowThisBotWorks"
defaultMessage="See how this bot works"
/>
</Link>
</small>
</p>
{ review ?
<div style={{ fontStyle: 'italic' }}>
<small>
{ review.accepted ?
<FormattedMessage
id="annotation.suggestionAccepted"
defaultMessage="Accepted by {user}"
values={{
user: <ProfileLink teamUser={review.user.team_user} />,
}}
/> :
<FormattedMessage
id="annotation.suggestionRejected"
defaultMessage="Rejected by {user}"
values={{
user: <ProfileLink teamUser={review.user.team_user} />,
}}
/>
}
</small>
</div> :
<div>
<Button
onClick={this.handleSuggestion.bind(this, activity.dbid, true)}
style={{ border: `1px solid ${black38}` }}
color="primary"
>
<FormattedMessage
id="annotation.acceptSuggestion"
defaultMessage="Accept"
/>
</Button>
<Button
onClick={this.handleSuggestion.bind(this, activity.dbid, false)}
style={{ border: `1px solid ${black38}` }}
color="primary"
>
<FormattedMessage
id="annotation.rejectSuggestion"
defaultMessage="Reject"
/>
</Button>
</div>
}
</div>
);
}
if (/^response_/.test(object.field_name) && activity.task) {
if (activity.task.fieldset === 'tasks') {
contentTemplate = (
<span className="annotation__task-resolved">
<FormattedMessage
id="annotation.taskResolve"
defaultMessage="Task completed by {author}: {task}{response}"
values={{
task: activity.task.label,
author: authorName,
response: Annotation.renderTaskResponse(activity.task.type, object),
}}
/>
</span>
);
}
if (activity.task.fieldset === 'metadata') {
contentTemplate = (
<span className="annotation__metadata-filled">
<FormattedMessage
id="annotation.metadataResponse"
defaultMessage='Annotation field "{fieldLabel}" filled by {author}: {response}'
values={{
fieldLabel: activity.task.label,
author: authorName,
response: Annotation.renderTaskResponse(activity.task.type, object),
}}
/>
</span>
);
}
}
// TODO Replace with Pender-supplied names.
const archivers = {
archive_is_response: 'Archive.is',
archive_org_response: 'Archive.org',
perma_cc_response: 'Perma.cc',
video_archiver_response: 'Video Archiver',
};
if (object.annotation_type === 'archiver' && activityType === 'create_dynamicannotationfield') {
const archiveContent = JSON.parse(annotation.content);
const archive = archiveContent.filter(item => item.field_name === object.field_name);
const archiveResponse = JSON.parse(archive[0].value);
const archiveLink = archiveResponse.location;
const archiveStatus = parseInt(archiveResponse.status, 10);
const archiveName = archivers[object.field_name];
contentTemplate = null;
if (archiveLink) {
contentTemplate = (
<span className="annotation__keep">
<FormattedHTMLMessage
id="annotation.archiverSuccess"
defaultMessage='In case this item goes offline, you can <a href="{link}" target="_blank" rel="noopener noreferrer">access a backup at {name}</a>.'
values={{ link: archiveLink, name: archiveName }}
/>
</span>
);
} else if (archiveResponse.error || archiveStatus >= 400) {
contentTemplate = (
<span className="annotation__keep">
<FormattedHTMLMessage
id="annotation.archiverError"
defaultMessage='Sorry, the following error occurred while archiving the item to {name}: "{message}". Please refresh the item to try again and contact {supportEmail} if the condition persists.'
values={{ name: archiveName, message: archiveResponse.error.message, supportEmail: stringHelper('SUPPORT_EMAIL') }}
/>
</span>
);
} else {
contentTemplate = (
<span className="annotation__keep">
<FormattedHTMLMessage
id="annotation.archiverWait"
defaultMessage="This item is being archived at {name}. The archive link will be displayed here when it's ready."
values={{ name: archiveName }}
/>
</span>
);
}
}
if (object.field_name === 'embed_code_copied') {
contentTemplate = (
<span className="annotation__embed-code-copied">
<FormattedMessage
id="annotation.embedCodeCopied"
defaultMessage="An embed code of the item has been generated and copied. The item may now be publicly viewable."
/>
</span>
);
}
if (object.field_name === 'pender_archive_response' && activityType === 'create_dynamicannotationfield') {
const penderResponse = JSON.parse(JSON.parse(annotation.content)[0].value);
contentTemplate = null;
if (penderResponse.error) {
contentTemplate = (
<span className="annotation__pender-archive">
<FormattedHTMLMessage
id="annotation.penderArchiveResponseError"
defaultMessage="Sorry, an error occurred while taking a screenshot of the item. Please refresh the item to try again and contact {supportEmail} if the condition persists."
values={{ supportEmail: stringHelper('SUPPORT_EMAIL') }}
/>
</span>
);
} else if (penderResponse.screenshot_taken) {
activityType = 'screenshot_taken';
authorName = null;
contentTemplate = (
<div>
<div className="annotation__card-content annotation__pender-archive">
<FormattedHTMLMessage
id="annotation.penderArchiveResponse"
defaultMessage="Keep has taken a screenshot of this URL."
/>
<div>
<div
style={{
background: `transparent url('${penderResponse.screenshot_url}') top left no-repeat`,
backgroundSize: 'cover',
border: '1px solid #ccc',
width: 80,
height: 80,
cursor: 'pointer',
display: 'inline-block',
}}
className="annotation__card-thumbnail annotation__pender-archive-thumbnail"
onClick={this.handleOpenCommentImage.bind(this, penderResponse.screenshot_url)}
/>
</div>
</div>
{/* lightbox */}
{penderResponse.screenshot_url && !!this.state.zoomedCommentImage ?
<Lightbox
onCloseRequest={this.handleCloseCommentImage.bind(this)}
mainSrc={this.state.zoomedCommentImage}
/> : null}
</div>
);
} else {
contentTemplate = (
<span className="annotation__pender-archive">
<FormattedHTMLMessage
id="annotation.penderArchiveWait"
defaultMessage="The screenshot of this item is being taken by Keep. Come back in a few minutes to see it."
/>
</span>
);
}
contentTemplate = null;
}
break;
}
case 'update_embed':
contentTemplate = (
<EmbedUpdate
activity={activity}
authorName={authorName}
/>);
break;
case 'create_embed':
contentTemplate = (
<EmbedCreate
annotated={annotated}
content={content}
authorName={authorName}
/>);
break;
case 'update_projectmediaproject':
if (activity.projects.edges.length > 0 && activity.user) {
const previousProject = activity.projects.edges[0].node;
const currentProject = activity.projects.edges[1].node;
const urlPrefix = `/${this.props.team.slug}/project/`;
contentTemplate = (
<span>
<FormattedMessage
id="annotation.projectMoved"
defaultMessage="Moved from folder {previousProject} to {currentProject} by {author}"
values={{
previousProject: (
<Link to={urlPrefix + previousProject.dbid}>
{previousProject.title}
</Link>
),
currentProject: (
<Link to={urlPrefix + currentProject.dbid}>
{currentProject.title}
</Link>
),
author: authorName,
}}
/>
</span>
);
} else if (activity.object_changes_json === '{"archived":[0,1]}') {
contentTemplate = (
<span>
<FormattedMessage
id="annotation.movedToTrash"
defaultMessage="Moved to Trash by {author}"
values={{
author: authorName,
}}
/>
</span>
);
} else if (activity.object_changes_json === '{"archived":[1,0]}') {
contentTemplate = (
<span>
<FormattedMessage
id="annotation.movedFromTrash"
defaultMessage="Moved out of Trash by {author}"
values={{
author: authorName,
}}
/>
</span>
);
}
break;
case 'copy_projectmedia':
if (activity.teams.edges.length > 0 && activity.user) {
const previousTeam = activity.teams.edges[0].node;
const previousTeamUrl = `/${previousTeam.slug}/`;
contentTemplate = (
<span>
<FormattedMessage
id="annotation.teamCopied"
defaultMessage="Copied from workspace {previousTeam} by {author}"
values={{
previousTeam: (
<Link to={previousTeamUrl}>
{previousTeam.name}
</Link>
),
author: authorName,
}}
/>
</span>
);
}
break;
case 'update_task':
contentTemplate = <TaskUpdate activity={activity} authorName={authorName} />;
break;
default:
contentTemplate = null;
break;
}
if (contentTemplate === null) {
return null;
}
const cardActivities = ['create_comment', 'screenshot_taken', 'bot_response', 'task_answer_suggestion'];
const useCardTemplate = (cardActivities.indexOf(activityType) > -1 || showCard);
const templateClass = `annotation--${useCardTemplate ? 'card' : 'default'}`;
const typeClass = annotation ? `annotation--${annotation.annotation_type}` : '';
return (
<StyledAnnotationWrapper
className={`annotation ${templateClass} ${typeClass}`}
id={`annotation-${activity.dbid}`}
>
{ useCardTemplate ?
<StyledAnnotationCardWrapper>
<Card>
<CardContent
className={`annotation__card-text annotation__card-activity-${activityType.replace(
/_/g,
'-',
)}`}
>
{ authorName ?
<RCTooltip placement="top" overlay={<UserTooltip teamUser={activity.user.team_user} />}>
<StyledAvatarColumn className="annotation__avatar-col">
<SourcePicture
className="avatar"
type="user"
size="small"
object={activity.user.source}
/>
</StyledAvatarColumn>
</RCTooltip> : null }
<StyledPrimaryColumn>
<Typography variant="body1" component="div">
{contentTemplate}
</Typography>
<StyledAnnotationMetadata>
<span className="annotation__card-footer">
{ authorName ?
<ProfileLink
className="annotation__card-author"
teamUser={activity.user.team_user}
/> : null }
<span>
{timestamp}
</span>
</span>
<StyledAnnotationActionsWrapper>
{annotationActions}
</StyledAnnotationActionsWrapper>
</StyledAnnotationMetadata>
</StyledPrimaryColumn>
</CardContent>
</Card>
</StyledAnnotationCardWrapper> :
<StyledDefaultAnnotation className="annotation__default">
<span>
<span className="annotation__default-content">{contentTemplate}</span>
{timestamp}
</span>
</StyledDefaultAnnotation>}
</StyledAnnotationWrapper>
);
}
}
Annotation.propTypes = {
// https://github.com/yannickcr/eslint-plugin-react/issues/1389
// eslint-disable-next-line react/no-typos
setFlashMessage: PropTypes.func.isRequired,
intl: intlShape.isRequired,
};
const annotationStyles = theme => ({
VideoAnnotationIcon: {
marginRight: theme.spacing(1),
position: 'relative',
top: theme.spacing(0.5),
},
videoAnnoText: {
cursor: 'pointer',
},
});
export default withStyles(annotationStyles)(withSetFlashMessage(injectIntl(Annotation)));
|
app/components/events/event.js | robhogfeldt-fron15/ReactiveDogs | import React from 'react';
import moment from 'moment';
let timeStyle = {
time: '',
style: ''
};
let divStyle = {color: 'green', fontWeight: 'bold', fontSize: '90px', clear: 'both'};
let divStyle2 = {color: '#337ab7', textAlign: 'justify', clear: 'both'};
let divStyle3 = {color: '#FA6900', textAlign: 'justify', clear: 'both'};
class Event extends React.Component {
constructor(props) {
super(props);
}
dateCheck(date){
let nowDate = new Date();
let moment1 = new moment(new Date(nowDate));
let moment2 = new moment(new Date(date));
let diffInMilliSeconds = moment2.diff(moment1);
let duration = moment.duration(diffInMilliSeconds);
let days = duration.days().toString();
let today = 'Idag!';
let upComming = 'Days left : ' + days;
let datePassed = 'Completed! ';
let x = nowDate.toLocaleDateString('en-US');
if (date === x) {
timeStyle = { time: today, style: divStyle };
} else if (days.substring(0, 1) === '-') {
timeStyle = { time: datePassed, style: divStyle3 };
} else {
timeStyle = { time: upComming, style: divStyle2 };
}
return timeStyle;
}
render() {
let self = this;
let sorted = this.props.events.sort(function(obj1, obj2) {
return new Date(obj2.date) - new Date(obj1.date);
});
let eventList = sorted.map(function(event, i){
timeStyle = self.dateCheck(event.date);
return <li key={i} style={timeStyle.style}
onClick={self.props.handleEventClick.bind(self, i)}>
<p className='alignleft'>
{event.name}
</p>
<p className='alignright'>
{timeStyle.time}
</p>
</li>;
});
return (
<div>
<div className='row flipInX animated'>
<div>
<div className='panel panel-default'>
<div className='panel-heading'>Choose Event</div>
<div className='panel-body'>
{eventList}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Event;
Event.propTypes = {
handleEventClick: React.PropTypes.any,
events: React.PropTypes.array
};
|
packages/@lyra/components/src/edititem/StoryMover.js | VegaPublish/vega-studio | import PropTypes from 'prop-types'
import React from 'react'
import Draggable from 'react-draggable'
export default class Mover extends React.Component {
static propTypes = {
children: PropTypes.node
}
constructor(props, args) {
super(props, args)
this.state = {
x: 50,
y: 50
}
}
handleStop = (event, element) => {
const scrollTop = document.getElementById('myScrollContainerId').scrollTop
// Trigger window resize to force redrawing of the popover component
window.dispatchEvent(new Event('resize'))
this.setState({
x: event.pageX - event.offsetX,
y: event.pageY - event.offsetY + scrollTop
})
}
render() {
return (
<div className="moverElement">
<Draggable onStop={this.handleStop}>
<div
style={{
zIndex: 1061,
position: 'absolute',
cursor: 'move',
color: 'white',
backgroundColor: 'red',
padding: '10px'
}}
>
Move me
</div>
</Draggable>
<div
style={{
position: 'absolute',
top: `${this.state.y + 50}px`,
left: `${this.state.x - 10}px`
}}
>
<div
style={{
color: 'red',
position: 'absolute',
zIndex: '5000',
backgroundColor: 'black'
}}
>
x: {this.state.x - 10} y: {this.state.y + 50}
</div>
{this.props.children}
</div>
</div>
)
}
}
|
ui/src/main/js/components/UpdatePreview.js | crashlytics/aurora | import React from 'react';
import { Link } from 'react-router-dom';
import PanelGroup, { Container } from 'components/Layout';
import { RelativeTime } from 'components/Time';
import { getClassForUpdateStatus, updateStats } from 'utils/Update';
export default function UpdatePreview({ update }) {
const stats = updateStats(update);
const {job: {role, environment, name}, id} = update.update.summary.key;
return (<Container>
<PanelGroup noPadding title=''>
<div
className={`update-preview ${getClassForUpdateStatus(update.update.summary.state.status)}`}>
<Link
to={`/scheduler/${role}/${environment}/${name}/update/${id}`}>
Update In Progress
</Link>
<span className='update-preview-details'>
started by <strong>{update.update.summary.user}</strong> <span>
<RelativeTime ts={update.update.summary.state.createdTimestampMs} /></span>
</span>
<span className='update-preview-progress'>
{stats.instancesUpdated} / {stats.totalInstancesToBeUpdated} ({stats.progress}%)
</span>
</div>
</PanelGroup>
</Container>);
}
|
src/main/app/scripts/views/Home.js | ondrejhudek/pinboard | import React from 'react'
import Login from '../components/auth/Login'
class HomeView extends React.Component {
render() {
return (
<div className="view-homepage">
<Login />
</div>
)
}
}
export default HomeView
|
src/components/Widgets/ProgressPie.js | RegOpz/RegOpzWebApp | import React, { Component } from 'react';
import {
PieChart,
XAxis,
YAxis,
CartesianGrid,
Pie,
Cell,
Tooltip,
Legend,
ResponsiveContainer,
Label
} from 'recharts';
class ProgressPie extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{
name: this.props.currentValueTag,
value: Math.round((this.props.currentValue * 100) / this.props.maxValue),
color: this.props.currentValueColor
},
{
name: this.props.maxValueTag,
value: Math.round((this.props.maxValue - this.props.currentValue) * 100 / this.props.maxValue),
color: this.props.maxValueColor
}
]
};
}
componentWillReceiveProps(nextProps) {
let currentValue = nextProps.currentValue;
let currentValueColor = nextProps.currentValueColor;
let currentValueTag = nextProps.currentValueTag;
let maxValue = nextProps.maxValue;
let maxValueColor = nextProps.maxValueColor;
let maxValueTag = nextProps.maxValueTag;
this.setState({
data: [
{
name: currentValueTag,
value: Math.round((currentValue * 100) / maxValue),
color: currentValueColor
},
{
name: maxValueTag,
value: Math.round((maxValue - currentValue) * 100 / maxValue),
color: maxValueColor
}
]
})
}
render() {
return (
<div className="tile_count">
<div className="tile_stats_count">
<span className="count_top">
<i className={'fa fa-' + this.props.iconName}></i>
{" " + this.props.titleText}
</span>
<div className={'count ' + (this.props.countColor ? this.props.countColor : '')}>
{this.props.countValue}
</div>
<div className="count_bottom">
<ResponsiveContainer height={this.props.height} width="100%">
<PieChart>
<Pie
onClick={this.props.handleClick}
name={this.props.legend}
data={this.state.data}
cx="50%"
cy="50%"
innerRadius={this.props.innerRadius}
outerRadius={this.props.outerRadius}
startAngle={90}
endAngle={450}
>
{
this.state.data.map((element) => {
return (
<Cell fill={element.color} />
);
})
}
<Label value={this.state.data[0].value + '%'} position="center" />
</Pie>
</PieChart>
</ResponsiveContainer>
</div>
</div >
</div>
);
}
}
export default ProgressPie; |
src/client/home/index.react.js | jirastom/react-learnig | import Component from '../components/component.react';
import DocumentTitle from 'react-document-title';
import React from 'react';
import {FormattedHTMLMessage} from 'react-intl';
import {Link} from 'react-router';
import Categories from '../categories/categories.react';
export default class Index extends Component {
static propTypes = {
msg: React.PropTypes.object.isRequired
}
render() {
const {msg: {home: msg}} = this.props;
return (
<DocumentTitle title={msg.title}>
<div className="home-page">
<p>
<FormattedHTMLMessage message={msg.infoHtml} />{' '}
<Link to="todos">{msg.todos}</Link>.
<Categories actions={this.props.actions.categories} data={this.props.categories.data} isLoaded={this.props.categories.isLoaded}/>
</p>
</div>
</DocumentTitle>
);
}
}
|
src/icons/Forward30Icon.js | kiloe/ui | import React from 'react';
import Icon from '../Icon';
export default class Forward30Icon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M19.1 27h.9c.4 0 .7-.1 1-.3s.3-.5.3-.9c0-.2 0-.3-.1-.4s-.1-.3-.2-.4-.2-.2-.4-.2-.3-.1-.5-.1-.3 0-.4.1-.3.1-.4.2-.2.2-.2.3-.1.2-.1.4h-1.7c0-.4.1-.7.2-1s.3-.5.6-.7.5-.4.9-.5.7-.2 1.1-.2c.4 0 .8.1 1.2.2s.7.3.9.5.5.5.6.8.2.7.2 1.1c0 .2 0 .4-.1.5s-.1.3-.3.5-.2.3-.4.4-.3.2-.6.3c.5.2.8.4 1.1.8s.4.8.4 1.2c0 .4-.1.8-.2 1.1s-.4.6-.6.8-.6.4-1 .5-.8.2-1.2.2c-.4 0-.7 0-1.1-.1s-.7-.2-.9-.5-.5-.5-.7-.8-.2-.7-.2-1.1h1.7c0 .2 0 .3.1.4s.1.2.3.3.2.2.4.2.3.1.5.1.4 0 .5-.1.3-.1.4-.2.2-.2.3-.4.1-.3.1-.5 0-.4-.1-.6-.2-.3-.3-.4-.3-.2-.4-.2-.4-.1-.6-.1h-.9V27zm11.5 1.5c0 .6-.1 1.2-.2 1.6s-.4.9-.6 1.2-.6.5-.9.7-.7.2-1.2.2-.8-.1-1.2-.2-.7-.4-.9-.7-.5-.7-.6-1.1-.2-1-.2-1.6V27c0-.6.1-1.2.2-1.6s.3-.8.6-1.1.6-.5.9-.7.7-.2 1.2-.2.8.1 1.2.2.7.4.9.7.5.7.6 1.1.2 1 .2 1.6v1.5zm-1.7-1.7c0-.4 0-.7-.1-1s-.1-.5-.2-.6-.2-.3-.4-.3-.3-.1-.5-.1-.4 0-.5.1-.3.2-.4.3-.2.4-.2.6-.1.6-.1 1v1.9c0 .4 0 .7.1 1s.1.5.2.6.2.3.4.3.3.1.5.1.4 0 .5-.1.3-.2.4-.3.2-.4.2-.6.1-.6.1-1v-1.9zM8 26c0 8.8 7.2 16 16 16s16-7.2 16-16h-4c0 6.6-5.4 12-12 12s-12-5.4-12-12 5.4-12 12-12v8l10-10L24 2v8c-8.8 0-16 7.2-16 16z"/></svg>;}
}; |
components/Icon/Icon.js | chrisspang/loggins | import React, { Component } from 'react';
import invariant from 'invariant';
import styles from './Icon.css';
import icons from './icons';
export default class Icon extends Component {
constructor(props) {
super(props);
invariant(
icons[props.name],
`Icon(): No icon exists for "${props.name}"`
);
}
render() {
const css = [
styles.root,
styles[this.props.name],
this.props.className || '',
].join(' ');
return (
<span
{...this.props}
className={css}
dangerouslySetInnerHTML={{ __html: icons[this.props.name] }}
/>
);
}
}
Icon.propTypes = {
name: React.PropTypes.string.isRequired,
className: React.PropTypes.string,
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.