path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
client/src/components/Admin/Issue/index.js | dotkom/super-duper-fiesta | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import { VOTING_NOT_STARTED, VOTING_IN_PROGRESS, VOTING_FINISHED } from 'common/actionTypes/issues';
import {
adminCloseIssue,
adminDeleteIssue,
enableVoting,
disableVoting,
} from 'features/adminButtons/actionCreators';
import { getIssueText, activeIssueExists, getIssue, getIssueKey } from 'features/issue/selectors';
import Button from '../../Button';
import Card from '../../Card';
import Dialog from '../../Dialog';
import ButtonIconText from '../../ButtonIconText';
import Pin from '../Pin';
import css from './Issue.css';
class Issue extends React.Component {
constructor(props) {
super(props);
this.state = {
redirectToEditIssue: false,
showDeleteIssueDialog: false,
showCloseIssueDialog: false,
showDisableVotingDialog: false,
};
}
onClickDeleteIssue() {
this.setState({ showDeleteIssueDialog: true });
}
onClickCloseIssue() {
this.setState({ showCloseIssueDialog: true });
}
deleteIssue() {
this.setState({ showDeleteIssueDialog: false });
this.props.deleteIssue();
}
closeIssue() {
this.setState({ showCloseIssueDialog: false });
this.props.closeIssue();
}
votingBtnOnClick() {
if (this.props.issueStatus === VOTING_NOT_STARTED) {
this.props.enableVoting();
} else if (this.props.issueStatus === VOTING_IN_PROGRESS) {
this.setState({ showDisableVotingDialog: true });
}
}
disableVoting() {
this.setState({ showDisableVotingDialog: false });
this.props.disableVoting();
}
closeDeleteDialog() {
this.setState({ showDeleteIssueDialog: false });
}
closeCloseDialog() {
this.setState({ showCloseIssueDialog: false });
}
closeDisableVotingDialog() {
this.setState({ showDisableVotingDialog: false });
}
render() {
const {
issueIsActive, issueStatus, issueText, pin, registrationOpen,
} = this.props;
const { showDeleteIssueDialog, showCloseIssueDialog, showDisableVotingDialog } = this.state;
const votingInProgress = issueStatus === VOTING_IN_PROGRESS;
let enableDisableVotingBtnText;
if (issueStatus === VOTING_NOT_STARTED) enableDisableVotingBtnText = 'Start votering';
else if (issueStatus === VOTING_IN_PROGRESS) enableDisableVotingBtnText = 'Avslutt votering';
else enableDisableVotingBtnText = 'Votering er ferdig';
return (
<Card classes={css.issue}>
{this.state.redirectToEditIssue && <Redirect to="/admin/question" />}
<Dialog
title="Bekreft sletting av sak"
subtitle={`Bekreft sletting av "${issueText}"`}
visible={showDeleteIssueDialog}
onClose={() => this.closeDeleteDialog()}
>
<Button background onClick={() => this.deleteIssue()}>Bekreft</Button>
<Button
background
onClick={() => this.closeDeleteDialog()}
>Avbryt</Button>
</Dialog>
<Dialog
title="Bekreft avslutting av sak"
subtitle={`Bekreft avslutting av "${issueText}"`}
visible={showCloseIssueDialog}
onClose={() => this.closeCloseDialog()}
>
<Button background onClick={() => this.closeIssue()}>Bekreft</Button>
<Button
background
onClick={() => this.closeCloseDialog()}
>Avbryt</Button>
</Dialog>
<Dialog
title="Bekreft avslutting av votering"
subtitle={`Bekreft avslutting av votering for "${issueText}"`}
visible={showDisableVotingDialog}
onClose={() => this.closeDisableVotingDialog()}
>
<Button background onClick={() => this.disableVoting()}>Bekreft</Button>
<Button
background
onClick={() => this.closeDisableVotingDialog()}
>Avbryt</Button>
</Dialog>
<div className={css.content}>
<div>
<Pin code={registrationOpen ? pin : 'Registreringen er ikke åpen.'} />
<p className={css.title}>Aktiv sak</p>
</div>
{issueIsActive && <div className={css.actions}>
<ButtonIconText
text={enableDisableVotingBtnText}
iconClass={votingInProgress || issueStatus === VOTING_FINISHED
? css.lock : css.unlock}
onClick={() => this.votingBtnOnClick()}
disabled={this.props.issueStatus === VOTING_FINISHED}
/>
<ButtonIconText
text="Rediger"
iconClass={css.edit}
onClick={() => { this.setState({ redirectToEditIssue: true }); }}
/>
<ButtonIconText
text="Avslutt" iconClass={css.end}
onClick={() => this.onClickCloseIssue()}
/>
<ButtonIconText
text="Slett"
iconClass={css.delete}
onClick={() => this.onClickDeleteIssue()}
/>
</div>
}
</div>
<p>{issueText}</p>
</Card>
);
}
}
Issue.defaultProps = {
pin: 0,
issueStatus: VOTING_NOT_STARTED,
registrationOpen: false,
};
Issue.propTypes = {
closeIssue: PropTypes.func.isRequired,
deleteIssue: PropTypes.func.isRequired,
disableVoting: PropTypes.func.isRequired,
enableVoting: PropTypes.func.isRequired,
issueIsActive: PropTypes.bool.isRequired,
issueStatus: PropTypes.string,
issueText: PropTypes.string.isRequired,
pin: PropTypes.number,
registrationOpen: PropTypes.bool,
};
const mapStateToProps = state => ({
issueIsActive: activeIssueExists(state),
issueStatus: getIssueKey(state, 'status'),
issueText: getIssueText(state),
issue: getIssue(state),
pin: state.meeting.pin,
registrationOpen: state.meeting.registrationOpen,
});
// Following this example since we need id from state
// https://github.com/reactjs/react-redux/issues/237#issuecomment-168817739
const mergeProps = (stateProps, dispatchProps, ownProps) => {
const { dispatch } = dispatchProps;
return {
...ownProps,
...stateProps,
closeIssue: () => {
dispatch(adminCloseIssue({ issue: stateProps.issue.id }));
},
deleteIssue: () => {
dispatch(adminDeleteIssue({ issue: stateProps.issue.id }));
},
disableVoting: () => {
dispatch(disableVoting({ issue: stateProps.issue.id }));
},
enableVoting: () => {
dispatch(enableVoting({ issue: stateProps.issue.id }));
},
};
};
export default Issue;
export const IssueContainer = connect(
mapStateToProps,
null,
mergeProps,
)(Issue);
|
modules/gui/src/widget/shape.js | openforis/sepal | import {compose} from 'compose'
import Icon from 'widget/icon'
import PropTypes from 'prop-types'
import React from 'react'
import Tooltip from 'widget/tooltip'
import lookStyles from 'style/look.module.css'
import styles from './shape.module.css'
import withForwardedRef from 'ref'
class _Shape extends React.Component {
classNames() {
const {chromeless, className, additionalClassName, look, size, shape, air,
alignment, width, disableHover, disableTransitions} = this.props
return className ? className : [
styles.shape,
styles[`size-${size}`],
styles[`shape-${shape}`],
styles[`air-${air}`],
styles[`alignment-${alignment}`],
styles[`width-${width}`],
lookStyles.look,
lookStyles[look],
chromeless ? lookStyles.chromeless : null,
disableTransitions ? lookStyles.noTransitions : null,
disableHover ? lookStyles.noHover : null,
additionalClassName
].join(' ')
}
renderTooltip(contents) {
const {tooltip, tooltipPlacement, tooltipDisabled, disabled} = this.props
return tooltip && !tooltipDisabled && !disabled ? (
<Tooltip msg={tooltip} placement={tooltipPlacement}>
{contents}
</Tooltip>
) : contents
}
renderShape(contents) {
const {disabled, forwardedRef} = this.props
return (
<div
ref={forwardedRef}
className={this.classNames()}
disabled={disabled}
>
{contents}
</div>
)
}
renderIcon() {
const {icon, iconType, iconAttributes} = this.props
return (
<Icon
name={icon}
type={iconType}
attributes={iconAttributes}
/>
)
}
renderLabel() {
const {label} = this.props
return (
<span>{label}</span>
)
}
renderContents() {
const {icon, iconPlacement, content, tail, children} = this.props
return (
<div className={styles.contents}>
{icon && iconPlacement === 'left' ? this.renderIcon() : null}
{children ? children : content}
{icon && iconPlacement === 'right' ? this.renderIcon() : null}
{tail}
</div>
)
}
render() {
const {shown = true} = this.props
return shown ? (
this.renderTooltip(
this.renderShape(
this.renderContents()
)
)
) : null
}
}
export const Shape = compose(
_Shape,
withForwardedRef()
)
Shape.propTypes = {
additionalClassName: PropTypes.string,
air: PropTypes.oneOf(['normal', 'more']),
alignment: PropTypes.oneOf(['left', 'center', 'right']),
children: PropTypes.any,
chromeless: PropTypes.any,
className: PropTypes.string,
content: PropTypes.any,
disabled: PropTypes.any,
disableHover: PropTypes.any,
disableTransitions: PropTypes.any,
icon: PropTypes.string,
iconAttributes: PropTypes.any,
iconPlacement: PropTypes.oneOf(['left', 'right']),
iconType: PropTypes.string,
look: PropTypes.oneOf(['default', 'highlight', 'selected', 'transparent', 'add', 'apply', 'cancel']),
shape: PropTypes.oneOf(['rectangle', 'pill', 'circle', 'none']),
shown: PropTypes.any,
size: PropTypes.oneOf(['x-small', 'small', 'normal', 'large', 'x-large', 'xx-large']),
tail: PropTypes.string,
tooltip: PropTypes.string,
tooltipDisabled: PropTypes.any,
tooltipPlacement: PropTypes.oneOf(['top', 'bottom', 'left', 'right']),
width: PropTypes.oneOf(['fit', 'fill'])
}
Shape.defaultProps = {
air: 'normal',
alignment: 'left',
iconPlacement: 'left',
look: 'default',
shape: 'rectangle',
shown: true,
size: 'normal',
width: 'fit'
}
|
app/components/areas/area-detail/index.js | Vizzuality/forest-watcher | // @flow
import type { Area } from 'types/areas.types';
import type { Route } from 'types/routes.types';
import React, { Component } from 'react';
import { Alert, View, Image, ScrollView, Text, TextInput, TouchableHighlight } from 'react-native';
import debounceUI from 'helpers/debounceUI';
import { trackScreenView } from 'helpers/analytics';
import i18n from 'i18next';
import moment from 'moment';
import Theme, { isSmallScreen } from 'config/theme';
import ActionButton from 'components/common/action-button';
import styles from './styles';
import { Navigation, NavigationButtonPressedEvent } from 'react-native-navigation';
import { withSafeArea } from 'react-native-safe-area';
import VerticalSplitRow from 'components/common/vertical-split-row';
import RoutePath from 'components/common/route-path';
import { formatDistance, getDistanceOfPolyline } from 'helpers/map';
import { pushMapScreen } from 'screens/maps';
const RoutePreviewSize = isSmallScreen ? 86 : 122;
const routeMapBackground = require('assets/routeMapBackground.png');
const SafeAreaView = withSafeArea(View, 'margin', 'vertical');
const editIcon = require('assets/edit.png');
const deleteIcon = require('assets/delete_white.png');
type State = {
name: ?string,
editingName: boolean
};
type Props = {
updateArea: Area => void,
deleteArea: (?string) => void,
isConnected: boolean,
componentId: string,
area: ?Area,
disableDelete: boolean,
routes: Array<Route>,
initialiseAreaLayerSettings: (string, string) => void
};
class AreaDetail extends Component<Props, State> {
static options(passProps: {}) {
return {
topBar: {
rightButtons: [
{
id: 'deleteArea',
icon: deleteIcon,
color: Theme.colors.turtleGreen
}
]
}
};
}
constructor(props: Props) {
super(props);
Navigation.events().bindComponent(this);
this.state = {
name: props.area?.name,
editingName: false
};
}
componentDidMount() {
trackScreenView('AreaDetail');
}
navigationButtonPressed({ buttonId }: NavigationButtonPressedEvent) {
if (buttonId === 'deleteArea') {
this.handleDeleteArea();
}
}
onEditPress = () => {
this.setState({ editingName: true });
};
onNameChange = (name: string) => {
this.setState({ name });
};
// $FlowFixMe
onNameSubmit = debounceUI((ev: SyntheticInputEvent<*>) => {
// $FlowFixMe
const newName = ev.nativeEvent.text;
const name = this.props.area?.name;
if (newName && newName !== name) {
this.setState({
name: newName,
editingName: false
});
const updatedArea = { ...this.props.area, name: newName };
this.props.updateArea(updatedArea);
this.replaceRouteTitle(updatedArea.name);
}
});
onRoutePress = debounceUI((route: Route) => {
this.props.initialiseAreaLayerSettings(route.id, route.areaId);
pushMapScreen(this.props.componentId, { areaId: route.areaId, routeId: route.id });
});
onRouteSettingsPress = debounceUI((route: Route) => {
Navigation.showModal({
stack: {
children: [
{
component: {
name: 'ForestWatcher.RouteDetail',
passProps: {
routeId: route.id,
routeName: route.name
}
}
}
]
}
});
});
replaceRouteTitle = (title: string) => {
Navigation.mergeOptions(this.props.componentId, {
topBar: {
title: {
text: title
}
}
});
};
handleDeleteArea = debounceUI(() => {
if (this.props.routes.length > 0) {
Alert.alert(
i18n.t('areaDetail.confirmDeleteWithRoutesTitle'),
i18n.t('areaDetail.confirmDeleteWithRoutesMessage'),
[
{
text: i18n.t('commonText.confirm'),
onPress: () => {
this.confirmDeleteArea();
}
},
{
text: i18n.t('commonText.cancel'),
style: 'cancel'
}
]
);
} else {
this.confirmDeleteArea();
}
});
confirmDeleteArea = debounceUI(() => {
if (this.props.isConnected) {
this.props.deleteArea(this.props.area?.id);
Navigation.pop(this.props.componentId);
} else {
Alert.alert(
i18n.t('commonText.connectionRequiredTitle'),
i18n.t('commonText.connectionRequired'),
[{ text: 'OK' }],
{
cancelable: false
}
);
}
});
render() {
const { area, disableDelete, routes } = this.props;
if (!area) {
return null;
}
return (
<SafeAreaView style={styles.container}>
<ScrollView
style={styles.container}
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
keyboardShouldPersistTaps={'always'}
>
<View>
<Text style={styles.title}>{i18n.t('commonText.name')}</Text>
{!this.state.editingName ? (
<View style={styles.section}>
<Text style={styles.name}>{this.state.name}</Text>
<TouchableHighlight activeOpacity={0.5} underlayColor="transparent" onPress={this.onEditPress}>
<Image style={Theme.icon} source={editIcon} />
</TouchableHighlight>
</View>
) : (
<View style={styles.section}>
<TextInput
autoFocus
autoCorrect={false}
multiline={false}
style={styles.input}
autoCapitalize="none"
value={this.state.name !== null ? this.state.name : this.props.area?.name}
onChangeText={this.onNameChange}
onSubmitEditing={this.onNameSubmit}
onBlur={this.onNameSubmit}
underlineColorAndroid="transparent"
selectionColor={Theme.colors.turtleGreen}
placeholderTextColor={Theme.fontColors.light}
/>
</View>
)}
</View>
<View style={styles.row}>
<Text style={styles.title}>{i18n.t('commonText.boundaries')}</Text>
<View style={styles.imageContainer}>
<Image style={styles.image} source={{ uri: area.image }} />
</View>
</View>
{routes.length > 0 && (
<View style={styles.row}>
<Text style={styles.title}>{i18n.t('settings.yourRoutes')}</Text>
{routes.map(route => {
const routeDistance = getDistanceOfPolyline(route.locations);
const dateText = moment(route.endDate).format('ll');
const distanceText = formatDistance(routeDistance, 1, false);
const subtitle = dateText + ', ' + distanceText;
// const action = {
// icon,
// callback: () => {
// onPress(item.title);
// },
// position
// };
return (
<VerticalSplitRow
backgroundImageResizeMode={'repeat'}
key={route.id}
onSettingsPress={this.onRouteSettingsPress.bind(this, route)}
onPress={this.onRoutePress.bind(this, route)}
title={route.name}
renderImageChildren={() => {
return <RoutePath route={route} size={RoutePreviewSize} />;
}}
imageSrc={routeMapBackground}
subtitle={subtitle}
largerPadding
largeImage
/>
);
})}
</View>
)}
{!disableDelete && (
<View style={styles.buttonContainer}>
<ActionButton onPress={this.handleDeleteArea} delete text={i18n.t('areaDetail.delete')} />
</View>
)}
</ScrollView>
</SafeAreaView>
);
}
}
export default AreaDetail;
|
app/component/quiz/Domicilio.js | vagnerpraia/ipeasurvey | import React, { Component } from 'react';
import { PanResponder, StyleSheet, TextInput, ToastAndroid, View } from 'react-native';
import { Body, Button, Card, CardItem, Container, Content, Footer, FooterTab, Header, Icon, Left, Right, Text, Title } from 'native-base';
import SideMenu from 'react-native-side-menu';
import SideMenuDomicilio from './SideMenuDomicilio';
import ReplyInputCurrency from './reply/ReplyInputCurrency';
import ReplyInputNumeric from './reply/ReplyInputNumeric';
import ReplyMultiSelect from './reply/ReplyMultiSelect';
import ReplyRadio from './reply/ReplyRadio';
import ReplyText from './reply/ReplyText';
import ReplyTime from './reply/ReplyTime';
import { passQuestion } from './business/PassQuestionDomicilio';
import FileStore from './../../FileStore';
import DomicilioData from './../../data/DomicilioData';
import { questoes } from './../../data/QuestoesDomicilio';
import { styles } from './../../Styles';
var type = (function(global) {
var cache = {};
return function(obj) {
var key;
return obj === null ? 'null'
: obj === global ? 'global'
: (key = typeof obj) !== 'object' ? key
: obj.nodeType ? 'object'
: cache[key = ({}).toString.call(obj)]
|| (cache[key] = key.slice(8, -1).toLowerCase());
};
}(this));
export default class Domicilio extends Component {
constructor(props) {
super(props);
this.state = {
admin: this.props.admin,
quiz: this.props.quiz
};
}
componentWillMount(){
if(this.state.quiz.domicilio === null){
this.state.quiz.domicilio = new DomicilioData(this.state.admin.id);
}
FileStore.saveFileDomicilio(this.state.quiz.domicilio);
let questao = questoes[this.state.admin.indexPage].id.replace(/\D/g,'');
for(key in passQuestion){
if(questao == passQuestion[key].questao){
//this.state.admin.maxQuestion = passQuestion[key].passe;
for (i = questao + 1; i < passQuestion[key].passe; i++) {
for(key in this.state.quiz){
if(key.replace(/\D/g,'') == i){
this.state.quiz[key] = -1;
}
}
}
break;
}
}
idQuestao = 'questao_' + questoes[this.state.admin.indexPage].id;
numeroQuestao = questoes[this.state.admin.indexPage].id.replace(/\D/g,'');
}
popQuizScreen(){
if(this.state.admin.indexPage === 0 && this.state.quiz['questao_1'] === null){
this.state.quiz.domicilio = null;
FileStore.deleteDomicilio(this.state.admin.id);
};
this.props.navigator.replacePreviousAndPop({
name: 'quiz',
admin: this.state.admin,
quiz: this.state.quiz,
isOpen: false
});
}
popScreen(){
if(this.state.admin.indexPage > 0){
this.state.admin.indexPage = Number(this.state.admin.indexPage) - 1;
this.props.navigator.replacePreviousAndPop({
name: 'domicilio',
admin: this.state.admin,
quiz: this.state.quiz
});
}else{
ToastAndroid.showWithGravity('Não há como voltar mais', ToastAndroid.SHORT, ToastAndroid.CENTER);
}
}
pushScreen(){
let flagResponse = true;
if(type(this.state.quiz.domicilio[idQuestao]) == 'array'){
if(this.state.quiz.domicilio[idQuestao].length == 0){
flagResponse = false;
}
}else{
if(this.state.quiz.domicilio[idQuestao] == null){
flagResponse = false;
}
}
if(flagResponse || Number(numeroQuestao) + 1 <= this.state.admin.maxQuestion){
if(Number(numeroQuestao) + 1 <= this.state.admin.maxQuestion){
this.state.admin.indexPage = Number(this.state.admin.indexPage) + 1;
FileStore.saveFileDomicilio(this.state.quiz.domicilio);
if(this.state.admin.indexPage >= questoes.length){
ToastAndroid.showWithGravity('Questionário Finalizado\nNão há como avançar mais', ToastAndroid.SHORT, ToastAndroid.CENTER);
}else{
this.props.navigator.push({
name: 'domicilio',
admin: this.state.admin,
quiz: this.state.quiz
});
}
}else{
ToastAndroid.showWithGravity('Responda a questão ' + numeroQuestao, ToastAndroid.SHORT, ToastAndroid.CENTER);
}
}else{
ToastAndroid.showWithGravity('Responda a questão', ToastAndroid.SHORT, ToastAndroid.CENTER);
}
}
updateMenuState() {
this.setState({
isOpen: !this.state.isOpen,
});
}
setMenuState(isOpen) {
this.setState({
isOpen: isOpen
});
}
render() {
let isOpen = this.state.isOpen;
let admin = this.state.admin;
let quiz = this.state.quiz;
let questao = questoes[admin.indexPage];
let pergunta_extensao = questao.pergunta_extensao;
const menu = <SideMenuDomicilio admin={admin} quiz={quiz} navigator={this.props.navigator} />;
function renderIf(condition, contentIf, contentElse = null) {
if (condition) {
return contentIf;
} else {
return contentElse;
}
}
return (
<Container style={styles.container}>
<Header style={styles.header}>
<Left>
<Button transparent onPress={() => {this.popQuizScreen()}}>
<Icon name='ios-arrow-back' />
</Button>
</Left>
<Body style={styles.bodyHeader}>
<Title>{questao.titulo}</Title>
</Body>
<Right>
<Button transparent onPress={() => {this.updateMenuState()}}>
<Text></Text>
</Button>
</Right>
</Header>
<Content>
<Card>
<CardItem style={styles.cardItemQuestao}>
<Text style={styles.questao}>{questao.id.replace(/\D/g,'') + '. ' + questao.pergunta}</Text>
<Text style={styles.observacaoQuestao}>{questao.observacao_pergunta}</Text>
</CardItem>
{renderIf(questao.pergunta_secundaria !== '',
<CardItem style={styles.pergunta_secundaria}>
<Text style={styles.questao_secundaria}>{questao.id.replace(/[0-9]/g, '').toUpperCase() + ') ' + questao.pergunta_secundaria.pergunta}</Text>
<Text note>{questao.pergunta_secundaria.observacao_pergunta}</Text>
</CardItem>
)}
<CardItem cardBody style={{justifyContent: 'center'}}>
{renderIf(questao.tipo === 'input_currency',
<ReplyInputCurrency admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} />
)}
{renderIf(questao.tipo === 'input_numeric',
<ReplyInputNumeric admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} />
)}
{renderIf(questao.tipo === 'multiple',
<ReplyMultiSelect admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} />
)}
{renderIf(questao.tipo === 'radio',
<ReplyRadio admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} />
)}
{renderIf(questao.tipo === 'text',
<ReplyText admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} />
)}
{renderIf(questao.tipo === 'input_time',
<ReplyTime admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} />
)}
</CardItem>
{renderIf(pergunta_extensao != '',
<CardItem>
<Text style={styles.observacaoQuestao}>{pergunta_extensao.pergunta}</Text>
<TextInput
style={{width: 500, fontSize: 20}}
keyboardType = 'default'
onChangeText = {(value) => {
if(quiz.domicilio[idQuestao] != null){
if(quiz.domicilio[idQuestao] == pergunta_extensao.referencia){
quiz.domicilio[idQuestao + '_secundaria'] = value;
}else if(quiz.domicilio[idQuestao].indexOf(Number(pergunta_extensao.referencia)) > -1){
quiz.domicilio[idQuestao + '_secundaria'] = value;
}
}
}}
defaultValue = {quiz.domicilio[idQuestao + '_secundaria']}
maxLength = {500}
/>
</CardItem>
)}
</Card>
</Content>
<Footer>
<FooterTab>
<Button style={{backgroundColor: '#005376'}} onPress={() => {this.popScreen()}}>
<Icon name='ios-arrow-back' />
</Button>
<Button style={{backgroundColor: '#005376'}} onPress={() => {this.pushScreen()}}>
<Icon name='ios-arrow-forward' />
</Button>
</FooterTab>
</Footer>
</Container>
);
}
}
|
research/reactNative/index.ios.js | huxinmin/PracticeMakesPerfect | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class reactNative extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('reactNative', () => reactNative);
|
src/index.js | webberdoo/react-redux-starter | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
|
src/icons/SocialJavascript.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class SocialJavascript extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g transform="translate(384 48)">
<g id="icon-javascript_1_1_">
<path d="M-176,40.001h-80v212.498c0,52.58-18.032,67.261-49.412,67.261c-14.705,0-27.948-2.521-38.25-6.063L-352,375.904
c14.7,5.062,37.259,8.096,54.907,8.096C-225.045,384-176,350.129-176,253.02V40.001L-176,40.001z"></path>
<path d="M-1.537,32C-78.98,32-128,75.998-128,134.154c0,50.083,37.751,81.44,92.641,101.665
c39.7,14.158,55.392,26.808,55.392,47.539c0,22.756-18.139,37.425-52.448,37.425c-31.863,0-60.789-10.64-80.394-21.255v-0.021
L-128,362.727c18.639,10.638,53.441,21.255,91.167,21.255C53.854,383.98,96,335.43,96,278.284c0-48.55-26.958-79.9-85.278-102.163
c-43.139-17.191-61.27-26.795-61.27-48.542c0-17.2,15.688-32.869,48.043-32.869c31.846,0,53.744,10.707,66.505,17.291l19.125-64
C63.125,39.22,36.188,32-1.537,32L-1.537,32z"></path>
</g>
</g>
</g>;
} return <IconBase>
<g transform="translate(384 48)">
<g id="icon-javascript_1_1_">
<path d="M-176,40.001h-80v212.498c0,52.58-18.032,67.261-49.412,67.261c-14.705,0-27.948-2.521-38.25-6.063L-352,375.904
c14.7,5.062,37.259,8.096,54.907,8.096C-225.045,384-176,350.129-176,253.02V40.001L-176,40.001z"></path>
<path d="M-1.537,32C-78.98,32-128,75.998-128,134.154c0,50.083,37.751,81.44,92.641,101.665
c39.7,14.158,55.392,26.808,55.392,47.539c0,22.756-18.139,37.425-52.448,37.425c-31.863,0-60.789-10.64-80.394-21.255v-0.021
L-128,362.727c18.639,10.638,53.441,21.255,91.167,21.255C53.854,383.98,96,335.43,96,278.284c0-48.55-26.958-79.9-85.278-102.163
c-43.139-17.191-61.27-26.795-61.27-48.542c0-17.2,15.688-32.869,48.043-32.869c31.846,0,53.744,10.707,66.505,17.291l19.125-64
C63.125,39.22,36.188,32-1.537,32L-1.537,32z"></path>
</g>
</g>
</IconBase>;
}
};SocialJavascript.defaultProps = {bare: false} |
app/views/Proposals/Proposal/Budgeting/Partial/Partial.js | RcKeller/STF-Refresh | import React from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import api from '../../../../../services'
import _ from 'lodash'
import { Select, Alert, message } from 'antd'
const Option = Select.Option
import { Boundary, Spreadsheet } from '../../../../../components'
/*
PARTIAL TAB:
Allows you to create a subset of a budget with more/less items
These can be "alternate" awards for partial or additional funding
both of which are common use cases
e.g. we want to fund 60k of a 100k ask for cloud computing credits
Create a partial here for 60k, then vote and approve it
*/
@connect(
(state, props) => ({
proposal: state.db.proposal._id,
// Use the most recent manifest as a baseline for this partial.
manifests: state.db.proposal.manifests,
user: state.user._id
}),
dispatch => ({ api: bindActionCreators(api, dispatch) })
)
class Partial extends React.Component {
static propTypes = {
api: PropTypes.object,
// Proposal / Author-User ID
user: PropTypes.string,
proposal: PropTypes.string,
manifests: PropTypes.array
}
constructor (props) {
super(props)
// The user can specify the manifest they want to import items from.
// We collect the index from them. To start, we use the most recent budget.
let index = this.props.manifests.length - 1 || 0
this.state = { index }
}
handleChange = (index) => this.setState({ index })
handleSubmit = (items) => {
const { api, proposal, user: author } = this.props
const partial = { proposal, type: 'partial', author, items }
const params = {
populate: ['items'],
transform: proposal => ({ proposal }),
update: ({ proposal: (prev, next) => {
let changed = Object.assign({}, prev)
changed.manifests.push(next)
return changed
}})
}
// Post it - partials are a one-time deal, they aren't patched after the fact.
api.post('manifest', partial, params)
.then(message.success(`Partial budget created! Please add it to the docket.`))
.catch(err => {
message.warning(`Failed to create partial budget - Unexpected client error`)
console.warn(err)
})
}
render (
{ manifests } = this.props,
{ index } = this.state
) {
const { title, body, items, total } = manifests[index]
const data = items.length > 0
? items.map(item => _.omit(item, ['_id', '__v', 'manifest', 'report']))
: []
const newData = { tax: 10.1, quantity: 1, price: 0 }
return (
<section>
<Boundary title='Partial Budget Wizard'>
<Alert type='info' showIcon banner
message='Partial Budgets'
description='For alternative budget choices, partial awards, etc.'
/>
<br />
<p>Partial budgets are how we fund specific elements of a budget. The process involves us pulling data from a prior budget you can select below (the original proposal, a different partial, or supplemental award), making your modifications, and submitting it.</p>
<p>When voting on a proposal, partials are a separate vote. This is for a variety of reasons, mostly so we can judge a proposal's merits objectively without factoring in any addenums that the committee has proposed.</p>
<h4>Import items from:</h4>
<Select value={index.toString()} style={{ width: '100%' }} onChange={this.handleChange}>
{manifests.map((budget, i) => (
<Option key={i} value={i.toString()} >{
`Budget #${i + 1} (${_.capitalize(budget.type)}) ${budget.title ? ' - ' + budget.title : ''}`}</Option>
))}
</Select>
<h4>{title}</h4>
<p>{body}</p>
<Spreadsheet
data={data}
onSubmit={this.handleSubmit}
disabled={false}
/>
</Boundary>
</section>
)
}
}
export default Partial
|
node_modules/react-native/Libraries/Components/Keyboard/Keyboard.js | kssujithcj/TestMobileCenter | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Keyboard
* @flow
*/
'use strict';
const invariant = require('fbjs/lib/invariant');
const NativeEventEmitter = require('NativeEventEmitter');
const KeyboardObserver = require('NativeModules').KeyboardObserver;
const dismissKeyboard = require('dismissKeyboard');
const KeyboardEventEmitter = new NativeEventEmitter(KeyboardObserver);
type KeyboardEventName =
| 'keyboardWillShow'
| 'keyboardDidShow'
| 'keyboardWillHide'
| 'keyboardDidHide'
| 'keyboardWillChangeFrame'
| 'keyboardDidChangeFrame';
type KeyboardEventData = {
endCoordinates: {
width: number,
height: number,
screenX: number,
screenY: number,
},
};
type KeyboardEventListener = (e: KeyboardEventData) => void;
// The following object exists for documentation purposes
// Actual work happens in
// https://github.com/facebook/react-native/blob/master/Libraries/EventEmitter/NativeEventEmitter.js
/**
* `Keyboard` module to control keyboard events.
*
* ### Usage
*
* The Keyboard module allows you to listen for native events and react to them, as
* well as make changes to the keyboard, like dismissing it.
*
*```
* import React, { Component } from 'react';
* import { Keyboard, TextInput } from 'react-native';
*
* class Example extends Component {
* componentWillMount () {
* this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
* this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
* }
*
* componentWillUnmount () {
* this.keyboardDidShowListener.remove();
* this.keyboardDidHideListener.remove();
* }
*
* _keyboardDidShow () {
* alert('Keyboard Shown');
* }
*
* _keyboardDidHide () {
* alert('Keyboard Hidden');
* }
*
* render() {
* return (
* <TextInput
* onSubmitEditing={Keyboard.dismiss}
* />
* );
* }
* }
*```
*/
let Keyboard = {
/**
* The `addListener` function connects a JavaScript function to an identified native
* keyboard notification event.
*
* This function then returns the reference to the listener.
*
* @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for. This
*can be any of the following:
*
* - `keyboardWillShow`
* - `keyboardDidShow`
* - `keyboardWillHide`
* - `keyboardDidHide`
* - `keyboardWillChangeFrame`
* - `keyboardDidChangeFrame`
*
* @param {function} callback function to be called when the event fires.
*/
addListener(eventName: KeyboardEventName, callback: KeyboardEventListener) {
invariant(false, 'Dummy method used for documentation');
},
/**
* Removes a specific listener.
*
* @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for.
* @param {function} callback function to be called when the event fires.
*/
removeListener(eventName: KeyboardEventName, callback: Function) {
invariant(false, 'Dummy method used for documentation');
},
/**
* Removes all listeners for a specific event type.
*
* @param {string} eventType The native event string listeners are watching which will be removed.
*/
removeAllListeners(eventName: KeyboardEventName) {
invariant(false, 'Dummy method used for documentation');
},
/**
* Dismisses the active keyboard and removes focus.
*/
dismiss() {
invariant(false, 'Dummy method used for documentation');
}
};
// Throw away the dummy object and reassign it to original module
Keyboard = KeyboardEventEmitter;
Keyboard.dismiss = dismissKeyboard;
module.exports = Keyboard;
|
src/svg-icons/editor/format-underlined.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatUnderlined = (props) => (
<SvgIcon {...props}>
<path d="M12 17c3.31 0 6-2.69 6-6V3h-2.5v8c0 1.93-1.57 3.5-3.5 3.5S8.5 12.93 8.5 11V3H6v8c0 3.31 2.69 6 6 6zm-7 2v2h14v-2H5z"/>
</SvgIcon>
);
EditorFormatUnderlined = pure(EditorFormatUnderlined);
EditorFormatUnderlined.displayName = 'EditorFormatUnderlined';
EditorFormatUnderlined.muiName = 'SvgIcon';
export default EditorFormatUnderlined;
|
src/components/Common/Alert/Alert.js | Jac21/reponotesreact | import React from 'react';
import PropTypes from 'prop-types';
import { css } from 'glamor';
const swatch = css({
display: 'block',
padding: `${1}em`,
fontSize: `${1}rem`,
color: '#fff'
});
const error = css({
backgroundColor: '#d91e18'
});
const Alert = ({ message }) => {
return (
<React.Fragment>
<div {...css(swatch, error)}> {message} </div>
</React.Fragment>
);
};
Alert.propTypes = {
kind: PropTypes.oneOf(['primary', 'warning', 'error']).isRequired,
message: PropTypes.string
};
export default React.memo(Alert);
|
packages/docs/components/Examples/static-toolbar/SimpleToolbarEditor/index.js | nikgraf/draft-js-plugin-editor | import React, { Component } from 'react';
import Editor, { createEditorStateWithText } from '@draft-js-plugins/editor';
import createToolbarPlugin from '@draft-js-plugins/static-toolbar';
import editorStyles from './editorStyles.module.css';
const staticToolbarPlugin = createToolbarPlugin();
const { Toolbar } = staticToolbarPlugin;
const plugins = [staticToolbarPlugin];
const text =
'The toolbar above the editor can be used for formatting text, as in conventional static editors …';
export default class SimpleStaticToolbarEditor extends Component {
state = {
editorState: createEditorStateWithText(text),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
componentDidMount() {
// fixing issue with SSR https://github.com/facebook/draft-js/issues/2332#issuecomment-761573306
// eslint-disable-next-line react/no-did-mount-set-state
this.setState({
editorState: createEditorStateWithText(text),
});
}
focus = () => {
this.editor.focus();
};
render() {
return (
<div>
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => {
this.editor = element;
}}
/>
<Toolbar />
</div>
</div>
);
}
}
|
src/components/FormMarcaAuto.js | aurigadl/EnvReactAsk | import React from 'react'
import SelectInput from './SelectInput.js'
import {remoteData} from '../utils/mrequest';
import {Tooltip, Card , Form , Input , message,
Col, Row, Button, Icon} from 'antd';
const FormItem = Form.Item;
const InputGroup = Input.Group;
var FormMarcaAuto = Form.create()(React.createClass({
getInitialState: function () {
return {
childSelectValue: undefined,
childSelectText: '',
inputValue: '',
newOptionMA: 0
};
},
//let emtpy fields and diseble button
componentDidMount: function(){
// To disabled submit button at the beginning.
this.props.form.validateFields();
},
//callback to get data from component selectinput
handleUserSelect: function (childSelectValue, childSelectText) {
this.setState({
childSelectValue: childSelectValue,
childSelectText: childSelectText
});
this.props.form.setFieldsValue({
marcaedit: childSelectText,
});
},
//Return all field to the initial state
handleReset: function (e) {
this.props.form.resetFields();
this.setState({
childSelectValue: '',
});
this.props.form.validateFields();
},
//Register change when the user enter characters
onChange(e) {
this.setState({inputValue: e.target.value});
},
//Create and edit option
handleSubmitForm: function (e) {
e.preventDefault();
const form = this.props.form;
const selecChildV = this.state.childSelectValue;
const selecChildT = this.state.childSelectText;
form.validateFields((err, values) => {
if (!err) {
const brand_new = values.marcaedit;
//If the user does not select an existing option
//create a new register
if (selecChildV === undefined || selecChildV === "") {
var params = { marca: brand_new };
var parreq = {
method: 'POST',
url: 'apiFuec/newMarca',
params: {'params': params}
};
remoteData(parreq,
(data) => {
message.success('Se creo el registro: ' + brand_new);
this.setState({newOptionMA: this.state.newOptionMA + 1});
//Update Container
this.props.newOptCont();
this.handleReset();
},
(err) => {
message.error('NO se creo el registro: '+ brand_new +
'\n Error :' + err.message.error)
}
);
//If the user select an existing option
//edit register selected.
} else {
var params = {
id: selecChildV,
name: brand_new
};
var parreq = {
method: 'PUT',
url: 'apiFuec/updateIdMarca',
params: {'params': params}
};
remoteData(parreq,
(data) => {
message.success('Se edito el registro (' + selecChildT + ') con ('+ brand_new+')');
this.setState({newOptionMA: this.state.newOptionMA + 1});
//Update Container
this.props.newOptCont();
this.handleReset();
},
(err) => {
message.error('No se edito el registro: '+ selecChildT +
'\n Error:' + err.message.error)
}
);
}
}
});
},
//Delete select option
handleDelete: function(e){
e.preventDefault();
var get_id = this.state.childSelectValue;
if(get_id){
const params = { id: get_id };
const parreq = {
method: 'DELETE',
url: 'apiFuec/deleteIdMarca',
params: {'params': params}
};
remoteData(parreq,
(data) => {
message.success('Se borro el registro: ' + this.state.childSelectText);
this.setState({newOptionMA: this.state.newOptionMA + 1});
//Update Container
this.props.newOptCont();
this.handleReset();
},
(err) => {
message.error('NO se borro el registro: '+ this.state.childSelectText +
'\n Error: ' + err.message.error)
}
);
}
},
render: function () {
const { getFieldDecorator, getFieldError, isFieldTouched } = this.props.form;
const marcaEditError = isFieldTouched('marcaedit') && getFieldError('marcaedit');
return (
<Card id={this.props.id} title="Marca de Carros" bordered={false}>
<Form onSubmit={this.handleSubmitForm}>
<FormItem>
<InputGroup compact>
<SelectInput
style={{ width: '88%' }}
url="apiFuec/allMarca"
value={{key:this.state.childSelectValue}}
newOption={this.state.newOptionMA}
onUserSelect={this.handleUserSelect}
/>
<Tooltip title={'Borrar el registro seleccionado'}>
<Button
onClick={this.handleDelete}
type="danger"
shape="circle"
icon="minus"/>
</Tooltip>
</InputGroup>
</FormItem>
<FormItem
validateStatus={marcaEditError ? 'error' : ''}
help={marcaEditError || ''}
>
{getFieldDecorator('marcaedit', {
rules: [{required: true,
whitespace: true,
min: '3',
initialValue: '',
message: 'Ingrese un nuevo nombre de marca!'}],
})(
<Input
placeholder="Editar o crear..."
onChange={this.onChange}/>
)}
</FormItem>
<FormItem>
<Button
disabled={getFieldError('marcaedit')}
type="primary"
htmlType="submit"
size="large">
Grabar
</Button>
<Button
style={{ marginLeft: 8 }}
htmlType="reset"
size="large"
onClick={this.handleReset}>
Limpiar
</Button>
</FormItem>
</Form>
</Card>
)
}
}));
export default FormMarcaAuto;
|
techCurriculum/ui/solutions/4.2/src/index.js | tadas412/EngineeringEssentials | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import '../stylesheet.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
assets/jqwidgets/demos/react/app/dropdownlist/righttoleftlayout/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxDropDownList from '../../../jqwidgets-react/react_jqxdropdownlist.js';
class App extends React.Component {
componentDidMount() {
let item = this.refs.myDropDownList.getItemByValue('US');
this.refs.myDropDownList.selectItem(item);
}
render() {
let source = [
{ value: 'AF', label: 'Afghanistan' },
{ value: 'AL', label: 'Albania' },
{ value: 'DZ', label: 'Algeria' },
{ value: 'AS', label: 'American Samoa' },
{ value: 'AD', label: 'Andorra' },
{ value: 'AO', label: 'Angola' },
{ value: 'AI', label: 'Anguilla' },
{ value: 'AQ', label: 'Antarctica' },
{ value: 'AG', label: 'Antigua and Barbuda' },
{ value: 'AR', label: 'Argentina' },
{ value: 'AM', label: 'Armenia' },
{ value: 'AW', label: 'Aruba' },
{ value: 'AU', label: 'Australia' },
{ value: 'AT', label: 'Austria' },
{ value: 'AZ', label: 'Azerbaijan' },
{ value: 'BS', label: 'Bahamas' },
{ value: 'BH', label: 'Bahrain' },
{ value: 'BD', label: 'Bangladesh' },
{ value: 'BB', label: 'Barbados' },
{ value: 'BY', label: 'Belarus' },
{ value: 'BE', label: 'Belgium' },
{ value: 'BZ', label: 'Belize' },
{ value: 'BJ', label: 'Benin' },
{ value: 'BM', label: 'Bermuda' },
{ value: 'BT', label: 'Bhutan' },
{ value: 'BO', label: 'Bolivia' },
{ value: 'BA', label: 'Bosnia and Herzegovina' },
{ value: 'BW', label: 'Botswana' },
{ value: 'BV', label: 'Bouvet Island' },
{ value: 'BR', label: 'Brazil' },
{ value: 'BN', label: 'Brunei' },
{ value: 'BG', label: 'Bulgaria' },
{ value: 'BF', label: 'Burkina Faso' },
{ value: 'BI', label: 'Burundi' },
{ value: 'KH', label: 'Cambodia' },
{ value: 'CM', label: 'Cameroon' },
{ value: 'CA', label: 'Canada' },
{ value: 'CV', label: 'Cape Verde' },
{ value: 'KY', label: 'Cayman Islands' },
{ value: 'CF', label: 'Central African Republic' },
{ value: 'TD', label: 'Chad' },
{ value: 'CL', label: 'Chile' },
{ value: 'CN', label: 'China' },
{ value: 'CX', label: 'Christmas Island' },
{ value: 'CC', label: 'Cocos (Keeling) Islands' },
{ value: 'CO', label: 'Columbia' },
{ value: 'KM', label: 'Comoros' },
{ value: 'CG', label: 'Congo' },
{ value: 'CK', label: 'Cook Islands' },
{ value: 'CR', label: 'Costa Rica' },
{ value: 'CI', label: 'Cote D`Ivorie' },
{ value: 'HR', label: 'Croatia (Hrvatska)' },
{ value: 'CU', label: 'Cuba' },
{ value: 'CY', label: 'Cyprus' },
{ value: 'CZ', label: 'Czech Republic' },
{ value: 'DK', label: 'Denmark' },
{ value: 'DJ', label: 'Djibouti' },
{ value: 'DM', label: 'Dominica' },
{ value: 'DO', label: 'Dominican Republic' },
{ value: 'TP', label: 'East Timor' },
{ value: 'EC', label: 'Ecuador' },
{ value: 'EG', label: 'Egypt' },
{ value: 'SV', label: 'El Salvador' },
{ value: 'GQ', label: 'Equatorial Guinea' },
{ value: 'ER', label: 'Eritrea' },
{ value: 'EE', label: 'Estonia' },
{ value: 'ET', label: 'Ethiopia' },
{ value: 'FO', label: 'Faroe Islands' },
{ value: 'FJ', label: 'Fiji' },
{ value: 'FI', label: 'Finland' },
{ value: 'FR', label: 'France' },
{ value: 'GF', label: 'French Guinea' },
{ value: 'PF', label: 'French Polynesia' },
{ value: 'GA', label: 'Gabon' },
{ value: 'GM', label: 'Gambia' },
{ value: 'GE', label: 'Georgia' },
{ value: 'DE', label: 'Germany' },
{ value: 'GH', label: 'Ghana' },
{ value: 'GI', label: 'Gibraltar' },
{ value: 'GR', label: 'Greece' },
{ value: 'GL', label: 'Greenland' },
{ value: 'GD', label: 'Grenada' },
{ value: 'GP', label: 'Guadeloupe' },
{ value: 'GU', label: 'Guam' },
{ value: 'GT', label: 'Guatemala' },
{ value: 'GN', label: 'Guinea' },
{ value: 'GW', label: 'Guinea-Bissau' },
{ value: 'GY', label: 'Guyana' },
{ value: 'HT', label: 'Haiti' },
{ value: 'HN', label: 'Honduras' },
{ value: 'HK', label: 'Hong Kong' },
{ value: 'HU', label: 'Hungary' },
{ value: 'IS', label: 'Iceland' },
{ value: 'IN', label: 'India' },
{ value: 'ID', label: 'Indonesia' },
{ value: 'IR', label: 'Iran' },
{ value: 'IQ', label: 'Iraq' },
{ value: 'IE', label: 'Ireland' },
{ value: 'IL', label: 'Israel' },
{ value: 'IT', label: 'Italy' },
{ value: 'JM', label: 'Jamaica' },
{ value: 'JP', label: 'Japan' },
{ value: 'JO', label: 'Jordan' },
{ value: 'KZ', label: 'Kazakhstan' },
{ value: 'KE', label: 'Kenya' },
{ value: 'KI', label: 'Kiribati' },
{ value: 'KW', label: 'Kuwait' },
{ value: 'KG', label: 'Kyrgyzstan' },
{ value: 'LA', label: 'Laos' },
{ value: 'LV', label: 'Latvia' },
{ value: 'LB', label: 'Lebanon' },
{ value: 'LS', label: 'Lesotho' },
{ value: 'LR', label: 'Liberia' },
{ value: 'LY', label: 'Libya' },
{ value: 'LI', label: 'Liechtenstein' },
{ value: 'LT', label: 'Lithuania' },
{ value: 'LU', label: 'Luxembourg' },
{ value: 'MO', label: 'Macau' },
{ value: 'MK', label: 'Macedonia' },
{ value: 'MG', label: 'Madagascar' },
{ value: 'MW', label: 'Malawi' },
{ value: 'MY', label: 'Malaysia' },
{ value: 'MV', label: 'Maldives' },
{ value: 'ML', label: 'Mali' },
{ value: 'MT', label: 'Malta' },
{ value: 'MH', label: 'Marshall Islands' },
{ value: 'MQ', label: 'Martinique' },
{ value: 'MR', label: 'Mauritania' },
{ value: 'MU', label: 'Mauritius' },
{ value: 'YT', label: 'Mayotte' },
{ value: 'MX', label: 'Mexico' },
{ value: 'FM', label: 'Micronesia' },
{ value: 'MD', label: 'Moldova' },
{ value: 'MC', label: 'Monaco' },
{ value: 'MN', label: 'Mongolia' },
{ value: 'MS', label: 'Montserrat' },
{ value: 'MA', label: 'Morocco' },
{ value: 'MZ', label: 'Mozambique' },
{ value: 'MM', label: 'Myanmar (Burma)' },
{ value: 'NA', label: 'Namibia' },
{ value: 'NR', label: 'Nauru' },
{ value: 'NP', label: 'Nepal' },
{ value: 'NL', label: 'Netherlands' },
{ value: 'AN', label: 'Netherlands Antilles' },
{ value: 'NC', label: 'New Caledonia' },
{ value: 'NZ', label: 'New Zealand' },
{ value: 'NI', label: 'Nicaragua' },
{ value: 'NE', label: 'Niger' },
{ value: 'NG', label: 'Nigeria' },
{ value: 'NU', label: 'Niue' },
{ value: 'NF', label: 'Norfolk Island' },
{ value: 'KP', label: 'North Korea' },
{ value: 'NO', label: 'Norway' },
{ value: 'OM', label: 'Oman' },
{ value: 'PK', label: 'Pakistan' },
{ value: 'PW', label: 'Palau' },
{ value: 'PA', label: 'Panama' },
{ value: 'PG', label: 'Papua New Guinea' },
{ value: 'PY', label: 'Paraguay' },
{ value: 'PE', label: 'Peru' },
{ value: 'PH', label: 'Philippines' },
{ value: 'PN', label: 'Pitcairn' },
{ value: 'PL', label: 'Poland' },
{ value: 'PT', label: 'Portugal' },
{ value: 'PR', label: 'Puerto Rico' },
{ value: 'QA', label: 'Qatar' },
{ value: 'RE', label: 'Reunion' },
{ value: 'RO', label: 'Romania' },
{ value: 'RU', label: 'Russia' },
{ value: 'RW', label: 'Rwanda' },
{ value: 'SH', label: 'Saint Helena' },
{ value: 'KN', label: 'Saint Kitts and Nevis' },
{ value: 'LC', label: 'Saint Lucia' },
{ value: 'SM', label: 'San Marino' },
{ value: 'SA', label: 'Saudi Arabia' },
{ value: 'SN', label: 'Senegal' },
{ value: 'SC', label: 'Seychelles' },
{ value: 'SL', label: 'Sierra Leone' },
{ value: 'SG', label: 'Singapore' },
{ value: 'SK', label: 'Slovak Republic' },
{ value: 'SI', label: 'Slovenia' },
{ value: 'SB', label: 'Solomon Islands' },
{ value: 'SO', label: 'Somalia' },
{ value: 'ZA', label: 'South Africa' },
{ value: 'GS', label: 'South Georgia' },
{ value: 'KR', label: 'South Korea' },
{ value: 'ES', label: 'Spain' },
{ value: 'LK', label: 'Sri Lanka' },
{ value: 'SD', label: 'Sudan' },
{ value: 'SR', label: 'Suriname' },
{ value: 'SZ', label: 'Swaziland' },
{ value: 'SE', label: 'Sweden' },
{ value: 'CH', label: 'Switzerland' },
{ value: 'SY', label: 'Syria' },
{ value: 'TW', label: 'Taiwan' },
{ value: 'TJ', label: 'Tajikistan' },
{ value: 'TZ', label: 'Tanzania' },
{ value: 'TH', label: 'Thailand' },
{ value: 'TG', label: 'Togo' },
{ value: 'TK', label: 'Tokelau' },
{ value: 'TO', label: 'Tonga' },
{ value: 'TT', label: 'Trinidad and Tobago' },
{ value: 'TN', label: 'Tunisia' },
{ value: 'TR', label: 'Turkey' },
{ value: 'TM', label: 'Turkmenistan' },
{ value: 'TC', label: 'Turks and Caicos Islands' },
{ value: 'TV', label: 'Tuvalu' },
{ value: 'UG', label: 'Uganda' },
{ value: 'UA', label: 'Ukraine' },
{ value: 'AE', label: 'United Arab Emirates' },
{ value: 'UK', label: 'United Kingdom' },
{ value: 'US', label: 'United States' },
{ value: 'UY', label: 'Uruguay' },
{ value: 'UZ', label: 'Uzbekistan' },
{ value: 'VU', label: 'Vanuatu' },
{ value: 'VA', label: 'Vatican City (Holy See)' },
{ value: 'VE', label: 'Venezuela' },
{ value: 'VN', label: 'Vietnam' },
{ value: 'VG', label: 'Virgin Islands (British)' },
{ value: 'VI', label: 'Virgin Islands (US)' },
{ value: 'WF', label: 'Wallis and Futuna Islands' },
{ value: 'EH', label: 'Western Sahara' },
{ value: 'WS', label: 'Western Samoa' },
{ value: 'YE', label: 'Yemen' },
{ value: 'YU', label: 'Yugoslavia' },
{ value: 'ZM', label: 'Zambia' },
{ value: 'ZW', label: 'Zimbabwe' }
];
return (
<JqxDropDownList ref='myDropDownList'
width={200} height={25} source={source} rtl={true}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/image/add-to-photos.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAddToPhotos = (props) => (
<SvgIcon {...props}>
<path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z"/>
</SvgIcon>
);
ImageAddToPhotos = pure(ImageAddToPhotos);
ImageAddToPhotos.displayName = 'ImageAddToPhotos';
export default ImageAddToPhotos;
|
examples/markdown.js | dundalek/react-blessed-contrib | // Adapted from https://github.com/yaronn/blessed-contrib/blob/master/examples/markdown.js
import React, { Component } from 'react';
import blessed from 'blessed';
import { render } from 'react-blessed';
import { Markdown } from '../src/index';
import chalk from 'chalk';
class App extends Component {
componentDidMount() {
this.refs.markdown.widget.setMarkdown('# Hello \n Testing `refs`.');
}
render() {
return (
<box>
<Markdown style={{firstHeading: chalk.red.italic}}>{'# Hello \n This is **markdown** printed in the `terminal` 11'}</Markdown>
<Markdown ref="markdown" top={3} style={{firstHeading: chalk.blue}} markdown={'# Hello \n This is **markdown** printed in the `terminal` 11'} />
</box>
);
}
}
const screen = blessed.screen();
render(<App />, screen);
|
app/javascript/mastodon/features/keyboard_shortcuts/index.js | lindwurm/mastodon | import React from 'react';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'keyboard_shortcuts.heading', defaultMessage: 'Keyboard Shortcuts' },
});
export default @injectIntl
class KeyboardShortcuts extends ImmutablePureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
render () {
const { intl, multiColumn } = this.props;
return (
<Column bindToDocument={!multiColumn} icon='question' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<div className='keyboard-shortcuts scrollable optionally-scrollable'>
<table>
<thead>
<tr>
<th><FormattedMessage id='keyboard_shortcuts.hotkey' defaultMessage='Hotkey' /></th>
<th><FormattedMessage id='keyboard_shortcuts.description' defaultMessage='Description' /></th>
</tr>
</thead>
<tbody>
<tr>
<td><kbd>r</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.reply' defaultMessage='to reply' /></td>
</tr>
<tr>
<td><kbd>m</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.mention' defaultMessage='to mention author' /></td>
</tr>
<tr>
<td><kbd>p</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.profile' defaultMessage="to open author's profile" /></td>
</tr>
<tr>
<td><kbd>f</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.favourite' defaultMessage='to favourite' /></td>
</tr>
<tr>
<td><kbd>b</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.boost' defaultMessage='to boost' /></td>
</tr>
<tr>
<td><kbd>enter</kbd>, <kbd>o</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.enter' defaultMessage='to open status' /></td>
</tr>
<tr>
<td><kbd>e</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.open_media' defaultMessage='to open media' /></td>
</tr>
<tr>
<td><kbd>x</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toggle_hidden' defaultMessage='to show/hide text behind CW' /></td>
</tr>
<tr>
<td><kbd>h</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toggle_sensitivity' defaultMessage='to show/hide media' /></td>
</tr>
<tr>
<td><kbd>up</kbd>, <kbd>k</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.up' defaultMessage='to move up in the list' /></td>
</tr>
<tr>
<td><kbd>down</kbd>, <kbd>j</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.down' defaultMessage='to move down in the list' /></td>
</tr>
<tr>
<td><kbd>1</kbd>-<kbd>9</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.column' defaultMessage='to focus a status in one of the columns' /></td>
</tr>
<tr>
<td><kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.compose' defaultMessage='to focus the compose textarea' /></td>
</tr>
<tr>
<td><kbd>alt</kbd>+<kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toot' defaultMessage='to start a brand new toot' /></td>
</tr>
<tr>
<td><kbd>alt</kbd>+<kbd>x</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.spoilers' defaultMessage='to show/hide CW field' /></td>
</tr>
<tr>
<td><kbd>backspace</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.back' defaultMessage='to navigate back' /></td>
</tr>
<tr>
<td><kbd>s</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.search' defaultMessage='to focus search' /></td>
</tr>
<tr>
<td><kbd>esc</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.unfocus' defaultMessage='to un-focus compose textarea/search' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>h</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.home' defaultMessage='to open home timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.notifications' defaultMessage='to open notifications column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>l</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.local' defaultMessage='to open local timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>t</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.federated' defaultMessage='to open federated timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>d</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.direct' defaultMessage='to open direct messages column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>s</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.start' defaultMessage='to open "get started" column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>f</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.favourites' defaultMessage='to open favourites list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>p</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.pinned' defaultMessage='to open pinned toots list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>u</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.my_profile' defaultMessage='to open your profile' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>b</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.blocked' defaultMessage='to open blocked users list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>m</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.muted' defaultMessage='to open muted users list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>r</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.requests' defaultMessage='to open follow requests list' /></td>
</tr>
<tr>
<td><kbd>?</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.legend' defaultMessage='to display this legend' /></td>
</tr>
</tbody>
</table>
</div>
</Column>
);
}
}
|
src/helpers/universalRouter.js | joelburget/pigment | import qs from 'query-string';
import React from 'react';
import {match, RoutingContext} from 'react-router';
import createRoutes from '../routes';
import { Provider } from 'react-redux';
const getFetchData = (component = {}) => {
return component.WrappedComponent ?
getFetchData(component.WrappedComponent) :
component.fetchData;
};
const fetchDataForContainers = (containers, store, params, query) => {
const promises = containers
.filter((component) => getFetchData(component)) // only look at ones with a static fetchData()
.map(getFetchData) // pull out fetch data methods
.map(fetchData => fetchData(store, params, query || {})); // call fetch data methods and save promises
return Promise.all(promises);
};
export default function universalRouter(location, history, store, preload) {
const routes = createRoutes(store);
return new Promise((resolve, reject) => {
match({routes, history, location}, (error, redirectLocation, renderProps) => {
if (error) {
return reject(error);
}
if (redirectLocation) {
return resolve({ redirectLocation });
}
const component = (
<Provider store={store} key='provider'>
<RoutingContext {...renderProps} />
</Provider>
);
if (preload) {
fetchDataForContainers(
renderProps.components,
store,
renderProps.params,
qs.parse(renderProps.location.search)
)
.then(
() => { resolve({ component }); },
err => reject(err)
);
} else {
resolve({ component });
}
});
});
}
|
src/components/Footer.js | laurentzziu/color-gems-react | import React from 'react';
const Footer = (props) => {
return (
<footer id="app-footer" className="text-center mb-3">
<small>Made with (love) by
<a href="https://floringorgan.com/">Florinel Gorgan</a>.
</small>
</footer>
)
}
export default Footer;
|
src/modules/widget/Table.js | lenxeon/react | 'use strict'
import React from 'react'
import classnames from 'classnames'
import { substitute } from './utils/strings'
import TableHeader from './TableHeader'
import { requireCss } from './themes'
requireCss('tables')
class Table extends React.Component {
static displayName = 'Table'
static propTypes = {
bordered: React.PropTypes.bool,
children: React.PropTypes.array,
className: React.PropTypes.string,
data: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.func
]).isRequired,
filters: React.PropTypes.array,
headers: React.PropTypes.array,
height: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
]),
onSort: React.PropTypes.func,
pagination: React.PropTypes.object,
selectAble: React.PropTypes.bool,
striped: React.PropTypes.bool,
style: React.PropTypes.object,
width: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
])
}
componentWillMount () {
this.fetchData(this.props.data)
}
componentDidMount () {
this.setHeaderWidth()
}
componentWillReceiveProps (nextProps) {
if (nextProps.data !== this.props.data) {
this.fetchData(nextProps.data)
}
/*
if (nextProps.children !== this.props.children) {
this.setHeaderProps(nextProps.children)
}
*/
}
componentDidUpdate () {
this.setHeaderWidth()
}
componentWillUnmount () {
this.unmounted = true
}
unmounted = false
state = {
index: this.props.pagination ? this.props.pagination.props.index : 1,
data: [],
sort: {},
total: null
}
setHeaderWidth () {
let body = React.findDOMNode(this.refs.body)
let tr = body.querySelector('tr')
if (!tr) {
return
}
let ths = React.findDOMNode(this.refs.header).querySelectorAll('th')
let tds = tr.querySelectorAll('td')
for (let i = 0, count = tds.length; i < count; i++) {
if (ths[i]) {
ths[i].style.width = tds[i].offsetWidth + 'px'
}
}
}
/*
setHeaderProps (children) {
let headers = []
if (children) {
if (children.constructor === Array) {
children.forEach(child => {
if (child.type === TableHeader) {
headers.push(child)
}
})
} else if (children.type === TableHeader) {
headers.push(children)
}
}
this.setState({headers})
}
*/
fetchData (data) {
if (typeof data === 'function') {
data.then(res => {
this.fetchData(res)
})()
} else {
if (!this.unmounted) {
this.setState({ data })
}
}
}
sortData (key, asc) {
let data = this.state.data
data = data.sort(function(a, b) {
var x = a[key]
var y = b[key]
if (asc) {
return ((x < y) ? -1 : ((x > y) ? 1 : 0))
} else {
return ((x > y) ? -1 : ((x < y) ? 1 : 0))
}
})
this.setState({ data })
}
onCheck (i, e) {
let checked = typeof e === 'boolean' ? e : e.target.checked,
data = this.state.data,
index = this.state.index,
size = this.props.pagination ? this.props.pagination.props.size : data.length,
start = 0,
end = 0
if (i === 'all') {
start = (index - 1) * size
end = index * size
} else {
start = (index - 1) * size + i
end = start + 1
}
for (; start < end; start++) {
data[start].$checked = checked
}
this.setState({data})
}
getChecked (name) {
let values = []
this.state.data.forEach(d => {
if (d.$checked) {
values.push(name ? d[name] : d)
}
})
return values
}
onBodyScroll (e) {
let hc = React.findDOMNode(this.refs.headerContainer)
hc.style.marginLeft = (0 - e.target.scrollLeft) + 'px'
}
getData () {
let page = this.props.pagination,
filters = this.props.filters,
data = []
if (filters) {
let filterCount = filters.length
this.state.data.forEach(d => {
let checked = true
for (let i = 0; i < filterCount; i++) {
let f = filters[i].func
checked = f(d)
if (!checked) {
break
}
}
if (checked) {
data.push(d)
}
})
} else {
data = this.state.data
}
let total = data.length
if (!page) {
return { total, data }
}
let size = page.props.size
if (data.length <= size) {
return { total, data }
}
let index = this.state.index
data = data.slice((index - 1) * size, index * size)
return { total, data }
}
renderBody (data) {
let selectAble = this.props.selectAble
let trs = data.map((d, i) => {
let tds = []
if (selectAble) {
tds.push(
<td style={{width: 13}} key="checkbox">
<input checked={d.$checked} onChange={this.onCheck.bind(this, i)} type="checkbox" />
</td>
)
}
this.props.headers.map((h, j) => {
if (h.hidden) {
return
}
let content = h.content,
tdStyle = {}
if (typeof content === 'string') {
content = substitute(content, d)
} else if (typeof content === 'function') {
content = content(d)
} else {
content = d[h.name]
}
if (h.width) {
tdStyle.width = h.width
}
tds.push(<td style={tdStyle} key={j}>{content}</td>)
})
return <tr key={i}>{tds}</tr>
})
return <tbody>{trs}</tbody>
}
renderHeader () {
let headers = []
if (this.props.selectAble) {
headers.push(
<TableHeader key="checkbox" name="$checkbox" header={
<input onClick={this.onCheck.bind(this, 'all')} type="checkbox" />
} />
)
}
this.props.headers.map((header, i) => {
if (header.hidden) {
return
}
let props = {
key: i,
onSort: (name, asc) => {
this.setState({sort: { name, asc }})
if (this.props.onSort) {
this.props.onSort(name, asc)
} else {
this.sortData(name, asc)
}
},
sort: this.state.sort
}
headers.push(
<TableHeader {...header} {...props} />
)
})
return <tr>{headers}</tr>
}
renderPagination (total) {
if (!this.props.pagination) {
return null
}
let props = {
total: total,
onChange: (index) => {
let data = this.state.data
data.forEach(d => {
d.$checked = false
})
this.setState({index, data})
}
}
return React.cloneElement(this.props.pagination, props)
}
render () {
let bodyStyle = {},
headerStyle = {},
tableStyle = {},
onBodyScroll = null,
{ total, data } = this.getData()
if (this.props.height) {
bodyStyle.height = this.props.height
bodyStyle.overflow = 'auto'
}
if (this.props.width) {
headerStyle.width = this.props.width
if (typeof headerStyle.width === 'number') {
headerStyle.width += 20
}
tableStyle.width = this.props.width
bodyStyle.overflow = 'auto'
onBodyScroll = this.onBodyScroll.bind(this)
}
let className = classnames(
this.props.className,
'rct-table',
{
'rct-bordered': this.props.bordered,
'rct-scrolled': this.props.height,
'rct-striped': this.props.striped
}
)
return (
<div style={this.props.style} className={className}>
<div className="header-container">
<div ref="headerContainer" style={headerStyle}>
<table ref="header">
<thead>{this.renderHeader()}</thead>
</table>
</div>
</div>
<div onScroll={onBodyScroll} style={bodyStyle} className="body-container">
<table style={tableStyle} className="rct-table-body" ref="body">
{this.renderBody(data)}
</table>
</div>
{this.renderPagination(total)}
</div>
)
}
}
export default Table
|
src/docs/components/quote/QuoteExamplesDoc.js | grommet/grommet-docs | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Quote from 'grommet/components/Quote';
import Paragraph from 'grommet/components/Paragraph';
import InteractiveExample from '../../../components/InteractiveExample';
Quote.displayName = 'Quote';
Paragraph.displayName = 'Paragraph';
const PROPS_SCHEMA = {
credit: { value: 'Ricky Baker', initial: true },
emphasizeCredit: { value: true, initial: true },
size: { options: ['small', 'medium', 'large', 'full'] },
borderColorIndex: { options: ['brand', 'accent-1', 'accent-2'] }
};
const CONTENTS_SCHEMA = {
line1: { value: <Paragraph>Trees. Birds. Rivers. Sky.</Paragraph>,
initial: true },
line2: { value: <Paragraph>Running with my Uncle Hec</Paragraph>,
initial: true },
line3: { value: <Paragraph>Living forever.</Paragraph>, initial: true }
};
export default class QuoteExamplesDoc extends Component {
constructor () {
super();
this.state = { contents: {}, elementProps: {} };
}
render () {
const { contents, elementProps } = this.state;
const element = (
<Quote {...elementProps}>
{contents.line1}
{contents.line2}
{contents.line3}
</Quote>
);
return (
<InteractiveExample contextLabel='Quote' contextPath='/docs/quote'
preamble={`import Quote from 'grommet/components/Quote';`}
propsSchema={PROPS_SCHEMA}
contentsSchema={CONTENTS_SCHEMA}
element={element}
onChange={(elementProps, contents) => {
this.setState({ elementProps, contents });
}} />
);
}
};
// const SINGLE = <Paragraph>{TEXT}</Paragraph>;
// const STRONG = <Paragraph><strong>{TEXT}</strong></Paragraph>;
// const MULTIPLE = [
// <Paragraph key={1}>Trees. Birds. Rivers. Sky.</Paragraph>,
// <Paragraph key={2}>Running with my Uncle Hec</Paragraph>,
// <Paragraph key={3}>Living forever.</Paragraph>
// ];
//
// const QuoteExample = (props) => (
// <Example align="start" code={
// <Quote {...props} />
// } />
// );
//
// export default class QuoteExamplesDoc extends ExamplesDoc {};
//
// QuoteExamplesDoc.defaultProps = {
// context: <Anchor path="/docs/quote">Quote</Anchor>,
// examples: [
// { label: 'Default', component: QuoteExample,
// props: { children: SINGLE, credit: 'Ricky Baker' }},
// { label: 'Small quote, emphasis reversed', component: QuoteExample,
// props: { children: STRONG, credit: 'Ricky Baker',
// borderColorIndex: 'accent-1', size: 'small',
// emphasizeCredit: false }},
// { label: 'Medium quote, multiple paragraphs', component: QuoteExample,
// props: { children: MULTIPLE, credit: 'Ricky Baker',
// borderColorIndex: 'accent-2', size: 'medium' }}
// ],
// title: 'Examples'
// };
|
lib/App.js | chelletuerk/react_number_guesser | import React from 'react'
import Controls from './Controls'
import UserRangeInputs from './UserRangeInputs'
require('./styles.scss')
class App extends React.Component {
constructor() {
super()
this.state = {
guess: '',
showGuess: null,
hint: null,
min: 1,
max: 100,
generatedNum: null,
resetEnabled: false,
showMinRange: null,
showMaxRange: null,
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.handleClear = this.handleClear.bind(this)
this.handleReset = this.handleReset.bind(this)
this.handleMinRange = this.handleMinRange.bind(this)
this.handleMaxRange = this.handleMaxRange.bind(this)
this.handleRangeSubmit = this.handleRangeSubmit.bind(this)
}
componentDidMount() {
let { min, max } = this.state
this.setState({
generatedNum: this.randomNum(),
showMinRange: min,
showMaxRange: max,
})
}
randomNum() {
return Math.floor(Math.random() * (this.state.max - this.state.min + 1)) + this.state.min
}
handleChange(e) {
let guess = e.target.value
this.setState({guess: guess})
}
outsideRange() {
let { guess } = this.state
if (+guess > this.state.max || +guess < this.state.min) {
alert('Sorry, you are outside the range')
guess = ''
}
}
notNumber() {
if (!parseFloat(this.state.guess)) {
alert('Sorry, that is not a number')
return this.state.guess = ''
}
}
handleSubmit() {
this.outsideRange()
this.notNumber()
const { guess, min, max } = this.state
this.setState({
showGuess: guess,
guess: '',
hint: this.highOrLow(),
resetEnabled: true
}, () => {
if (this.state.hint === 'Winner winner, chicken dinner!') {
this.setState({
min: min - 10,
max: max + 10,
}, () => {
this.setState({
generatedNum: this.randomNum(),
}, () => {
this.setState({
showMinRange: this.state.min,
showMaxRange: this.state.max,
})
})
})
}
})
}
handleClear() {
this.setState({ guess: '' })
}
handleReset() {
this.setState({
showGuess: '',
guess: '',
hint: '',
min: 1,
max: 100,
resetEnabled: false,
showMinRange: 1,
showMaxRange: 100,
}, () => {
this.setState({generatedNum: this.randomNum()})
})
}
handleMinRange(e) {
let minRange = e.target.value
this.setState({min: minRange})
}
handleMaxRange(e) {
let maxRange = e.target.value
this.setState({max: maxRange})
}
handleRangeSubmit(minMax) {
let { min, max } = minMax
this.setState({
showMinRange: min,
showMaxRange: max,
resetEnabled: true,
min: +min,
max: +max,
}, () => {
this.setState({ generatedNum: this.randomNum() })
})
}
renderGuess() {
return this.state.showGuess
}
renderMinRange() {
return this.state.showMinRange
}
renderMaxRange() {
return this.state.showMaxRange
}
renderHint() {
return this.state.hint
}
buttonDisabled() {
return !this.state.guess
}
resetDisabled() {
return !this.state.resetEnabled
}
highOrLow() {
let { guess, generatedNum } = this.state
if (guess > generatedNum) {
return 'Sorry, that guess is too high. Try a lower number.'
} else if ( guess < generatedNum) {
return 'Sorry, that guess is too low. Try a higher number'
} else {
return 'Winner winner, chicken dinner!'
}
}
render() {
return (
<div>
<h1>Number Guesser in React</h1>
<h2>Your last guess was...</h2>
<ul className='rendered-guess'>
<li className='shown-guess'>{this.renderGuess()}</li>
<li>{this.renderHint()}</li>
</ul>
<Controls
buttonDisabled={this.buttonDisabled()}
resetDisabled={this.resetDisabled()}
highOrLow={this.highOrLow()}
guess={this.state.guess}
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
handleClear={this.handleClear}
handleReset={this.handleReset}/>
<UserRangeInputs
handleMinRange={this.handleMinRange}
handleMaxRange={this.handleMaxRange}
handleRangeSubmit={this.handleRangeSubmit}/>
<li className='range'>
<span className='min'>Min: {this.renderMinRange()}</span>
<span>Max: {this.renderMaxRange()}</span>
</li>
</div>
)
}
}
module.exports = App
|
examples/05 Customize/Drop Effects/index.js | jowcy/react-dnd | import React from 'react';
import Container from './Container';
export default class CustomizeDropEffects {
render() {
return (
<div>
<p>
<b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/05%20Customize/Drop%20Effects'>Browse the Source</a></b>
</p>
<p>
Some browsers let you specify the “drop effects” for the draggable items.
In the compatible browsers, you will see a “copy” icon when you drag the first box over the drop zone.
</p>
<Container />
</div>
);
}
}
|
src/index.js | wwayne/react-tooltip | /* eslint-disable no-unused-vars, dot-notation */
import React from 'react';
import PropTypes from 'prop-types';
/* Decorators */
import staticMethods from './decorators/staticMethods';
import windowListener from './decorators/windowListener';
import customEvent from './decorators/customEvent';
import isCapture from './decorators/isCapture';
import getEffect from './decorators/getEffect';
import bodyMode from './decorators/bodyMode';
import trackRemoval from './decorators/trackRemoval';
/* Utils */
import getPosition from './utils/getPosition';
import getTipContent from './utils/getTipContent';
import { parseAria } from './utils/aria';
import nodeListToArray from './utils/nodeListToArray';
import { generateUUID } from './utils/uuid';
/* CSS */
import baseCss from './index.scss';
import { generateTooltipStyle } from './decorators/styler';
/* Polyfill */
import 'core-js/modules/es.array.find';
@staticMethods
@windowListener
@customEvent
@isCapture
@getEffect
@bodyMode
@trackRemoval
class ReactTooltip extends React.ReactNode {
static get propTypes() {
return {
uuid: PropTypes.string,
children: PropTypes.any,
place: PropTypes.string,
type: PropTypes.string,
effect: PropTypes.string,
offset: PropTypes.object,
padding: PropTypes.string,
multiline: PropTypes.bool,
border: PropTypes.bool,
textColor: PropTypes.string,
backgroundColor: PropTypes.string,
borderColor: PropTypes.string,
arrowColor: PropTypes.string,
insecure: PropTypes.bool,
class: PropTypes.string,
className: PropTypes.string,
id: PropTypes.string,
html: PropTypes.bool,
delayHide: PropTypes.number,
delayUpdate: PropTypes.number,
delayShow: PropTypes.number,
event: PropTypes.string,
eventOff: PropTypes.string,
isCapture: PropTypes.bool,
globalEventOff: PropTypes.string,
getContent: PropTypes.any,
afterShow: PropTypes.func,
afterHide: PropTypes.func,
overridePosition: PropTypes.func,
disable: PropTypes.bool,
scrollHide: PropTypes.bool,
resizeHide: PropTypes.bool,
wrapper: PropTypes.string,
bodyMode: PropTypes.bool,
possibleCustomEvents: PropTypes.string,
possibleCustomEventsOff: PropTypes.string,
clickable: PropTypes.bool
};
}
static defaultProps = {
insecure: true,
resizeHide: true,
wrapper: 'div',
clickable: false
};
static supportedWrappers = ['div', 'span'];
static displayName = 'ReactTooltip';
constructor(props) {
super(props);
this.state = {
uuid: props.uuid || generateUUID(),
place: props.place || 'top', // Direction of tooltip
desiredPlace: props.place || 'top',
type: props.type || 'dark', // Color theme of tooltip
effect: props.effect || 'float', // float or fixed
show: false,
border: false,
customColors: {},
offset: {},
padding: props.padding,
extraClass: '',
html: false,
delayHide: 0,
delayShow: 0,
event: props.event || null,
eventOff: props.eventOff || null,
currentEvent: null, // Current mouse event
currentTarget: null, // Current target of mouse event
ariaProps: parseAria(props), // aria- and role attributes
isEmptyTip: false,
disable: false,
possibleCustomEvents: props.possibleCustomEvents || '',
possibleCustomEventsOff: props.possibleCustomEventsOff || '',
originTooltip: null,
isMultiline: false
};
this.bind([
'showTooltip',
'updateTooltip',
'hideTooltip',
'hideTooltipOnScroll',
'getTooltipContent',
'globalRebuild',
'globalShow',
'globalHide',
'onWindowResize',
'mouseOnToolTip'
]);
this.mount = true;
this.delayShowLoop = null;
this.delayHideLoop = null;
this.delayReshow = null;
this.intervalUpdateContent = null;
}
/**
* For unify the bind and unbind listener
*/
bind(methodArray) {
methodArray.forEach(method => {
this[method] = this[method].bind(this);
});
}
componentDidMount() {
const { insecure, resizeHide } = this.props;
this.mount = true;
this.bindListener(); // Bind listener for tooltip
this.bindWindowEvents(resizeHide); // Bind global event for static method
this.injectStyles(); // Inject styles for each DOM root having tooltip.
}
static getDerivedStateFromProps(nextProps, prevState) {
const { ariaProps } = prevState;
const newAriaProps = parseAria(nextProps);
const isChanged = Object.keys(newAriaProps).some(props => {
return newAriaProps[props] !== ariaProps[props];
});
if (!isChanged) {
return null;
}
return {
...prevState,
ariaProps: newAriaProps
};
}
componentWillUnmount() {
this.mount = false;
this.clearTimer();
this.unbindListener();
this.removeScrollListener(this.state.currentTarget);
this.unbindWindowEvents();
}
/* Look for the closest DOM root having tooltip and inject styles. */
injectStyles() {
const { tooltipRef } = this;
if (!tooltipRef) {
return;
}
let parentNode = tooltipRef.parentNode;
while (parentNode.parentNode) {
parentNode = parentNode.parentNode;
}
let domRoot;
switch (parentNode.constructor.name) {
case 'Document':
case 'HTMLDocument':
case undefined:
domRoot = parentNode.head;
break;
case 'ShadowRoot':
default:
domRoot = parentNode;
break;
}
// Prevent styles duplication.
if (!domRoot.querySelector('style[data-react-tooltip]')) {
const style = document.createElement('style');
style.textContent = baseCss;
style.setAttribute('data-react-tooltip', 'true');
domRoot.appendChild(style);
}
}
/**
* Return if the mouse is on the tooltip.
* @returns {boolean} true - mouse is on the tooltip
*/
mouseOnToolTip() {
const { show } = this.state;
if (show && this.tooltipRef) {
/* old IE or Firefox work around */
if (!this.tooltipRef.matches) {
/* old IE work around */
if (this.tooltipRef.msMatchesSelector) {
this.tooltipRef.matches = this.tooltipRef.msMatchesSelector;
} else {
/* old Firefox work around */
this.tooltipRef.matches = this.tooltipRef.mozMatchesSelector;
}
}
return this.tooltipRef.matches(':hover');
}
return false;
}
/**
* Pick out corresponded target elements
*/
getTargetArray(id) {
let targetArray = [];
let selector;
if (!id) {
selector = '[data-tip]:not([data-for])';
} else {
const escaped = id.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
selector = `[data-tip][data-for="${escaped}"]`;
}
// Scan document for shadow DOM elements
nodeListToArray(document.getElementsByTagName('*'))
.filter(element => element.shadowRoot)
.forEach(element => {
targetArray = targetArray.concat(
nodeListToArray(element.shadowRoot.querySelectorAll(selector))
);
});
return targetArray.concat(
nodeListToArray(document.querySelectorAll(selector))
);
}
/**
* Bind listener to the target elements
* These listeners used to trigger showing or hiding the tooltip
*/
bindListener() {
const { id, globalEventOff, isCapture } = this.props;
const targetArray = this.getTargetArray(id);
targetArray.forEach(target => {
if (target.getAttribute('currentItem') === null) {
target.setAttribute('currentItem', 'false');
}
this.unbindBasicListener(target);
if (this.isCustomEvent(target)) {
this.customUnbindListener(target);
}
});
if (this.isBodyMode()) {
this.bindBodyListener(targetArray);
} else {
targetArray.forEach(target => {
const isCaptureMode = this.isCapture(target);
const effect = this.getEffect(target);
if (this.isCustomEvent(target)) {
this.customBindListener(target);
return;
}
target.addEventListener('mouseenter', this.showTooltip, isCaptureMode);
target.addEventListener('focus', this.showTooltip, isCaptureMode);
if (effect === 'float') {
target.addEventListener(
'mousemove',
this.updateTooltip,
isCaptureMode
);
}
target.addEventListener('mouseleave', this.hideTooltip, isCaptureMode);
target.addEventListener('blur', this.hideTooltip, isCaptureMode);
});
}
// Global event to hide tooltip
if (globalEventOff) {
window.removeEventListener(globalEventOff, this.hideTooltip);
window.addEventListener(globalEventOff, this.hideTooltip, isCapture);
}
// Track removal of targetArray elements from DOM
this.bindRemovalTracker();
}
/**
* Unbind listeners on target elements
*/
unbindListener() {
const { id, globalEventOff } = this.props;
if (this.isBodyMode()) {
this.unbindBodyListener();
} else {
const targetArray = this.getTargetArray(id);
targetArray.forEach(target => {
this.unbindBasicListener(target);
if (this.isCustomEvent(target)) this.customUnbindListener(target);
});
}
if (globalEventOff)
window.removeEventListener(globalEventOff, this.hideTooltip);
this.unbindRemovalTracker();
}
/**
* Invoke this before bind listener and unmount the component
* it is necessary to invoke this even when binding custom event
* so that the tooltip can switch between custom and default listener
*/
unbindBasicListener(target) {
const isCaptureMode = this.isCapture(target);
target.removeEventListener('mouseenter', this.showTooltip, isCaptureMode);
target.removeEventListener('mousemove', this.updateTooltip, isCaptureMode);
target.removeEventListener('mouseleave', this.hideTooltip, isCaptureMode);
}
getTooltipContent() {
const { getContent, children } = this.props;
// Generate tooltip content
let content;
if (getContent) {
if (Array.isArray(getContent)) {
content = getContent[0] && getContent[0](this.state.originTooltip);
} else {
content = getContent(this.state.originTooltip);
}
}
return getTipContent(
this.state.originTooltip,
children,
content,
this.state.isMultiline
);
}
isEmptyTip(placeholder) {
return (
(typeof placeholder === 'string' && placeholder === '') ||
placeholder === null
);
}
/**
* When mouse enter, show the tooltip
*/
showTooltip(e, isGlobalCall) {
if (!this.tooltipRef) {
return;
}
if (isGlobalCall) {
// Don't trigger other elements belongs to other ReactTooltip
const targetArray = this.getTargetArray(this.props.id);
const isMyElement = targetArray.some(ele => ele === e.currentTarget);
if (!isMyElement) return;
}
// Get the tooltip content
// calculate in this phrase so that tip width height can be detected
const { multiline, getContent } = this.props;
const originTooltip = e.currentTarget.getAttribute('data-tip');
const isMultiline =
e.currentTarget.getAttribute('data-multiline') || multiline || false;
// If it is focus event or called by ReactTooltip.show, switch to `solid` effect
const switchToSolid = e instanceof window.FocusEvent || isGlobalCall;
// if it needs to skip adding hide listener to scroll
let scrollHide = true;
if (e.currentTarget.getAttribute('data-scroll-hide')) {
scrollHide = e.currentTarget.getAttribute('data-scroll-hide') === 'true';
} else if (this.props.scrollHide != null) {
scrollHide = this.props.scrollHide;
}
// adding aria-describedby to target to make tooltips read by screen readers
if (e && e.currentTarget && e.currentTarget.setAttribute) {
e.currentTarget.setAttribute(
'aria-describedby',
this.props.id || this.state.uuid
);
}
// Make sure the correct place is set
const desiredPlace =
e.currentTarget.getAttribute('data-place') || this.props.place || 'top';
const effect =
(switchToSolid && 'solid') || this.getEffect(e.currentTarget);
const offset =
e.currentTarget.getAttribute('data-offset') || this.props.offset || {};
const result = getPosition(
e,
e.currentTarget,
this.tooltipRef,
desiredPlace.split(',')[0],
desiredPlace,
effect,
offset
);
if (result.position && this.props.overridePosition) {
result.position = this.props.overridePosition(
result.position,
e,
e.currentTarget,
this.tooltipRef,
desiredPlace,
desiredPlace,
effect,
offset
);
}
const place = result.isNewState
? result.newState.place
: desiredPlace.split(',')[0];
// To prevent previously created timers from triggering
this.clearTimer();
const target = e.currentTarget;
const reshowDelay = this.state.show
? target.getAttribute('data-delay-update') || this.props.delayUpdate
: 0;
const self = this;
const updateState = function updateState() {
self.setState(
{
originTooltip: originTooltip,
isMultiline: isMultiline,
desiredPlace: desiredPlace,
place: place,
type: target.getAttribute('data-type') || self.props.type || 'dark',
customColors: {
text:
target.getAttribute('data-text-color') ||
self.props.textColor ||
null,
background:
target.getAttribute('data-background-color') ||
self.props.backgroundColor ||
null,
border:
target.getAttribute('data-border-color') ||
self.props.borderColor ||
null,
arrow:
target.getAttribute('data-arrow-color') ||
self.props.arrowColor ||
null
},
effect: effect,
offset: offset,
padding: target.getAttribute('data-padding') || self.props.padding,
html:
(target.getAttribute('data-html')
? target.getAttribute('data-html') === 'true'
: self.props.html) || false,
delayShow:
target.getAttribute('data-delay-show') || self.props.delayShow || 0,
delayHide:
target.getAttribute('data-delay-hide') || self.props.delayHide || 0,
delayUpdate:
target.getAttribute('data-delay-update') ||
self.props.delayUpdate ||
0,
border:
(target.getAttribute('data-border')
? target.getAttribute('data-border') === 'true'
: self.props.border) || false,
extraClass:
target.getAttribute('data-class') ||
self.props.class ||
self.props.className ||
'',
disable:
(target.getAttribute('data-tip-disable')
? target.getAttribute('data-tip-disable') === 'true'
: self.props.disable) || false,
currentTarget: target
},
() => {
if (scrollHide) {
self.addScrollListener(self.state.currentTarget);
}
self.updateTooltip(e);
if (getContent && Array.isArray(getContent)) {
self.intervalUpdateContent = setInterval(() => {
if (self.mount) {
const { getContent } = self.props;
const placeholder = getTipContent(
originTooltip,
'',
getContent[0](),
isMultiline
);
const isEmptyTip = self.isEmptyTip(placeholder);
self.setState({ isEmptyTip });
self.updatePosition();
}
}, getContent[1]);
}
}
);
};
// If there is no delay call immediately, don't allow events to get in first.
if (reshowDelay) {
this.delayReshow = setTimeout(updateState, reshowDelay);
} else {
updateState();
}
}
/**
* When mouse hover, update tool tip
*/
updateTooltip(e) {
const { delayShow, disable } = this.state;
const { afterShow, disable: disableProp } = this.props;
const placeholder = this.getTooltipContent();
const eventTarget = e.currentTarget || e.target;
// Check if the mouse is actually over the tooltip, if so don't hide the tooltip
if (this.mouseOnToolTip()) {
return;
}
// if the tooltip is empty, disable the tooltip
if (this.isEmptyTip(placeholder) || disable || disableProp) {
return;
}
const delayTime = !this.state.show ? parseInt(delayShow, 10) : 0;
const updateState = () => {
if (
(Array.isArray(placeholder) && placeholder.length > 0) ||
placeholder
) {
const isInvisible = !this.state.show;
this.setState(
{
currentEvent: e,
currentTarget: eventTarget,
show: true
},
() => {
this.updatePosition(() => {
if (isInvisible && afterShow) {
afterShow(e);
}
});
}
);
}
};
if (this.delayShowLoop) {
clearTimeout(this.delayShowLoop);
}
if (delayTime) {
this.delayShowLoop = setTimeout(updateState, delayTime);
} else {
this.delayShowLoop = null;
updateState();
}
}
/*
* If we're mousing over the tooltip remove it when we leave.
*/
listenForTooltipExit() {
const { show } = this.state;
if (show && this.tooltipRef) {
this.tooltipRef.addEventListener('mouseleave', this.hideTooltip);
}
}
removeListenerForTooltipExit() {
const { show } = this.state;
if (show && this.tooltipRef) {
this.tooltipRef.removeEventListener('mouseleave', this.hideTooltip);
}
}
/**
* When mouse leave, hide tooltip
*/
hideTooltip(e, hasTarget, options = { isScroll: false }) {
const { disable } = this.state;
const { isScroll } = options;
const delayHide = isScroll ? 0 : this.state.delayHide;
const { afterHide, disable: disableProp } = this.props;
const placeholder = this.getTooltipContent();
if (!this.mount) return;
if (this.isEmptyTip(placeholder) || disable || disableProp) return; // if the tooltip is empty, disable the tooltip
if (hasTarget) {
// Don't trigger other elements belongs to other ReactTooltip
const targetArray = this.getTargetArray(this.props.id);
const isMyElement = targetArray.some(ele => ele === e.currentTarget);
if (!isMyElement || !this.state.show) return;
}
// clean up aria-describedby when hiding tooltip
if (e && e.currentTarget && e.currentTarget.removeAttribute) {
e.currentTarget.removeAttribute('aria-describedby');
}
const resetState = () => {
const isVisible = this.state.show;
// Check if the mouse is actually over the tooltip, if so don't hide the tooltip
if (this.mouseOnToolTip()) {
this.listenForTooltipExit();
return;
}
this.removeListenerForTooltipExit();
this.setState({ show: false }, () => {
this.removeScrollListener(this.state.currentTarget);
if (isVisible && afterHide) {
afterHide(e);
}
});
};
this.clearTimer();
if (delayHide) {
this.delayHideLoop = setTimeout(resetState, parseInt(delayHide, 10));
} else {
resetState();
}
}
/**
* When scroll, hide tooltip
*/
hideTooltipOnScroll(event, hasTarget) {
this.hideTooltip(event, hasTarget, { isScroll: true });
}
/**
* Add scroll event listener when tooltip show
* automatically hide the tooltip when scrolling
*/
addScrollListener(currentTarget) {
const isCaptureMode = this.isCapture(currentTarget);
window.addEventListener('scroll', this.hideTooltipOnScroll, isCaptureMode);
}
removeScrollListener(currentTarget) {
const isCaptureMode = this.isCapture(currentTarget);
window.removeEventListener(
'scroll',
this.hideTooltipOnScroll,
isCaptureMode
);
}
// Calculation the position
updatePosition(callbackAfter) {
const {
currentEvent,
currentTarget,
place,
desiredPlace,
effect,
offset
} = this.state;
const node = this.tooltipRef;
const result = getPosition(
currentEvent,
currentTarget,
node,
place,
desiredPlace,
effect,
offset
);
if (result.position && this.props.overridePosition) {
result.position = this.props.overridePosition(
result.position,
currentEvent,
currentTarget,
node,
place,
desiredPlace,
effect,
offset
);
}
if (result.isNewState) {
// Switch to reverse placement
return this.setState(result.newState, () => {
this.updatePosition(callbackAfter);
});
}
callbackAfter();
// Set tooltip position
node.style.left = result.position.left + 'px';
node.style.top = result.position.top + 'px';
}
/**
* CLear all kinds of timeout of interval
*/
clearTimer() {
if (this.delayShowLoop) {
clearTimeout(this.delayShowLoop);
this.delayShowLoop = null;
}
if (this.delayHideLoop) {
clearTimeout(this.delayHideLoop);
this.delayHideLoop = null;
}
if (this.delayReshow) {
clearTimeout(this.delayReshow);
this.delayReshow = null;
}
if (this.intervalUpdateContent) {
clearInterval(this.intervalUpdateContent);
this.intervalUpdateContent = null;
}
}
hasCustomColors() {
return Boolean(
Object.keys(this.state.customColors).find(
color => color !== 'border' && this.state.customColors[color]
) ||
(this.state.border && this.state.customColors['border'])
);
}
render() {
const { extraClass, html, ariaProps, disable, uuid } = this.state;
const content = this.getTooltipContent();
const isEmptyTip = this.isEmptyTip(content);
const style = generateTooltipStyle(
this.state.uuid,
this.state.customColors,
this.state.type,
this.state.border,
this.state.padding
);
const tooltipClass =
'__react_component_tooltip' +
` ${this.state.uuid}` +
(this.state.show && !disable && !isEmptyTip ? ' show' : '') +
(this.state.border ? ' border' : '') +
` place-${this.state.place}` + // top, bottom, left, right
` type-${this.hasCustomColors() ? 'custom' : this.state.type}` + // dark, success, warning, error, info, light, custom
(this.props.delayUpdate ? ' allow_hover' : '') +
(this.props.clickable ? ' allow_click' : '');
let Wrapper = this.props.wrapper;
if (ReactTooltip.supportedWrappers.indexOf(Wrapper) < 0) {
Wrapper = ReactTooltip.defaultProps.wrapper;
}
const wrapperClassName = [tooltipClass, extraClass]
.filter(Boolean)
.join(' ');
if (html) {
const htmlContent = `${content}\n<style aria-hidden="true">${style}</style>`;
return (
<Wrapper
className={`${wrapperClassName}`}
id={this.props.id || uuid}
ref={ref => (this.tooltipRef = ref)}
{...ariaProps}
data-id="tooltip"
dangerouslySetInnerHTML={{ __html: htmlContent }}
/>
);
} else {
return (
<Wrapper
className={`${wrapperClassName}`}
id={this.props.id || uuid}
{...ariaProps}
ref={ref => (this.tooltipRef = ref)}
data-id="tooltip"
>
<style
dangerouslySetInnerHTML={{ __html: style }}
aria-hidden="true"
/>
{content}
</Wrapper>
);
}
}
}
export default ReactTooltip;
|
scripts/components/UserList.react.js | ViniciusAtaide/chatflux | import React from 'react';
import ChatActions from '../Actions/UserActions';
export default class UserList extends React.Component {
_login() {
let login = this.refs.login.getDOMNode();
ChatActions.loginAction(login.value);
login.value = "";
}
_subscribe() {
let login = this.refs.login.getDOMNode();
ChatActions.createUser(login.value);
login.value = "";
}
render() {
let style = {
ul: {
margin: 0,
padding: 5
},
li: {
margin: '0 10px',
listStyleType: 'none',
display: 'inline-block'
}
};
let users = this.props.users.map((user) => {
return <li style={style.li} key={user._id}>{user.name}</li>
});
return (
<div>
<form onSubmit={this._login.bind(this)}>
<input type="text" ref="login" />
<input type="submit" value="Login"/>
<button onClick={this._subscribe.bind(this)}>Cadastro</button>
</form>
<ul style={style.ul}>
{users}
</ul>
</div>
);
}
} |
src/App.js | aerobatic/kexp-spotify-player | import React, { Component } from 'react';
import Player from './components/Player';
import WelcomeSplash from './components/WelcomeSplash';
import * as spotifyAuth from './lib/spotifyAuth';
import glamorous from 'glamorous'
import './App.css';
const AppShell = glamorous.section({
width: 700,
maxWidth: '100%',
margin: '0 auto',
marginBottom: 15
});
class App extends Component {
render() {
let Child;
if (spotifyAuth.validAccessToken() !== true) {
Child = <WelcomeSplash />;
} else {
Child = <Player />;
}
return (
<AppShell>{Child}</AppShell>
);
}
}
export default App;
|
src/docs/apiExamples/SankeyChart.js | recharts/recharts.org | import React from 'react';
import { Sankey, Tooltip, Layer, Rectangle } from 'recharts';
const data0 = {
nodes: [
{ name: 'Visit' },
{ name: 'Direct-Favourite' },
{ name: 'Page-Click' },
{ name: 'Detail-Favourite' },
{ name: 'Lost' },
],
links: [
{ source: 0, target: 1, value: 3728.3 },
{ source: 0, target: 2, value: 354170 },
{ source: 2, target: 3, value: 62429 },
{ source: 2, target: 4, value: 291741 },
],
};
const MyCustomNode = ({ x, y, width, height, index, payload, containerWidth }) => {
const isOut = x + width + 6 > containerWidth;
return (
<Layer key={`CustomNode${index}`}>
<Rectangle x={x} y={y} width={width} height={height} fill="#5192ca" fillOpacity="1" />
<text
textAnchor={isOut ? 'end' : 'start'}
x={isOut ? x - 6 : x + width + 6}
y={y + height / 2}
fontSize="14"
stroke="#333"
>
{payload.name}
</text>
<text
textAnchor={isOut ? 'end' : 'start'}
x={isOut ? x - 6 : x + width + 6}
y={y + height / 2 + 13}
fontSize="12"
stroke="#333"
strokeOpacity="0.5"
>
{`${payload.value}k`}
</text>
</Layer>
);
};
const example = () => (
<Sankey
width={960}
height={500}
data={data0}
node={<MyCustomNode />}
nodePadding={50}
margin={{
left: 200,
right: 200,
top: 100,
bottom: 100,
}}
link={{ stroke: '#77c878' }}
>
<Tooltip />
</Sankey>
);
const exampleCode = `
<Sankey
width={960}
height={500}
data={data0}
node={<MyCustomNode />}
nodePadding={50}
margin={{
left: 200,
right: 200,
top: 100,
bottom: 100,
}}
link={{ stroke: '#77c878' }}
>
<Tooltip />
</Sankey>
`;
export default [
{
demo: example,
code: exampleCode,
dataCode: `
const data0 = ${JSON.stringify(data0, null, 2)};
`,
},
];
|
node_modules/react-bootstrap/es/Tab.js | WatkinsSoftwareDevelopment/HowardsBarberShop | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import TabContainer from './TabContainer';
import TabContent from './TabContent';
import TabPane from './TabPane';
var propTypes = _extends({}, TabPane.propTypes, {
disabled: React.PropTypes.bool,
title: React.PropTypes.node,
/**
* tabClassName is used as className for the associated NavItem
*/
tabClassName: React.PropTypes.string
});
var Tab = function (_React$Component) {
_inherits(Tab, _React$Component);
function Tab() {
_classCallCheck(this, Tab);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tab.prototype.render = function render() {
var props = _extends({}, this.props);
// These props are for the parent `<Tabs>` rather than the `<TabPane>`.
delete props.title;
delete props.disabled;
delete props.tabClassName;
return React.createElement(TabPane, props);
};
return Tab;
}(React.Component);
Tab.propTypes = propTypes;
Tab.Container = TabContainer;
Tab.Content = TabContent;
Tab.Pane = TabPane;
export default Tab; |
src/svg-icons/image/exposure-plus-2.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageExposurePlus2 = (props) => (
<SvgIcon {...props}>
<path d="M16.05 16.29l2.86-3.07c.38-.39.72-.79 1.04-1.18.32-.39.59-.78.82-1.17.23-.39.41-.78.54-1.17.13-.39.19-.79.19-1.18 0-.53-.09-1.02-.27-1.46-.18-.44-.44-.81-.78-1.11-.34-.31-.77-.54-1.26-.71-.51-.16-1.08-.24-1.72-.24-.69 0-1.31.11-1.85.32-.54.21-1 .51-1.36.88-.37.37-.65.8-.84 1.3-.18.47-.27.97-.28 1.5h2.14c.01-.31.05-.6.13-.87.09-.29.23-.54.4-.75.18-.21.41-.37.68-.49.27-.12.6-.18.96-.18.31 0 .58.05.81.15.23.1.43.25.59.43.16.18.28.4.37.65.08.25.13.52.13.81 0 .22-.03.43-.08.65-.06.22-.15.45-.29.7-.14.25-.32.53-.56.83-.23.3-.52.65-.88 1.03l-4.17 4.55V18H22v-1.71h-5.95zM8 7H6v4H2v2h4v4h2v-4h4v-2H8V7z"/>
</SvgIcon>
);
ImageExposurePlus2 = pure(ImageExposurePlus2);
ImageExposurePlus2.displayName = 'ImageExposurePlus2';
ImageExposurePlus2.muiName = 'SvgIcon';
export default ImageExposurePlus2;
|
src/Tooltip/Tooltip.js | yurizhang/ishow | import React from 'react';
import PropTypes from 'prop-types';
import {default as Component,View} from '../Common/plugs/index.js'; //提供style, classname方法
import Transition from '../Message/transition';
import Popper from '../Common/utils/popper';
import '../Common/css/Tooltip.css';
import '../Common/css/Popover.css';
export default class Tooltip extends Component {
constructor(props) {
super(props);
this.state = {
showPopper: false
}
}
componentWillReceiveProps(props) {
if (props.visible !== this.props.visible) {
this.setState({
showPopper: props.visible
});
}
}
showPopper() {
if (!this.props.manual) {
this.timeout = setTimeout(() => {
this.setState({ showPopper: true });
}, this.props.openDelay);
}
}
hidePopper() {
if (!this.props.manual) {
clearTimeout(this.timeout);
this.setState({ showPopper: false });
}
}
onEnter() {
const { popper, reference, arrow } = this.refs;
if (arrow) {
arrow.setAttribute('x-arrow', '');
}
this.popperJS = new Popper(reference, popper, {
placement: this.props.placement,
gpuAcceleration: false
});
}
onAfterLeave() {
this.popperJS.destroy();
}
render() {
const { effect, content, disabled, transition, visibleArrow } = this.props;
return (
<div style={this.style()} className={this.className('ishow-tooltip')} onMouseEnter={this.showPopper.bind(this)} onMouseLeave={this.hidePopper.bind(this)}>
<div ref="reference" className="ishow-tooltip__rel">
<div>{ this.props.children }</div>
</div>
{
!disabled && (
<Transition name={transition} onEnter={this.onEnter.bind(this)} onAfterLeave={this.onAfterLeave.bind(this)}>
<View show={this.state.showPopper} >
<div ref="popper" className={ this.classNames("ishow-tooltip__popper", `is-${effect}`) }>
<div>{ content }</div>
{ visibleArrow && <div ref="arrow" className="popper__arrow"></div> }
</div>
</View>
</Transition>
)
}
</div>
)
}
}
Tooltip.propTypes = {
// 默认提供的主题: dark, light
effect: PropTypes.string,
// 显示的内容,也可以通过 slot#content 传入 DOM
content: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
// Tooltip 的出现位置 [top, top-start, top-end, bottom, bottom-start, bottom-end, left, left-start, left-end, right, right-start, right-end]
placement: PropTypes.oneOf(['top', 'top-start', 'top-end', 'bottom', 'bottom-start', 'bottom-end', 'left', 'left-start', 'left-end', 'right', 'right-start', 'right-end']),
// 状态是否可用
disabled: PropTypes.bool,
// 渐变动画定义
transition: PropTypes.string,
// 是否显示 Tooltip 箭头
visibleArrow: PropTypes.bool,
// 延迟出现(单位: 毫秒)
openDelay: PropTypes.number,
// 手动控制模式,设置为 true 后,mouseenter 和 mouseleave 事件将不会生效
manual: PropTypes.bool,
// 手动控制状态的展示
visible: PropTypes.bool
};
Tooltip.defaultProps = {
effect: "dark",
placement: "bottom",
disabled: false,
transition: "fade-in-linear",
visibleArrow: true,
openDelay: 0,
manual: false
}
|
src/components/Blog/Blog.react.js | DeveloperAlfa/chat.susi.ai | import './Blog.css';
import 'font-awesome/css/font-awesome.min.css';
import PropTypes from 'prop-types';
import htmlToText from 'html-to-text';
import $ from 'jquery';
import { Card, CardMedia, CardTitle, CardText, CardActions } from 'material-ui/Card';
import susi from '../../images/susi-logo.svg';
import dateFormat from 'dateformat';
import StaticAppBar from '../StaticAppBar/StaticAppBar.react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import Next from 'material-ui/svg-icons/hardware/keyboard-arrow-right';
import Previous from 'material-ui/svg-icons/hardware/keyboard-arrow-left';
import React, { Component } from 'react';
import renderHTML from 'react-render-html';
import Loading from 'react-loading-animation';
import Footer from '../Footer/Footer.react';
import {
ShareButtons,
generateShareIcon
} from 'react-share';
function arrDiff(a1, a2) {
var a = [], diff = [];
for (var f = 0; f < a1.length; f++) {
a[a1[f]] = true;
}
for (var z = 0; z < a2.length; z++) {
if (a[a2[z]]) {
delete a[a2[z]];
} else {
a[a2[z]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
};
class Blog extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
postRendered: false,
startPage: 0,
nextDisplay: 'visible',
prevDisplay: 'hidden',
}
}
componentDidMount() {
// Adding title tag to page
document.title = 'Blog Posts about Open Source Artificial Intelligence for Personal Assistants, Robots, Help Desks and Chatbots - SUSI.AI';
// Scrolling to top of page when component loads
$('html, body').animate({ scrollTop: 0 }, 'fast');
// Ajax call to convert the RSS feed to JSON format
$.ajax({
url: 'https://api.rss2json.com/v1/api.json',
method: 'GET',
dataType: 'json',
data: {
'rss_url': 'http://blog.fossasia.org/tag/susi-ai/feed/',
'api_key': 'qsmzjtyycc49whsfvf5ikzottxrbditq3burojhd', // put your api key here
'count': 50
}
}).done(function (response) {
if (response.status !== 'ok') { throw response.message; }
this.setState({ posts: response.items, postRendered: true });
}.bind(this));
}
scrollStep() {
if (window.pageYOffset === 0) {
clearInterval(this.state.intervalId);
}
window.scroll(0, window.pageYOffset - 1000);
}
// Function to scroll to top of page
scrollToTop() {
let intervalId = setInterval(this.scrollStep.bind(this), 16.66);
this.setState({ intervalId: intervalId });
}
// Function to navigate to previous page
previousPage = () => {
let current = this.state.startPage;
if (current - 10 === 0) {
this.setState({ startPage: current - 10, prevDisplay: 'hidden', nextDisplay: 'visible' })
}
else {
this.setState({ startPage: current - 10, prevDisplay: 'visible', nextDisplay: 'visible' })
}
this.scrollToTop();
}
// Function to navigate to next page
nextPage = () => {
let current = this.state.startPage;
let size = this.state.posts.length;
console.log(size)
if (current + 10 === size - 10) {
this.setState({ startPage: current + 10, nextDisplay: 'hidden', prevDisplay: 'visible' })
}
else {
this.setState({ startPage: current + 10, prevDisplay: 'visible', nextDisplay: 'visible' })
}
this.scrollToTop();
}
render() {
const {
FacebookShareButton,
TwitterShareButton,
} = ShareButtons;
const FacebookIcon = generateShareIcon('facebook');
const TwitterIcon = generateShareIcon('twitter');
const nextStyle = {
visibility: this.state.nextDisplay,
marginLeft: '10px'
}
const prevStyle = {
visibility: this.state.prevDisplay
}
const loadingStyle = {
marginTop: '20px',
position: 'relative',
}
const allCategories = ['FOSSASIA', 'GSoC', 'SUSI.AI',
'Tutorial', 'Android', 'API', 'App generator', 'CodeHeat', 'Community', 'Event',
'Event Management', 'loklak', 'Meilix', 'Open Event', 'Phimpme', 'Pocket Science Lab', 'yaydoc'];
return (
<div>
<StaticAppBar {...this.props}
location={this.props.location} />
<div className='head_section'>
<div className='container'>
<div className="heading">
<h1>Blog</h1>
<p>Latest Blog Posts on SUSI.AI</p>
</div>
</div>
</div>
<Loading
style={loadingStyle}
isLoading={!this.state.postRendered} />
{!this.state.postRendered &&
(<div><center>Fetching Blogs..</center></div>)}
{this.state.postRendered && (<div>
<div style={{ width: '100%' }}>
{
this.state.posts
.slice(this.state.startPage, this.state.startPage + 10)
.map((posts, i) => {
let description = htmlToText.fromString(posts.description).split('…');
let content = posts.content;
let category = [];
posts.categories.forEach((cat) => {
let k = 0;
for (k = 0; k < allCategories.length; k++) {
if (cat === allCategories[k]) {
category.push(cat);
}
}
});
var tags = arrDiff(category, posts.categories)
let fCategory = category.map((cat) =>
<span key={cat} ><a className="tagname" href={'http://blog.fossasia.org/category/' + cat.replace(/\s+/g, '-').toLowerCase()}
rel="noopener noreferrer">{cat}</a></span>
);
let ftags = tags.map((tag) =>
<span key={tag} ><a className="tagname" href={'http://blog.fossasia.org/tag/' + tag.replace(/\s+/g, '-').toLowerCase()}
rel="noopener noreferrer">{tag}</a></span>
);
let htmlContent = content.replace(/<img.*?>/, '');
htmlContent = renderHTML(htmlContent);
let image = susi
let regExp = /\[(.*?)\]/;
let imageUrl = regExp.exec(description[0]);
if (imageUrl) {
image = imageUrl[1]
}
let date = posts.pubDate.split(' ');
let d = new Date(date[0]);
return (
<div key={i} className="section_blog">
<Card style={{ width: '100%', padding: '0' }}>
<CardMedia
overlay={
<CardTitle
className="noUnderline"
subtitle={renderHTML('<a href="' + posts.link + '" >Published on ' + dateFormat(d, 'dddd, mmmm dS, yyyy') + '</a>')} />
}>
<img className="featured_image"
src={image}
alt={posts.title}
/>
</CardMedia>
<CardTitle className="noUnderline" title={posts.title} subtitle={renderHTML('by <a href="http://blog.fossasia.org/author/' + posts.author + '" >' + posts.author + '</a>')} />
<CardText style={{ fontSize: '16px' }}> {htmlContent}
</CardText>
<div className="social-btns">
<TwitterShareButton
url={posts.guid}
title={posts.title}
via='asksusi'
hashtags={posts.categories.slice(0, 4)} >
<TwitterIcon
size={32}
round={true} />
</TwitterShareButton>
<FacebookShareButton url={posts.link}>
<FacebookIcon size={32} round={true} />
</FacebookShareButton>
</div>
<CardActions className="cardActions">
<span className="calendarContainer">
<i className="fa fa-calendar tagIcon"></i>
{renderHTML('<a href="' + posts.link + '">' + dateFormat(d, 'mmmm dd, yyyy') + '</a>')}
</span>
<span className="authorsContainer">
<i className="fa fa-user tagIcon"></i>
<a
rel="noopener noreferrer"
href={'http://blog.fossasia.org/author/' + posts.author}
>
{posts.author}
</a></span>
<span className='categoryContainer'>
<i className="fa fa-folder-open-o tagIcon"></i>
{fCategory}
</span>
<span className='tagsContainer'>
<i className="fa fa-tags tagIcon"></i>
{ftags}
</span>
</CardActions>
</Card>
</div>
)
})
}
</div>
<div className="blog_navigation">
<FloatingActionButton
style={prevStyle}
backgroundColor={'#4285f4'}
onTouchTap={this.previousPage}>
<Previous />
</FloatingActionButton>
<FloatingActionButton
style={nextStyle}
backgroundColor={'#4285f4'}
onTouchTap={this.nextPage}>
<Next />
</FloatingActionButton>
</div>
<div className="post_bottom"></div>
<Footer />
</div>)}
</div>
);
}
}
Blog.propTypes = {
history: PropTypes.object,
location: PropTypes.object
}
export default Blog;
|
docs/app/Examples/elements/Input/Variations/InputExampleActionIconButton.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Input } from 'semantic-ui-react'
const InputExampleActionIconButton = () => (
<Input action={{ icon: 'search' }} placeholder='Search...' />
)
export default InputExampleActionIconButton
|
src/svg-icons/device/signal-cellular-connected-no-internet-1-bar.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet1Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 10v8h2v-8h-2zm-8 12V12L2 22h10zm8 0h2v-2h-2v2z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet1Bar = pure(DeviceSignalCellularConnectedNoInternet1Bar);
DeviceSignalCellularConnectedNoInternet1Bar.displayName = 'DeviceSignalCellularConnectedNoInternet1Bar';
DeviceSignalCellularConnectedNoInternet1Bar.muiName = 'SvgIcon';
export default DeviceSignalCellularConnectedNoInternet1Bar;
|
src/components/Square.js | marcjohnstonuw/bingo-gen | import React, { Component } from 'react';
class GameType extends Component {
constructor (props) {
super(props);
this.state = {
isEditing: props.data.text ? false : true,
newText: props.data.text
};
}
onSave () {
this.setState({
isEditing: false
})
this.props.onSave(this.props.data.id, this.state.newText);
}
render () {
return (
<div>
{this.state.isEditing ?
<input onChange={(ev) => this.setState({newText: ev.target.value})}
value={this.state.newText} /> :
this.props.data.text
}
{this.state.isEditing ?
<button onClick={() => this.onSave() }>Save</button> :
<button onClick={() => this.setState({isEditing: true})}>Edit</button>
}
</div>
)
}
}
export default GameType; |
webpack/scenes/ModuleStreams/ModuleStreamsPage.js | cfouant/katello | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Grid, Row, Col, Form, FormGroup } from 'react-bootstrap';
import qs from 'query-string';
import Search from '../../components/Search/index';
import ModuleStreamsTable from './ModuleStreamsTable';
import { orgId } from '../../services/api';
class ModuleStreamsPage extends Component {
constructor(props) {
super(props);
const queryParams = qs.parse(this.props.location.search);
this.state = {
searchQuery: queryParams.search || '',
};
}
componentDidMount() {
this.props.getModuleStreams({
search: this.state.searchQuery,
});
}
onPaginationChange = (pagination) => {
this.props.getModuleStreams({
...pagination,
});
};
onSearch = (search) => {
this.props.getModuleStreams({ search });
};
getAutoCompleteParams = search => ({
endpoint: '/module_streams/auto_complete_search',
params: {
organization_id: orgId(),
search,
},
});
updateSearchQuery = (searchQuery) => {
this.setState({ searchQuery });
};
render() {
const { moduleStreams } = this.props;
return (
<Grid bsClass="container-fluid">
<Row>
<Col sm={12}>
<h1>{__('Module Streams')}</h1>
</Col>
</Row>
<Row>
<Col sm={6}>
<Form className="toolbar-pf-actions">
<FormGroup className="toolbar-pf toolbar-pf-filter">
<Search
onSearch={this.onSearch}
getAutoCompleteParams={this.getAutoCompleteParams}
updateSearchQuery={this.updateSearchQuery}
initialInputValue={this.state.searchQuery}
/>
</FormGroup>
</Form>
</Col>
</Row>
<Row>
<Col sm={12}>
<ModuleStreamsTable
moduleStreams={moduleStreams}
onPaginationChange={this.onPaginationChange}
/>
</Col>
</Row>
</Grid>
);
}
}
ModuleStreamsPage.propTypes = {
location: PropTypes.shape({
search: PropTypes.oneOfType([
PropTypes.shape({}),
PropTypes.string,
]),
}),
getModuleStreams: PropTypes.func.isRequired,
moduleStreams: PropTypes.shape({}).isRequired,
};
ModuleStreamsPage.defaultProps = {
location: { search: '' },
};
export default ModuleStreamsPage;
|
src/components/Sidebar.js | maloun96/react-admin | import React from 'react';
import {render} from 'react-dom';
import {Link} from 'react-router-dom';
class Sidebar extends React.Component {
render(){
return (
<div>
<aside className="main-sidebar">
<section className="sidebar">
<div className="user-panel">
<div className="pull-left image">
<img src="public/dist/img/user2-160x160.jpg" className="img-circle" alt="User Image" />
</div>
<div className="pull-left info">
<p>Alexander Pierce</p>
<a href="public/#"><i className="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<form action="#" method="get" className="sidebar-form">
<div className="input-group">
<input type="text" name="q" className="form-control" placeholder="Search..." />
<span className="input-group-btn">
<button type="submit" name="search" id="search-btn" className="btn btn-flat"><i className="fa fa-search"></i>
</button>
</span>
</div>
</form>
<ul className="sidebar-menu">
<li className="header">MAIN NAVIGATION</li>
<li><Link to='/add-quiz'>Add Quiz</Link></li>
<li><Link to='/list-quiz'>List of quizes</Link></li>
<li><Link to='/mail'>Mail</Link></li>
</ul>
</section>
</aside>
</div>
);
}
}
export default Sidebar;
|
docs/src/app/components/pages/components/AutoComplete/ExampleSimple.js | ruifortes/material-ui | import React from 'react';
import AutoComplete from 'material-ui/AutoComplete';
export default class AutoCompleteExampleSimple extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
};
}
handleUpdateInput = (value) => {
this.setState({
dataSource: [
value,
value + value,
value + value + value,
],
});
};
render() {
return (
<div>
<AutoComplete
hintText="Type anything"
dataSource={this.state.dataSource}
onUpdateInput={this.handleUpdateInput}
/>
<AutoComplete
hintText="Type anything"
dataSource={this.state.dataSource}
onUpdateInput={this.handleUpdateInput}
floatingLabelText="Full width"
fullWidth={true}
/>
</div>
);
}
}
|
src/website/app/demos/Grid/common/DemoLayout.js | mineral-ui/mineral-ui | /* @flow */
import styled from '@emotion/styled';
import { clearFix } from 'polished';
import React from 'react';
import { ignoreSsrWarning } from '../../../../../library/utils/emotion';
import type { StyledComponent } from '@emotion/styled-base/src/utils';
const Root: StyledComponent<{ [key: string]: any }> = styled('div')(
({ lastRowStartsAt }) => {
const condition = lastRowStartsAt
? `:nth-child(n + ${lastRowStartsAt})${ignoreSsrWarning}`
: ':last-child';
return {
...clearFix(),
[`& > *:not(${condition})`]: {
marginBottom: '1rem'
}
};
}
);
const DemoLayout = (props: Object) => <Root {...props} />;
export default DemoLayout;
|
src/pages/index.js | daudahmad/daudahmad.github.io | import React from 'react'
import { Link, graphql } from 'gatsby'
import Bio from '../components/Bio'
import Layout from '../components/Layout'
import SEO from '../components/seo'
import { rhythm } from '../utils/typography'
class BlogIndex extends React.Component {
render() {
const { data } = this.props
const siteTitle = data.site.siteMetadata.title
const posts = data.allMarkdownRemark.edges
return (
<Layout location={this.props.location} title={siteTitle}>
<SEO
title="All posts"
keywords={[`blog`, `gatsby`, `javascript`, `react`]}
/>
<Bio />
{posts.map(({ node }) => {
const title = node.frontmatter.title || node.fields.slug
return (
<div key={node.fields.slug}>
<h3
style={{
marginBottom: rhythm(1 / 4),
}}
>
<Link style={{ boxShadow: `none` }} to={node.fields.slug}>
{title}
</Link>
</h3>
<small>{node.frontmatter.date}</small>
<p dangerouslySetInnerHTML={{ __html: node.excerpt }} />
</div>
)
})}
</Layout>
)
}
}
export default BlogIndex
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
excerpt
fields {
slug
}
frontmatter {
date(formatString: "MMMM DD, YYYY")
title
}
}
}
}
}
`
|
app/javascript/mastodon/features/compose/components/reply_indicator.js | lynlynlynx/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from '../../../components/avatar';
import IconButton from '../../../components/icon_button';
import DisplayName from '../../../components/display_name';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import AttachmentList from 'mastodon/components/attachment_list';
const messages = defineMessages({
cancel: { id: 'reply_indicator.cancel', defaultMessage: 'Cancel' },
});
export default @injectIntl
class ReplyIndicator extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map,
onCancel: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onCancel();
}
handleAccountClick = (e) => {
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`);
}
}
render () {
const { status, intl } = this.props;
if (!status) {
return null;
}
const content = { __html: status.get('contentHtml') };
return (
<div className='reply-indicator'>
<div className='reply-indicator__header'>
<div className='reply-indicator__cancel'><IconButton title={intl.formatMessage(messages.cancel)} icon='times' onClick={this.handleClick} inverted /></div>
<a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='reply-indicator__display-name'>
<div className='reply-indicator__display-avatar'><Avatar account={status.get('account')} size={24} /></div>
<DisplayName account={status.get('account')} />
</a>
</div>
<div className='reply-indicator__content translate' dangerouslySetInnerHTML={content} />
{status.get('media_attachments').size > 0 && (
<AttachmentList
compact
media={status.get('media_attachments')}
/>
)}
</div>
);
}
}
|
app/javascript/flavours/glitch/components/media_gallery.js | Kirishima21/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { is } from 'immutable';
import IconButton from './icon_button';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from 'flavours/glitch/util/is_mobile';
import classNames from 'classnames';
import { autoPlayGif, displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state';
import { debounce } from 'lodash';
import Blurhash from 'flavours/glitch/components/blurhash';
const messages = defineMessages({
hidden: {
defaultMessage: 'Media hidden',
id: 'status.media_hidden',
},
sensitive: {
defaultMessage: 'Sensitive',
id: 'media_gallery.sensitive',
},
toggle: {
defaultMessage: 'Click to view',
id: 'status.sensitive_toggle',
},
toggle_visible: {
defaultMessage: '{number, plural, one {Hide image} other {Hide images}}',
id: 'media_gallery.toggle_visible',
},
warning: {
defaultMessage: 'Sensitive content',
id: 'status.sensitive_warning',
},
});
class Item extends React.PureComponent {
static propTypes = {
attachment: ImmutablePropTypes.map.isRequired,
standalone: PropTypes.bool,
index: PropTypes.number.isRequired,
size: PropTypes.number.isRequired,
letterbox: PropTypes.bool,
onClick: PropTypes.func.isRequired,
displayWidth: PropTypes.number,
visible: PropTypes.bool.isRequired,
autoplay: PropTypes.bool,
};
static defaultProps = {
standalone: false,
index: 0,
size: 1,
};
state = {
loaded: false,
};
handleMouseEnter = (e) => {
if (this.hoverToPlay()) {
e.target.play();
}
}
handleMouseLeave = (e) => {
if (this.hoverToPlay()) {
e.target.pause();
e.target.currentTime = 0;
}
}
getAutoPlay() {
return this.props.autoplay || autoPlayGif;
}
hoverToPlay () {
const { attachment } = this.props;
return !this.getAutoPlay() && attachment.get('type') === 'gifv';
}
handleClick = (e) => {
const { index, onClick } = this.props;
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
if (this.hoverToPlay()) {
e.target.pause();
e.target.currentTime = 0;
}
e.preventDefault();
onClick(index);
}
e.stopPropagation();
}
handleImageLoad = () => {
this.setState({ loaded: true });
}
render () {
const { attachment, index, size, standalone, letterbox, displayWidth, visible } = this.props;
let width = 50;
let height = 100;
let top = 'auto';
let left = 'auto';
let bottom = 'auto';
let right = 'auto';
if (size === 1) {
width = 100;
}
if (size === 4 || (size === 3 && index > 0)) {
height = 50;
}
if (size === 2) {
if (index === 0) {
right = '2px';
} else {
left = '2px';
}
} else if (size === 3) {
if (index === 0) {
right = '2px';
} else if (index > 0) {
left = '2px';
}
if (index === 1) {
bottom = '2px';
} else if (index > 1) {
top = '2px';
}
} else if (size === 4) {
if (index === 0 || index === 2) {
right = '2px';
}
if (index === 1 || index === 3) {
left = '2px';
}
if (index < 2) {
bottom = '2px';
} else {
top = '2px';
}
}
let thumbnail = '';
if (attachment.get('type') === 'unknown') {
return (
<div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
<a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || attachment.get('url')} style={{ cursor: 'pointer' }} title={attachment.get('description')} target='_blank' rel='noopener noreferrer'>
<Blurhash
hash={attachment.get('blurhash')}
className='media-gallery__preview'
dummy={!useBlurhash}
/>
</a>
</div>
);
} else if (attachment.get('type') === 'image') {
const previewUrl = attachment.get('preview_url');
const previewWidth = attachment.getIn(['meta', 'small', 'width']);
const originalUrl = attachment.get('url');
const originalWidth = attachment.getIn(['meta', 'original', 'width']);
const hasSize = typeof originalWidth === 'number' && typeof previewWidth === 'number';
const srcSet = hasSize ? `${originalUrl} ${originalWidth}w, ${previewUrl} ${previewWidth}w` : null;
const sizes = hasSize && (displayWidth > 0) ? `${displayWidth * (width / 100)}px` : null;
const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0;
const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0;
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
thumbnail = (
<a
className='media-gallery__item-thumbnail'
href={attachment.get('remote_url') || originalUrl}
onClick={this.handleClick}
target='_blank'
rel='noopener noreferrer'
>
<img
className={letterbox ? 'letterbox' : null}
src={previewUrl}
srcSet={srcSet}
sizes={sizes}
alt={attachment.get('description')}
title={attachment.get('description')}
style={{ objectPosition: letterbox ? null : `${x}% ${y}%` }}
onLoad={this.handleImageLoad}
/>
</a>
);
} else if (attachment.get('type') === 'gifv') {
const autoPlay = !isIOS() && this.getAutoPlay();
thumbnail = (
<div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}>
<video
className={`media-gallery__item-gifv-thumbnail${letterbox ? ' letterbox' : ''}`}
aria-label={attachment.get('description')}
title={attachment.get('description')}
role='application'
src={attachment.get('url')}
onClick={this.handleClick}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
autoPlay={autoPlay}
loop
muted
/>
<span className='media-gallery__gifv__label'>GIF</span>
</div>
);
}
return (
<div className={classNames('media-gallery__item', { standalone, letterbox })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
<Blurhash
hash={attachment.get('blurhash')}
dummy={!useBlurhash}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': visible && this.state.loaded,
})}
/>
{visible && thumbnail}
</div>
);
}
}
export default @injectIntl
class MediaGallery extends React.PureComponent {
static propTypes = {
sensitive: PropTypes.bool,
standalone: PropTypes.bool,
letterbox: PropTypes.bool,
fullwidth: PropTypes.bool,
hidden: PropTypes.bool,
media: ImmutablePropTypes.list.isRequired,
size: PropTypes.object,
onOpenMedia: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
defaultWidth: PropTypes.number,
cacheWidth: PropTypes.func,
visible: PropTypes.bool,
autoplay: PropTypes.bool,
onToggleVisibility: PropTypes.func,
};
static defaultProps = {
standalone: false,
};
state = {
visible: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'),
width: this.props.defaultWidth,
};
componentDidMount () {
window.addEventListener('resize', this.handleResize, { passive: true });
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
componentWillReceiveProps (nextProps) {
if (!is(nextProps.media, this.props.media) && nextProps.visible === undefined) {
this.setState({ visible: displayMedia !== 'hide_all' && !nextProps.sensitive || displayMedia === 'show_all' });
} else if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) {
this.setState({ visible: nextProps.visible });
}
}
componentDidUpdate (prevProps) {
if (this.node) {
this.handleResize();
}
}
handleResize = debounce(() => {
if (this.node) {
this._setDimensions();
}
}, 250, {
leading: true,
trailing: true,
});
handleOpen = () => {
if (this.props.onToggleVisibility) {
this.props.onToggleVisibility();
} else {
this.setState({ visible: !this.state.visible });
}
}
handleClick = (index) => {
this.props.onOpenMedia(this.props.media, index);
}
handleRef = (node) => {
this.node = node;
if (this.node) {
this._setDimensions();
}
}
_setDimensions () {
const width = this.node.offsetWidth;
if (width && width != this.state.width) {
// offsetWidth triggers a layout, so only calculate when we need to
if (this.props.cacheWidth) {
this.props.cacheWidth(width);
}
this.setState({
width: width,
});
}
}
isStandaloneEligible() {
const { media, standalone } = this.props;
return standalone && media.size === 1 && media.getIn([0, 'meta', 'small', 'aspect']);
}
render () {
const { media, intl, sensitive, letterbox, fullwidth, defaultWidth, autoplay } = this.props;
const { visible } = this.state;
const size = media.take(4).size;
const uncached = media.every(attachment => attachment.get('type') === 'unknown');
const width = this.state.width || defaultWidth;
let children, spoilerButton;
const style = {};
const computedClass = classNames('media-gallery', { 'full-width': fullwidth });
if (this.isStandaloneEligible() && width) {
style.height = width / this.props.media.getIn([0, 'meta', 'small', 'aspect']);
} else if (width) {
style.height = width / (16/9);
} else {
return (<div className={computedClass} ref={this.handleRef}></div>);
}
if (this.isStandaloneEligible()) {
children = <Item standalone autoplay={autoplay} onClick={this.handleClick} attachment={media.get(0)} displayWidth={width} visible={visible} />;
} else {
children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} autoplay={autoplay} onClick={this.handleClick} attachment={attachment} index={i} size={size} letterbox={letterbox} displayWidth={width} visible={visible || uncached} />);
}
if (uncached) {
spoilerButton = (
<button type='button' disabled className='spoiler-button__overlay'>
<span className='spoiler-button__overlay__label'><FormattedMessage id='status.uncached_media_warning' defaultMessage='Not available' /></span>
</button>
);
} else if (visible) {
spoilerButton = <IconButton title={intl.formatMessage(messages.toggle_visible, { number: size })} icon='eye-slash' overlay onClick={this.handleOpen} />;
} else {
spoilerButton = (
<button type='button' onClick={this.handleOpen} className='spoiler-button__overlay'>
<span className='spoiler-button__overlay__label'>{sensitive ? <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /> : <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />}</span>
</button>
);
}
return (
<div className={computedClass} style={style} ref={this.handleRef}>
<div className={classNames('spoiler-button', { 'spoiler-button--minified': visible && !uncached, 'spoiler-button--click-thru': uncached })}>
{spoilerButton}
{visible && sensitive && (
<span className='sensitive-marker'>
<FormattedMessage {...messages.sensitive} />
</span>
)}
</div>
{children}
</div>
);
}
}
|
examples/with-redux-reselect-recompose/components/clock.js | callumlocke/next.js | import React from 'react'
import PropTypes from 'prop-types'
import { compose, pure, setDisplayName, setPropTypes } from 'recompose'
const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
const pad = n => n < 10 ? `0${n}` : n
const Clock = ({ lastUpdate, light }) =>
<div className={light ? 'light' : ''}>
{format(new Date(lastUpdate))}
<style jsx>{`
div {
padding: 15px;
display: inline-block;
color: #82FA58;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div>
export default compose(
setDisplayName('Clock'),
setPropTypes({
lastUpdate: PropTypes.number,
light: PropTypes.bool
}),
pure
)(Clock)
|
src/views/IconView.js | nitrog7/nl-fluid | import React from 'react';
import * as components from 'components';
const {
Box,
Code,
Component,
Container
} = components;
export default class IconView extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<Container direction="column">
<h1>Icon</h1>
<p> </p>
<h3>Default</h3>
<Code>
<span className="code_comment">// Default</span><br/>
<Box></Box><br/>
</Code>
<Box>Test</Box>
</Container>
);
}
}
|
src/components/footer.js | paulckennedy/KennedyChemistryRocks | import React from 'react';
export default (props) => {
return (
<div>
<footer className="hg_footer">
<div className="contactus">
<h3>Tracy Kennedy MS.</h3>
<div clasclassNames="address">
<h1 className="bigOne"></h1>
<ul id="address">
<li><i className="fa fa-road"></i> Carthage High School</li>
<li>#1 Bulldog Drive</li>
<li>Carthage, Texas 75633</li>
</ul>
</div>
<div className="content">
<pre id="object"></pre>
</div>
<div clclassNameass="contacttypes">
<ul id="contactinfo">
<li><i className="fa fa-envelope-o"></i> Email: [email protected]</li>
<li><i className="fa fa-phone"></i> Phone: 903-693-2552</li>
<li>Conference: 4th Period</li>
<li>Room: D5</li>
</ul>
</div>
</div>
</footer>
</div>
);
} |
app/javascript/mastodon/features/getting_started/index.js | pixiv/mastodon | import React from 'react';
import Column from '../ui/components/column';
import ColumnLink from '../ui/components/column_link';
import ColumnSubheading from '../ui/components/column_subheading';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me } from '../../initial_state';
import { fetchFollowRequests } from '../../actions/accounts';
import { List as ImmutableList } from 'immutable';
import Toggle from 'react-toggle';
import { changeSetting } from '../../actions/settings';
import PawooGettingStartedOnOnboardingPage from '../../../pawoo/components/getting_started_on_onboarding_page';
const messages = defineMessages({
heading: { id: 'getting_started.heading', defaultMessage: 'Getting started' },
home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' },
notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' },
public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' },
navigation_subheading: { id: 'column_subheading.navigation', defaultMessage: 'Navigation' },
settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' },
community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' },
direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' },
preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
sign_out: { id: 'navigation_bar.logout', defaultMessage: 'Logout' },
favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' },
blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' },
domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' },
mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' },
help: { id: 'navigation_bar.help', defaultMessage: 'Pawoo Help' },
info: { id: 'navigation_bar.info', defaultMessage: 'Extended information' },
pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' },
lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
keyboard_shortcuts: { id: 'navigation_bar.keyboard_shortcuts', defaultMessage: 'Keyboard shortcuts' },
suggested_accounts: { id: 'navigation_bar.suggested_accounts', defaultMessage: 'Active Accounts' },
media_timeline: { id: 'navigation_bar.media_timeline', defaultMessage: 'Media timeline' },
gallery: { id: 'pawoo.navigation_bar.gallery', defaultMessage: 'Gallery' },
});
const mapStateToProps = state => ({
myAccount: state.getIn(['accounts', me]),
columns: state.getIn(['settings', 'columns']),
unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size,
unreadNotifications: state.getIn(['notifications', 'unread']),
pawooMultiColumn: state.getIn(['settings', 'pawoo', 'multiColumn']),
pawooPage: state.getIn(['pawoo', 'page']),
});
const mapDispatchToProps = dispatch => ({
fetchFollowRequests: () => dispatch(fetchFollowRequests()),
pawooToggleMultiColumn: checked => dispatch(changeSetting(['pawoo', 'multiColumn'], checked)),
});
const badgeDisplay = (number, limit) => {
if (number === 0) {
return undefined;
} else if (limit && number >= limit) {
return `${limit}+`;
} else {
return number;
}
};
@connect(mapStateToProps, mapDispatchToProps)
@injectIntl
export default class GettingStarted extends ImmutablePureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
myAccount: ImmutablePropTypes.map.isRequired,
columns: ImmutablePropTypes.list,
multiColumn: PropTypes.bool,
fetchFollowRequests: PropTypes.func.isRequired,
unreadFollowRequests: PropTypes.number,
unreadNotifications: PropTypes.number,
pawooMultiColumn: PropTypes.bool,
pawooPage: PropTypes.string,
pawooToggleMultiColumn: PropTypes.func.isRequired,
};
componentDidMount () {
const { myAccount, fetchFollowRequests } = this.props;
if (myAccount.get('locked')) {
fetchFollowRequests();
}
}
pawooHandleColumnToggle = ({ target }) => {
this.props.pawooToggleMultiColumn(target.checked);
}
render () {
const { intl, myAccount, columns, multiColumn, unreadFollowRequests, unreadNotifications, pawooMultiColumn, pawooPage } = this.props;
const navItems = [];
if (multiColumn) {
if (pawooPage === 'ONBOARDING') {
return <PawooGettingStartedOnOnboardingPage />;
}
if (!columns.find(item => item.get('id') === 'HOME')) {
navItems.push(<ColumnLink key='0' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/timelines/home' />);
}
if (!columns.find(item => item.get('id') === 'NOTIFICATIONS')) {
navItems.push(<ColumnLink key='1' icon='bell' text={intl.formatMessage(messages.notifications)} badge={badgeDisplay(unreadNotifications)} to='/notifications' />);
}
if (!columns.find(item => item.get('id') === 'COMMUNITY')) {
navItems.push(<ColumnLink key='2' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />);
}
if (!columns.find(item => item.get('id') === 'MEDIA')) {
navItems.push(<ColumnLink key='media_timeline' icon='image' text={intl.formatMessage(messages.media_timeline)} to='/timelines/public/media' />);
}
}
if (!multiColumn || !columns.find(item => item.get('id') === 'PUBLIC')) {
navItems.push(<ColumnLink key='3' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />);
}
if (!multiColumn || !columns.find(item => item.get('id') === 'DIRECT')) {
navItems.push(<ColumnLink key='4' icon='envelope' text={intl.formatMessage(messages.direct)} to='/timelines/direct' />);
}
navItems.push(
<ColumnLink key='suggested_accounts' icon='user-plus' text={intl.formatMessage(messages.suggested_accounts)} to='/suggested_accounts' />,
<ColumnLink key='5' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />,
<ColumnLink key='6' icon='bars' text={intl.formatMessage(messages.lists)} to='/lists' />
);
if (myAccount.get('locked')) {
navItems.push(<ColumnLink key='7' icon='users' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />);
}
if (multiColumn) {
navItems.push(<ColumnLink key='8' icon='question' text={intl.formatMessage(messages.keyboard_shortcuts)} to='/keyboard-shortcuts' />);
}
navItems.push(<ColumnLink key='9' icon='book' text={intl.formatMessage(messages.info)} href='/about/more' />);
navItems.push(<ColumnLink key='10' icon='image' text={intl.formatMessage(messages.gallery)} href='/pawoo/galleries' />);
return (
<Column icon='asterisk' heading={intl.formatMessage(messages.heading)} hideHeadingOnMobile>
<div className='getting-started__wrapper'>
<ColumnSubheading text={intl.formatMessage(messages.navigation_subheading)} />
{navItems}
<ColumnSubheading text={intl.formatMessage(messages.settings_subheading)} />
<ColumnLink icon='thumb-tack' text={intl.formatMessage(messages.pins)} to='/pinned' />
<ColumnLink icon='volume-off' text={intl.formatMessage(messages.mutes)} to='/mutes' />
<ColumnLink icon='ban' text={intl.formatMessage(messages.blocks)} to='/blocks' />
<ColumnLink icon='minus-circle' text={intl.formatMessage(messages.domain_blocks)} to='/domain_blocks' />
<ColumnLink icon='cog' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />
<ColumnLink icon='question-circle' text={intl.formatMessage(messages.help)} href='https://pawoo.pixiv.help/hc/ja' rel='noopener' target='_blank' />
<ColumnLink icon='sign-out' text={intl.formatMessage(messages.sign_out)} href='/auth/sign_out' method='delete' />
</div>
<div className='static-content getting-started'>
<p>
<a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/FAQ.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.faq' defaultMessage='FAQ' /></a> • <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/User-guide.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.userguide' defaultMessage='User Guide' /></a> • <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/Apps.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.appsshort' defaultMessage='Apps' /></a>
</p>
<p>
<FormattedMessage
id='getting_started.open_source_notice'
defaultMessage='Mastodon is open source software. You can contribute or report issues on GitHub at {github}.'
values={{ github: <a href='https://github.com/pixiv/mastodon' rel='noopener' target='_blank'>pixiv/mastodon (pawoo)</a> }}
/>
</p>
{multiColumn && (
<div className='pawoo-extension-getting-started__column-toggle'>
<div className='setting-toggle'>
<Toggle
checked={pawooMultiColumn}
id='pawoo-extension-getting-started__column-toggle'
onChange={this.pawooHandleColumnToggle}
/>
<label htmlFor='pawoo-extension-getting-started__column-toggle' className='setting-toggle__label'>
<FormattedMessage defaultMessage='Multicolumn' id='pawoo.multicolumn' />
</label>
</div>
</div>
)}
</div>
</Column>
);
}
}
|
src/shared/components/socialMedia/socialMediaItem/socialMediaItem.js | OperationCode/operationcode_frontend | import React from 'react';
import PropTypes from 'prop-types';
import styles from './socialMediaItem.css';
const SocialMediaItem = (props) => {
const {
smImage,
smText,
link,
} = props;
return (
<div className={styles.socialMediaItem}>
<a href={link} target="_blank" rel="noopener noreferrer">
<img src={smImage} alt={smText} />
</a>
</div>
);
};
SocialMediaItem.propTypes = {
smImage: PropTypes.string.isRequired,
smText: PropTypes.string.isRequired,
link: PropTypes.string.isRequired,
};
export default SocialMediaItem;
|
frontend/src/components/ChatMeta.js | nepeat/chatforesnics | import React from 'react';
import ReactHighstock from 'react-highcharts/ReactHighstock.src';
import HighchartsMore from 'highcharts-more';
import HighchatsExporting from 'highcharts-exporting';
// Modules
HighchartsMore(ReactHighstock.Highcharts);
HighchatsExporting(ReactHighstock.Highcharts);
const ChatMeta = ({ chat }) => {
if (!chat.daily) {
return null;
}
let dailyData = [];
for (let point of chat.daily) {
dailyData.push([point.time * 1000, point.count]);
}
const chartOptions = {
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Messages'
}
},
title: {
text: 'Messages'
},
series: [{
name: 'Messages',
data: dailyData
}]
};
return (
<div className='chatmeta'>
<ReactHighstock config={chartOptions}/>
</div>
);
};
export default ChatMeta;
|
src/parser/rogue/subtlety/modules/features/SymbolsOfDeathUptime.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import Analyzer from 'parser/core/Analyzer';
import Enemies from 'parser/shared/modules/Enemies';
class SymbolsOfDeathUptime extends Analyzer {
static dependencies = {
enemies: Enemies,
};
statistic() {
const symbolsOfDeathUptime = this.selectedCombatant.getBuffUptime(SPELLS.SYMBOLS_OF_DEATH.id) / this.owner.fightDuration;
return (
<StatisticBox
position={STATISTIC_ORDER.CORE(30)}
icon={<SpellIcon id={SPELLS.SYMBOLS_OF_DEATH.id} />}
value={`${formatPercentage(symbolsOfDeathUptime)} %`}
label="Symbols of Death uptime"
/>
);
}
}
export default SymbolsOfDeathUptime;
|
src/components/BoggleCube.js | jlfwong/boggle | import React, { Component } from 'react';
import { StyleSheet, css } from 'aphrodite';
import PureComponent from 'react-pure-render/component';
const RP = React.PropTypes;
const BoggleCube = (name, CUBE_WIDTH, CUBE_SPACING) => {
/**
* Render a single boggle cube.
*/
class _Cube extends PureComponent {
static displayName = name
static propTypes = {
// The letter to display on the cube (will be 2 letters in the case of
// 'Qu')
letter: RP.string.isRequired,
// True if the cube should display as "selected"
selected: RP.bool,
// True if the cube's border should display as "selected" if the cell is
// selected.
selectedBorder: RP.bool,
position: RP.oneOf(["start", "middle", "end"]),
}
static defaultProps = {
selected: false,
selectedBorder: true,
position: "middle"
};
render() {
const {
letter,
partOfWord,
position,
selected,
selectedBorder
} = this.props;
const cubeClassName = css(
styles.cube,
selected && selectedBorder && styles.cubeSelected
);
const cubeTextClassName = css(
styles.cubeText,
selected && styles.cubeTextSelected,
{
"start": styles.cubeTextStart,
"end": styles.cubeTextEnd
}[position]
);
return (
<div className={cubeClassName}>
<div className={css(styles.cubeInner)}>
<div className={cubeTextClassName}>
{letter}
</div>
</div>
</div>
);
}
};
const styles = StyleSheet.create({
cube: {
width: CUBE_WIDTH,
height: CUBE_WIDTH,
boxSizing: 'border-box',
borderRadius: CUBE_WIDTH / 5,
background: ('linear-gradient(to bottom, rgba(255,250,232,1) 0%, ' +
'rgba(166,163,151,1) 100%)'),
margin: CUBE_SPACING / 2,
padding: 1,
border: '1px solid #000',
},
cubeSelected: {
border: '1px solid #fff',
},
cubePartOfWord: {
border: '1px solid #cfc',
},
cubeInner: {
borderRadius: CUBE_WIDTH / 2,
width: CUBE_WIDTH - 4,
height: CUBE_WIDTH - 4,
boxShadow: '0 0 1px #E1DFCC',
boxSizing: 'border-box',
background: '#E1DFCC',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontFamily: 'Arial Bold, sans-serif'
},
cubeText: {
color: 'black',
fontSize: CUBE_WIDTH / 2.5,
},
cubeTextSelected: {
color: 'white',
textShadow: `
-1px -1px 0 black,
-1px 1px 0 black,
1px -1px 0 black,
1px 1px 0 black
`,
},
cubeTextStart: {
color: '#ccf',
},
cubeTextEnd: {
color: '#fcc',
},
});
return _Cube;
};
export default BoggleCube;
|
node/client/src/views/Page/Page.js | joseph-bakke/hack4cause | import React from 'react';
import axios from 'axios';
import _ from 'lodash';
import Layout from '../Shared/Layout';
import Graph from '../Shared/Graph';
import ButtonSelectorMenu from '../Shared/ButtonSelectorMenu';
const eugeneOverviewEndpoint = 'http://localhost:3001/eugeneData';
const ignoreFields = ['index', 'rentMed', 'year'];
const labelMappings = {
unemployment: 'Regional Unemployment',
totalWages: 'Total Wages',
avgWage: 'Average Wage',
natHHMedIncome: 'National Average Wage',
housingMed: 'Median Housing Price',
zhvi: 'Zillow Median Housing Price',
natUnemployment: 'National Unemployment'
};
export default React.createClass({
getInitialState() {
return {
data: {},
selectedKeys: ['housingMed', 'zhvi'],
errors: []
}
},
componentWillMount() {
axios.get(eugeneOverviewEndpoint)
.then((res) => {
this.parseData(res.data);
})
.catch((err) => {
const errors = this.state.errors.concat([err]);
this.setState({errors});
});
},
parseData(returnedData) {
const dataSets = Object.keys(_.first(returnedData)).filter(key => !_.includes(ignoreFields, key));
const organizedData = {};
dataSets.forEach((dataSet) => {
organizedData[dataSet] = {
data: [],
label: labelMappings[dataSet]
};
returnedData.forEach((yearlyData) => {
organizedData[dataSet].data.push(yearlyData[dataSet]);
});
});
this.setState({
data: organizedData
});
},
updateSelectedKeys(keys) {
this.setState({selectedKeys: keys});
},
renderSelectors() {
const dataSets = Object.keys(labelMappings);
const buttonConfig = {};
dataSets.forEach((set) => {
const text = labelMappings[set];
buttonConfig[set] = {
label: <span>{text}</span>
};
});
return (
<ButtonSelectorMenu defaultSelected={this.state.selectedKeys} buttonConfig={buttonConfig} onSelectCallback={this.updateSelectedKeys} />
);
},
render() {
console.log(this.state);
if (!_.isEmpty(this.state.errors)) {
return (
<div>
{this.state.errors}
</div>
);
}
const descriptionJsx = (
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut doloribus enim in minima modi molestiae, nostrum soluta temporibus. Explicabo porro sequi tenetur. Autem, eligendi, error. Facilis iste modi sequi similique.</p>
);
const graphJsx = (
<div>
{_.isEmpty(this.state.data) === false && <Graph title={"Income Change"} datasets={this.state.data} selected={this.state.selectedKeys}/>}
</div>
);
return (
<Layout title={"Income"}
visualization={graphJsx}
description={descriptionJsx}>
{this.renderSelectors()}
</Layout>
);
}
});
|
src/containers/DevTools.js | robertcasanova/personal-website | import React from 'react'
// Exported from redux-devtools
import { createDevTools } from 'redux-devtools'
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
// createDevTools takes a monitor and produces a DevTools component
const DevTools = createDevTools(
// Monitors are individually adjustable with props.
// Consult their repositories to learn about those props.
// Here, we put LogMonitor inside a DockMonitor.
// Note: DockMonitor is visible by default.
<DockMonitor toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'
>
<LogMonitor theme='tomorrow' />
</DockMonitor>
)
export default DevTools
|
index.android.js | sercaninaler/chatbot | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class chatbot 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}>
Double tap R on your keyboard to reload,{'\n'}
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('chatbot', () => chatbot);
|
src/components/FileUpload.js | iGameLab/teleport-client | import React from 'react'
import PropTypes from 'prop-types'
import Dropzone from 'react-dropzone'
export default class FileUpload extends React.Component{
static propTypes = {
apiUrl: PropTypes.string.isRequired,
multiple: PropTypes.bool.isRequired,
extraData: PropTypes.object
}
constructor(props){
super(props)
this.state={
filesPreview:[],
filesToBeSent:[],
printcount:10,
accepted: [],
rejected: []
}
}
onDrop(){
console.log('yep, file drop')
}
handleClick(event){
if ( this.state.accepted.length > 0 ) {
var formData = new FormData();
this.state.accepted.forEach(function(image){
formData.append('images', image)
})
// 有时候在上传文件的时候需要一些其他的元数据。
if(this.props.extraData){
formData.append('data', JSON.stringify(this.props.extraData))
}
fetch( this.props.apiUrl , {
method:'POST',
body: formData
})
.then( result => result.json() )
.then( data => {
console.log(data)
if(data.success){
alert( data.message)
} else {
alert( data.message)
}
})
}
else{
// this.props.notify('error', '')
alert('你尚未选择任何图片')
}
}
render() {
const style = {
marginTop: '10px',
textAlign: 'center',
color: 'grey',
fontSize: '40px',
border: '1px dashed grey',
height: '60px',
width: '60px'
}
const btnStyle={
marginBottom: '20px'
}
return (
<section>
<div className="dropzone">
<Dropzone
style={ style }
multiple={ this.props.multiple }
accept="image/jpeg, image/png"
onDrop={(accepted, rejected) => { this.setState({ accepted, rejected }); }} >
+
</Dropzone>
<p>直接拖入文件或者点击该区域上传文件。只支持 *.jpeg和 *.png文件</p>
</div>
<aside>
<ul>
{
this.state.accepted.map(f => <li key={f.name}>{f.name} - {f.size} bytes</li>)
}
</ul>
</aside>
<button className="btn btn-success" style={btnStyle} onClick={this.handleClick.bind(this) }> 上传 </button>
</section>
)
}
} |
public/js/cat_source/es6/components/modals/ForgotPasswordModal.js | matecat/MateCat | import update from 'immutability-helper'
import React from 'react'
import TextField from '../common/TextField'
import * as RuleRunner from '../common/ruleRunner'
import * as FormRules from '../common/formRules'
import {forgotPassword} from '../../api/forgotPassword'
import {checkRedeemProject as checkRedeemProjectApi} from '../../api/checkRedeemProject'
class ForgotPasswordModal extends React.Component {
constructor(props) {
super(props)
this.state = {
showErrors: false,
validationErrors: {},
generalError: '',
requestRunning: false,
}
this.state.validationErrors = RuleRunner.run(this.state, fieldValidations)
this.handleFieldChanged = this.handleFieldChanged.bind(this)
this.handleSubmitClicked = this.handleSubmitClicked.bind(this)
this.errorFor = this.errorFor.bind(this)
}
openLoginModal() {
$('#modal').trigger('openlogin')
}
handleFieldChanged(field) {
return (e) => {
var newState = update(this.state, {
[field]: {$set: e.target.value},
})
newState.validationErrors = RuleRunner.run(newState, fieldValidations)
newState.generalError = ''
this.setState(newState)
}
}
handleSubmitClicked() {
var self = this
this.setState({showErrors: true})
if ($.isEmptyObject(this.state.validationErrors) == false) return null
if (this.state.requestRunning) {
return false
}
this.setState({requestRunning: true})
this.checkRedeemProject().then(
this.sendForgotPassword()
.then(() => {
$('#modal').trigger('opensuccess', [
{
title: 'Forgot Password',
text:
'We sent an email to ' +
self.state.emailAddress +
'. Follow the instructions to create a new password.',
},
])
})
.catch(({errors}) => {
const error = errors?.[0]
? errors[0].message
: 'There was a problem saving the data, please try again later or contact support.'
self.setState({
generalError: error,
requestRunning: false,
})
}),
)
}
sendForgotPassword() {
return forgotPassword(this.state.emailAddress, window.location.href)
}
checkRedeemProject() {
checkRedeemProjectApi()
if (this.props.redeemMessage) {
return checkRedeemProjectApi()
} else {
return Promise.resolve()
}
}
errorFor(field) {
return this.state.validationErrors[field]
}
render() {
var generalErrorHtml = ''
if (this.state.generalError.length) {
generalErrorHtml = (
<div>
<span style={{color: 'red', fontSize: '14px'}} className="text">
{this.state.generalError}
</span>
<br />
</div>
)
}
var loaderClass = this.state.requestRunning ? 'show' : ''
return (
<div className="forgot-password-modal">
<p>
Enter the email address associated with your account and we'll
send you the link to reset your password.
</p>
<TextField
showError={this.state.showErrors}
onFieldChanged={this.handleFieldChanged('emailAddress')}
placeholder="Email"
name="emailAddress"
errorText={this.errorFor('emailAddress')}
tabindex={1}
onKeyPress={(e) => {
e.key === 'Enter' ? this.handleSubmitClicked() : null
}}
/>
<a
className="send-password-button btn-confirm-medium"
onKeyPress={(e) => {
e.key === 'Enter' ? this.handleSubmitClicked() : null
}}
onClick={this.handleSubmitClicked.bind()}
tabIndex={2}
>
<span className={'button-loader ' + loaderClass} /> Send{' '}
</a>
{generalErrorHtml}
<br />
<span className="forgot-password" onClick={this.openLoginModal}>
Back to login
</span>
</div>
)
}
}
const fieldValidations = [
RuleRunner.ruleRunner(
'emailAddress',
'Email address',
FormRules.requiredRule,
FormRules.checkEmail,
),
]
export default ForgotPasswordModal
|
client/components/ui/multi-state-modal.js | jankeromnes/kresus | import React from 'react';
import PropTypes from 'prop-types';
import { assertHas } from '../../helpers';
import Modal from './modal';
class MultiStateModal extends React.Component {
constructor(props) {
super(props);
this.state = {
view: props.initialView
};
this.switchView = this.switchView.bind(this);
}
switchView(view) {
this.setState({
view
});
}
render() {
assertHas(this.props.views, this.state.view, 'initial view must be known');
let modal = this.props.views[this.state.view](this.switchView);
let { modalTitle, modalBody, modalFooter } = modal;
return (<Modal
modalId={ this.props.modalId }
modalBody={ modalBody }
modalTitle={ modalTitle }
modalFooter={ modalFooter }
/>);
}
}
MultiStateModal.propTypes = {
// The initial view to show to the user. Must be in the views descriptor below.
initialView: PropTypes.string.isRequired,
// An plain old object mapping viewName => { modalBody, modalTitle, modalFooter } factories.
// Each factory will be passed the switchView function, to easily switch from one view to
// the other.
views: PropTypes.object.isRequired,
// CSS unique id.
modalId: PropTypes.string.isRequired,
};
export default MultiStateModal;
|
src/components/prototype/Record.js | arayi/SLions | /**
* Practice Scene
*/
import React from 'react';
import PropTypes from 'prop-types';
import { View, Button, Alert } from 'react-native';
import { Actions } from 'react-native-router-flux';
// Consts and Libs
import { AppStyles } from '@theme/';
import { DefaultSongs } from '@constants/';
import Sound from 'react-native-sound';
// Components
import { Text } from '@ui/';
Sound.setCategory('Playback');
const english = new Sound(require('./english.mp3'), (error) => {
if (error) {
Alert(JSON.stringify(error));
}
});
const chinese = new Sound(require('./chinese.mp3'), (error) => {
if (error) {
Alert(JSON.stringify(error));
}
});
const playSong = (path) => {
const song = path === 'english' ? english : chinese;
song.play();
};
/* Component ==================================================================== */
const Record = ({ songArray }) => {
const song = songArray[0];
return (
<View style={[AppStyles.container, AppStyles.containerCentered]}>
<Text h1>Record!</Text>
<Button
onPress={() => playSong(song.path)}
key={song.language}
color="#20aa25"
title={`${song.name} (${song.language})`}
/>
{song.body.map((line, index) => {
const currentLine = `line-${index}`;
return (<Text key={currentLine}>{line.toString()}</Text>);
})}
<Button
onPress={() => Actions.feedback()}
key="record"
color="#bb2520"
title="Start recording..."
/>
</View>
);
};
Record.propTypes = {
songArray: PropTypes.arrayOf(PropTypes.shape({
language: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
body: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.string))).isRequired,
})),
};
Record.defaultProps = {
songArray: DefaultSongs,
};
Record.componentName = 'Record';
/* Export Component ==================================================================== */
export default Record;
|
src/spares/paragraph/Paragraph.js | korchemkin/spares-uikit | /**
*
* Spares-uikit
*
* @author Dmitri Korchemkin
* @source https://github.com/korchemkin/spares-uikit
*/
import React, { Component } from 'react';
import './Paragraph.css';
class Paragraph extends Component {
render() {
return (
<p className="spares-paragraph">{this.props.children}</p>
);
}
}
export default Paragraph;
|
web/src/js/utils.js | StevenVanAcker/mitmproxy | import _ from 'lodash'
import React from 'react'
window._ = _;
window.React = React;
export var Key = {
UP: 38,
DOWN: 40,
PAGE_UP: 33,
PAGE_DOWN: 34,
HOME: 36,
END: 35,
LEFT: 37,
RIGHT: 39,
ENTER: 13,
ESC: 27,
TAB: 9,
SPACE: 32,
BACKSPACE: 8,
SHIFT: 16
};
// Add A-Z
for (var i = 65; i <= 90; i++) {
Key[String.fromCharCode(i)] = i;
}
export var formatSize = function (bytes) {
if (bytes === 0)
return "0";
var prefix = ["b", "kb", "mb", "gb", "tb"];
for (var i = 0; i < prefix.length; i++) {
if (Math.pow(1024, i + 1) > bytes) {
break;
}
}
var precision;
if (bytes % Math.pow(1024, i) === 0)
precision = 0;
else
precision = 1;
return (bytes / Math.pow(1024, i)).toFixed(precision) + prefix[i];
};
export var formatTimeDelta = function (milliseconds) {
var time = milliseconds;
var prefix = ["ms", "s", "min", "h"];
var div = [1000, 60, 60];
var i = 0;
while (Math.abs(time) >= div[i] && i < div.length) {
time = time / div[i];
i++;
}
return Math.round(time) + prefix[i];
};
export var formatTimeStamp = function (seconds) {
var ts = (new Date(seconds * 1000)).toISOString();
return ts.replace("T", " ").replace("Z", "");
};
// At some places, we need to sort strings alphabetically descending,
// but we can only provide a key function.
// This beauty "reverses" a JS string.
var end = String.fromCharCode(0xffff);
export function reverseString(s) {
return String.fromCharCode.apply(String,
_.map(s.split(""), function (c) {
return 0xffff - c.charCodeAt(0);
})
) + end;
}
function getCookie(name) {
var r = document.cookie.match(new RegExp("\\b" + name + "=([^;]*)\\b"));
return r ? r[1] : undefined;
}
const xsrf = `_xsrf=${getCookie("_xsrf")}`;
export function fetchApi(url, options={}) {
if (options.method && options.method !== "GET") {
if (url.indexOf("?") === -1) {
url += "?" + xsrf;
} else {
url += "&" + xsrf;
}
} else {
url += '.json'
}
if (url.startsWith("/")) {
url = "." + url;
}
return fetch(url, {
credentials: 'same-origin',
...options
});
}
fetchApi.put = (url, json, options) => fetchApi(
url,
{
method: "PUT",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(json),
...options
}
)
// deep comparison of two json objects (dicts). arrays are handeled as a single value.
// return: json object including only the changed keys value pairs.
export function getDiff(obj1, obj2) {
let result = {...obj2};
for(let key in obj1) {
if(_.isEqual(obj2[key], obj1[key]))
result[key] = undefined
else if(Object.prototype.toString.call(obj2[key]) === '[object Object]' &&
Object.prototype.toString.call(obj1[key]) === '[object Object]' )
result[key] = getDiff(obj1[key], obj2[key])
}
return result
}
export const pure = renderFn => class extends React.PureComponent {
static displayName = renderFn.name
render() {
return renderFn(this.props)
}
}
|
app/containers/NotFoundPage/index.js | xavierouicar/react-boilerplate | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
frontend/component/Footer.js | laayoune/whoquan | import React from 'react';
const footerStyle ={
marginTop:50,
padding:20
};
export default class Footer extends React.Component {
render(){
return(
<div className="text-center" style={footerStyle}>
© CopyRight Node.js实战
</div>
)
}
} |
src/components/App.js | Montana-Code-School/LifeCoach | import React from 'react';
import Navigation from './Navigation';
class App extends React.Component{
constructor() {
super();
}
render() {
return(
<div>
<Navigation/>
{this.props.children}
</div>
);
}
}
export default App;
|
app/Meneame.js | alvaromb/mnm | import React from 'react'
import { StyleSheet, Image, Text, Dimensions } from 'react-native'
import MaterialIcons from 'react-native-vector-icons/MaterialIcons'
import Ionicon from 'react-native-vector-icons/Ionicons'
import { Menu } from 'react-native-section-menu'
import {
MnmSectionPortada,
MnmSectionNuevas,
MnmSectionPopulares,
MnmSectionMasVisitadas,
MnmSectionDestacadas,
} from './MnmSections'
const MnmAndroidHeader = (props) =>
<Image source={require('./img/header.png')} style={styles.headerContainer} resizeMode="cover">
<Text style={styles.headerText}>Menéame</Text>
<Text style={styles.versionText}>Versión 1.0</Text>
</Image>
const styles = StyleSheet.create({
headerContainer: {
flexDirection: 'column',
justifyContent: 'flex-end',
alignItems: 'flex-start',
width: Dimensions.get('window').width - 56,
height: ((Dimensions.get('window').width - 56) * 9) / 16,
backgroundColor: 'coral',
},
headerText: {
color: 'white',
fontSize: 24,
marginLeft: 14,
marginBottom: 4,
},
versionText : {
color: 'white',
fontSize: 14,
marginLeft: 14,
marginBottom: 8,
}
})
class Meneame extends React.Component {
render () {
const androidIconSize = 18
const iOSiconSize = 30
let itemId = 0
const header = <MnmAndroidHeader />
return (
<Menu barTintColor="black" tintColor="#d35400" initialEntry={0}
header={header}
entries={[
{
id: itemId++,
title: 'Portada',
element: <MnmSectionPortada />,
androidIcon: <MaterialIcons name="description" size={androidIconSize} />,
itemComponent: Ionicon.TabBarItem,
iconName: 'ios-paper-outline',
selectedIconName: 'ios-paper',
iconSize: iOSiconSize,
},
{
id: itemId++,
title: 'Nuevas',
element: <MnmSectionNuevas />,
androidIcon: <MaterialIcons name="access-time" size={androidIconSize} />,
itemComponent: Ionicon.TabBarItem,
iconName: 'ios-time-outline',
selectedIconName: 'ios-time',
iconSize: iOSiconSize,
},
{
id: itemId++,
title: 'Populares',
element: <MnmSectionPopulares />,
androidIcon: <MaterialIcons name="favorite" size={androidIconSize} />,
itemComponent: Ionicon.TabBarItem,
iconName: 'ios-heart-outline',
selectedIconName: 'ios-heart',
iconSize: iOSiconSize,
},
{
id: itemId++,
title: 'Más visitadas',
element: <MnmSectionMasVisitadas />,
androidIcon: <MaterialIcons name="whatshot" size={androidIconSize} />,
itemComponent: Ionicon.TabBarItem,
iconName: 'ios-flame-outline',
selectedIconName: 'ios-flame',
iconSize: iOSiconSize,
},
{
id: itemId++,
title: 'Destacadas',
element: <MnmSectionDestacadas />,
androidIcon: <MaterialIcons name="grade" size={androidIconSize} />,
itemComponent: Ionicon.TabBarItem,
iconName: 'ios-star-outline',
selectedIconName: 'ios-star',
iconSize: iOSiconSize,
},
]}
/>
)
}
}
export default Meneame
|
src/components/Counter/Counter.js | cargo-transport/web-frontend | import React from 'react';
import classes from './Counter.scss';
export const Counter = (props) => (
<div>
<h2 className={classes.counterContainer}>
Counter:
{' '}
<span className={classes['counter--green']}>
{props.counter}
</span>
</h2>
<button className="btn btn-default" onClick={props.increment}>
Increment
</button>
{' '}
<button className="btn btn-default" onClick={props.doubleAsync}>
Double (Async)
</button>
</div>
);
Counter.propTypes = {
counter: React.PropTypes.number.isRequired,
doubleAsync: React.PropTypes.func.isRequired,
increment: React.PropTypes.func.isRequired
};
export default Counter;
|
modules/Router.js | mjw56/react-router | import React from 'react'
import warning from 'warning'
import createHashHistory from 'history/lib/createHashHistory'
import { createRoutes } from './RouteUtils'
import RoutingContext from './RoutingContext'
import useRoutes from './useRoutes'
import { routes } from './PropTypes'
const { func, object } = React.PropTypes
/**
* A <Router> is a high-level API for automatically setting up
* a router that renders a <RoutingContext> with all the props
* it needs each time the URL changes.
*/
const Router = React.createClass({
propTypes: {
history: object,
children: routes,
routes, // alias for children
createElement: func,
onError: func,
onUpdate: func,
parseQueryString: func,
stringifyQuery: func
},
getInitialState() {
return {
location: null,
routes: null,
params: null,
components: null
}
},
handleError(error) {
if (this.props.onError) {
this.props.onError.call(this, error)
} else {
// Throw errors by default so we don't silently swallow them!
throw error // This error probably occurred in getChildRoutes or getComponents.
}
},
componentWillMount() {
let { history, children, routes, parseQueryString, stringifyQuery } = this.props
let createHistory = history ? () => history : createHashHistory
this.history = useRoutes(createHistory)({
routes: createRoutes(routes || children),
parseQueryString,
stringifyQuery
})
this._unlisten = this.history.listen((error, state) => {
if (error) {
this.handleError(error)
} else {
this.setState(state, this.props.onUpdate)
}
})
},
componentWillReceiveProps(nextProps) {
warning(
nextProps.history === this.props.history,
"The `history` provided to <Router/> has changed, it will be ignored."
)
},
componentWillUnmount() {
if (this._unlisten)
this._unlisten()
},
render() {
let { location, routes, params, components } = this.state
let { createElement } = this.props
if (location == null)
return null // Async match
return React.createElement(RoutingContext, {
history: this.history,
createElement,
location,
routes,
params,
components
})
}
})
export default Router
|
src/components/GroupList.js | wookiecookie87/lunch_group_creator_with_reactjs | import React from 'react'
class GroupList extends React.Component{
constructor(props, context) {
super(props, context);
}
render () {
let groupList = this.props.groupMembers.map((member) => (
<li key={member.name} className="list-group-item">{member.name}</li>
));
return (
<ul className="list-group list-group-flush">
{groupList}
</ul>
)
}
}
export default GroupList; |
src/svg-icons/device/battery-alert.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBatteryAlert = (props) => (
<SvgIcon {...props}>
<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM13 18h-2v-2h2v2zm0-4h-2V9h2v5z"/>
</SvgIcon>
);
DeviceBatteryAlert = pure(DeviceBatteryAlert);
DeviceBatteryAlert.displayName = 'DeviceBatteryAlert';
DeviceBatteryAlert.muiName = 'SvgIcon';
export default DeviceBatteryAlert;
|
src/components/portfolio-contact.js | relwiwa/fcc-portfolio-page | import React from 'react';
import '../styles/portfolio-contact.scss';
const PortfolioContact = (props) => {
const { contactData } = props;
const renderContactItem = (item) => {
const { description, image, title, url } = item;
return(
<div
className="column column-block text-center"
key={title}
>
<a href={url} title={description}>
<img src={image.url} alt={description} />
</a>
</div>
);
};
return (
<div className="portfolio-contact row" id="portfolio-contact">
<div className="column callout small-12">
<h1 >Contact <small>relwiwa</small></h1>
<p>I'm looking forward to getting in touch with you on one of the following sites:</p>
<div className="row small-up-3 medium-up-6">
{contactData.map((item) => renderContactItem(item))}
</div>
</div>
</div>
);
}
export default PortfolioContact;
|
lib/components/App.js | dpkshrma/beaver | 'use babel';
import React from 'react';
import { Collapse } from 'react-collapse';
import TodoFormContainer from './TodoForm';
import TodoListContainer from './TodoList';
import { TodoService } from '../services';
const TODO_FORM = 'todoForm';
const TODO_LIST = 'todoList';
const TopBar = ({ children, toggleTopMenu, selectedPage }) => (
<atom-panel className="padded">
<div className="panel-heading top-menu-button">
<i className="icon icon-three-bars" onClick={toggleTopMenu} />
{selectedPage === TODO_FORM ? 'Add a todo' : null}
{selectedPage === TODO_LIST ? 'Todo List' : null}
</div>
{children}
</atom-panel>
);
const TopMenu = ({ topMenuVisible, onTopMenuItemClick }) => (
<div className="panel-body top-menu">
<Collapse isOpened={topMenuVisible}>
<div
className="top-menu-item"
onClick={onTopMenuItemClick}
data-page="todoForm"
>
Add a todo
</div>
<div
className="top-menu-item"
onClick={onTopMenuItemClick}
data-page="todoList"
>
Todo List
</div>
</Collapse>
</div>
);
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedPage: TODO_LIST,
topMenuVisible: false,
activeTodo: null
};
}
toggleTopMenu = () => {
this.setState({ topMenuVisible: !this.state.topMenuVisible });
};
onTopMenuItemClick = e => {
this.setState({
selectedPage: e.target.getAttribute('data-page'),
topMenuVisible: false,
activeTodo: null
});
};
editTodo = todoId => {
TodoService.getTodo(todoId).then(todo => {
if (todo) {
this.setState({
selectedPage: TODO_FORM,
activeTodo: todo
});
}
});
};
render() {
const { selectedPage } = this.state;
return (
<div id={this.props.id}>
<TopBar selectedPage={selectedPage} toggleTopMenu={this.toggleTopMenu}>
<TopMenu
topMenuVisible={this.state.topMenuVisible}
onTopMenuItemClick={this.onTopMenuItemClick}
/>
</TopBar>
{selectedPage === TODO_FORM && (
<TodoFormContainer todo={this.state.activeTodo} />
)}
{selectedPage === TODO_LIST && (
<TodoListContainer editTodo={this.editTodo} />
)}
</div>
);
}
}
export default App;
|
src/components/counter.js | pingf/BSIDK | import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import Button from './button'
// React component
class Counter extends React.Component {
render(){
const { value, onIncreaseClick, click } = this.props;
return (
<div>
<div>
<span>{value}</span>
<Button onClick={onIncreaseClick}>click me to increase 1</Button>
</div>
<div>
<Button onClick={this.test}>点我输出</Button>
</div>
</div>
);
}
test(){
console.log('hahahaha');
}
}
// Action:
const increaseAction = {type: 'increase'};
// Reducer:
function counter(state={count: 0}, action) {
let count = state.count;
switch(action.type){
case 'increase':
return {count: count+1};
default:
return state;
}
}
// Store:
let store = createStore(counter);
// Map Redux state to component props
function mapStateToProps(state) {
return {
value: state.count
};
}
// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction),
};
}
// Connected Component:
let App = connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
|
client/components/dashboard/SurveyTemplates.js | AnatolyBelobrovik/itechartlabs | import React from 'react';
import { connect } from 'react-redux';
import MenuPage from '../shared/MenuPage';
import TemplatesGrid from '../shared/templates/TemplatesGrid';
import SearchBar from '../shared/SearchBar';
import NoData from '../shared/NoData';
import Loader from 'react-loader';
import { getTemplatesRequest, deleteTemplateRequest } from '../../actions/dashboardActions';
import { addFlashMessage } from '../../actions/flashMessagesActions';
import PropTypes from 'prop-types';
class SurveyTemplates extends React.Component {
constructor() {
super();
this.state = {
items: [],
term: '',
isLoaded: false
};
this.onCreateNewTemplate = this.onCreateNewTemplate.bind(this);
this.filterData = this.filterData.bind(this);
}
componentDidMount() {
this.populateData();
}
componentWillReceiveProps(nextProps) {
this.setState({
items: nextProps.templates
});
}
populateData() {
this.props.getTemplatesRequest()
.then(() => {
this.initialData = this.props.templates;
this.setState({
items: this.initialData,
isLoaded: true
});
})
.catch(err => {
this.props.addFlashMessage({
type: 'warning',
text: `${err.response.data.error}`
});
});
}
filterData(config) {
this.setState({ items: config.data, term: config.term });
}
onCreateNewTemplate() {
this.context.router.history.push('/new', true);
}
render() {
const { term, items, isLoaded } = this.state;
const { addFlashMessage, deleteTemplateRequest } = this.props;
return (
<div className="container-fluid">
<div className="row">
<aside className="col-md-3">
<MenuPage />
</aside>
<section className="col-md-9">
<div className="panel panel-default">
<div className="panel-heading grey">
<h3 className="panel-title">Survey Templates</h3>
</div>
<div className="panel-body">
<div className="row">
<div className="col-md-4">
<button
onClick={this.onCreateNewTemplate}
className="btn btn-success btn-sm"
>
Create New Template
</button>
</div>
<div className="col-md-4 col-md-offset-4">
<SearchBar
userSearch={false}
term={term}
data={this.initialData}
update={this.filterData}
/>
</div>
</div>
<br />
<Loader color="#a9a9a9" loaded={isLoaded}>
{items.length === 0 && <NoData />}
<TemplatesGrid
dataSet={items}
deleteTemplateRequest={deleteTemplateRequest}
addFlashMessage={addFlashMessage}
/>
</Loader>
</div>
</div>
</section>
</div>
</div>
);
}
}
SurveyTemplates.propTypes = {
templates: PropTypes.array,
getTemplatesRequest: PropTypes.func.isRequired,
deleteTemplateRequest: PropTypes.func.isRequired,
addFlashMessage: PropTypes.func.isRequired
};
SurveyTemplates.contextTypes = {
router: PropTypes.object.isRequired
};
function mapStateToProps(state) {
return {
templates: state.templates.templates
};
}
export default connect(mapStateToProps, { getTemplatesRequest, addFlashMessage, deleteTemplateRequest })(SurveyTemplates);
|
pyxis/components/Grid/index.js | gtkatakura/furb-desenvolvimento-plataformas-moveis | import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import Components from './../../components';
const styles = new StyleSheet.create({
grid: {
margin: 20
},
header: {
},
header_text: {
fontSize: 32
},
header_actions: {
// flexWrap: 'wrap',
flexDirection: 'row'
},
content: {},
item: {
flexDirection: 'row',
marginTop: 15,
padding: 8
},
identifier: {
marginRight: 24
},
identifier_text: {
fontSize: 18
},
name_text: {
fontSize: 18
}
});
class Grid extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.grid}>
<View style={styles.header}>
<Text style={styles.header_text}>{this.props.title}</Text>
<View style={styles.header_actions}>
{
this.props.buttons.map(button => <Button title={button.title} onPress={() => button.action()}></Button>)
}
</View>
</View>
<View style={styles.content}>
{
(this.props.data || []).map(item => {
return (
<View key={item.id} style={styles.item}>
<View style={styles.identifier}><Text style={styles.identifier_text}>{item.id}</Text></View>
<View style={styles.name}><Text style={styles.name_text}>{item.name}</Text></View>
</View>
)
})
}
</View>
</View>
);
}
}
export default Grid; |
src/components/exercises/build-sentence-video.component.js | serlo-org/serlo-abc | import React from 'react';
import { View, Dimensions } from 'react-native';
import { PRIMARY } from '../../styles/colors';
import Video from '../common/Video';
import { PortraitScreenOrientation } from '../helpers/screen-orientation';
import { BuildSentence } from './build-sentence.component';
export const BuildSentenceVideo = props => {
const { height } = Dimensions.get('window');
return (
<PortraitScreenOrientation>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
backgroundColor: PRIMARY
}}
>
<View
style={{
height: height / 3,
width: '100%'
}}
>
<Video video={props.video} />
</View>
<View
style={{
position: 'absolute',
top: height / 3,
height: (height * 2) / 3,
width: '100%'
}}
>
<BuildSentence
sentence={props.sentence}
changeAnswer={state => {
console.warn(state);
}}
/>
</View>
</View>
</PortraitScreenOrientation>
);
};
|
packages/mineral-ui-icons/src/IconEventSeat.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconEventSeat(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M4 18v3h3v-3h10v3h3v-6H4zm15-8h3v3h-3zM2 10h3v3H2zm15 3H7V5c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2v8z"/>
</g>
</Icon>
);
}
IconEventSeat.displayName = 'IconEventSeat';
IconEventSeat.category = 'action';
|
ui/src/components/role-policy/AddAssertionForRole.js | yahoo/athenz | /*
* Copyright 2020 Verizon Media
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import styled from '@emotion/styled';
import AddRuleFormForRole from './AddRuleFormForRole';
import Button from '../denali/Button';
import { colors } from '../denali/styles';
import Color from '../denali/Color';
import RequestUtils from '../utils/RequestUtils';
const StyledDiv = styled.div`
background-color: ${colors.white};
`;
const ModifiedButton = styled(Button)`
min-width: 8.5em;
min-height: 1em;
`;
const ButtonDiv = styled.div`
margin-left: 155px;
`;
const ErrorDiv = styled.div`
margin-left: 155px;
`;
export default class AddAssertionForRole extends React.Component {
constructor(props) {
super(props);
this.api = this.props.api;
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {};
}
onChange(key, value) {
this.setState({ [key]: value });
}
onSubmit() {
if (!this.state.action || this.state.action === '') {
this.setState({
errorMessage: 'Rule action is required.',
});
return;
}
if (!this.state.resource || this.state.resource === '') {
this.setState({
errorMessage: 'Rule resource is required.',
});
return;
}
this.api
.addAssertion(
this.props.domain,
this.props.name,
this.props.role,
this.state.resource,
this.state.action,
this.state.effect,
this.props._csrf
)
.then((data) => {
this.props.submit(
`Successfully created assertion for policy ${this.props.name}`
);
})
.catch((err) => {
this.setState({
errorMessage: RequestUtils.xhrErrorCheckHelper(err),
});
});
}
render() {
return (
<StyledDiv data-testid='add-assertion-for-role'>
<AddRuleFormForRole
id={this.props.id}
api={this.api}
onChange={this.onChange}
domain={this.props.domain}
/>
{this.state.errorMessage && (
<ErrorDiv>
<Color name={'red600'}>{this.state.errorMessage}</Color>
</ErrorDiv>
)}
<ButtonDiv>
<ModifiedButton onClick={this.onSubmit}>
Submit
</ModifiedButton>
<ModifiedButton secondary onClick={this.props.cancel}>
Cancel
</ModifiedButton>
</ButtonDiv>
</StyledDiv>
);
}
}
|
components/AppBar.js | nodegin/react-native-redux-routing | import React from 'react'
import {
StyleSheet,
Text,
View,
Dimensions,
TouchableHighlight,
Platform,
WebView,
} from 'react-native'
import { types } from '../actions'
const windowSize = Dimensions.get('window')
const appBarIconSize = 24
export default class extends React.Component {
_class() {
return 'AppBar'
}
handleMenuPress = () => {
if (this.props.router.transitioning) {
return
}
setTimeout(() => {
if (this.props.router.routes.length > 1) {
this.props.actions._navigate(-1)
} else {
this.props.actions._openDrawer()
}
}, 150)
}
handleNavActionPress = () => setTimeout(this.props.router.navActionHandler, 150)
render() {
const { router } = this.props
const menuIcon = 'M19,10H5V8H19V10M19,16H5V14H19V16Z'
const backIcon = 'M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z'
let pathData
if (router.action === types.ROUTE_PUSH) {
pathData = !router.transitioning && router.routes.length > 1 ? backIcon : router.routes.length > 2 ? backIcon : menuIcon
} else if (router.action === types.ROUTE_POP) {
pathData = !router.transitioning && router.routes.length < 2 ? menuIcon : backIcon
} else if (router.action === types.ROUTE_REPLACE) {
pathData = router.routes.length > 1 ? backIcon : menuIcon
} else {
pathData = menuIcon
}
const contrastColor = this.props.config.statusBarStyle === 'default' ? '#000' : '#fff'
return (
<View style={styles.appBarContainer}>
<View style={{
backgroundColor: this.props.config.accentColor,
height: this.props.config.statusBarSize,
}} />
<View style={[styles.appBar, {
backgroundColor: this.props.config.accentColor,
height: router.appBarSize,
}]}>
<View style={[styles.appBarTitle, { height: router.appBarSize }]}>
<Text style={[styles.appBarTitleText, { color: contrastColor }]}>{ router.navTitle }</Text>
</View>
<View style={styles.appBarMenuIconWrapper}>
<View style={styles.appBarMenuIcon}>
<WebView
source={{
html:
`
<style>body{background:${this.props.config.accentColor};margin:0}</style>
<body><svg style="width:${appBarIconSize}px;height:${appBarIconSize}px" viewBox="0 0 24 24">
<path fill="${contrastColor}" d="${pathData}"/></svg></body>
`
}}
scrollEnabled={false} />
</View>
<TouchableHighlight
style={[styles.appBarMenuIconHighlight, styles.appBarMenuIconWrapper]}
underlayColor="rgba(255,255,255,.25)"
onPress={this.handleMenuPress}>
<View />
</TouchableHighlight>
</View>
<View style={styles.appBarFillBlank} />
{
!router.navActionRenderer ? null :
<TouchableHighlight
style={styles.appBarIconWrapper}
underlayColor="rgba(255,255,255,.25)"
onPress={this.handleNavActionPress}>
{router.navActionRenderer()}
</TouchableHighlight>
}
</View>
</View>
)
}
}
const styles = StyleSheet.create({
appBar: {
alignItems: 'center',
flexDirection: 'row',
paddingLeft: 8,
paddingRight: 8,
},
appBarMenuIconWrapper: {
alignItems: 'center',
height: 32,
justifyContent: 'center',
width: 32,
},
appBarMenuIcon: {
height: appBarIconSize,
width: appBarIconSize,
},
appBarMenuIconHighlight: {
borderRadius: 2,
left: 0,
position: 'absolute',
top: 0,
},
appBarIconWrapper: {
alignItems: 'center',
borderRadius: 2,
height: 32,
justifyContent: 'center',
paddingLeft: 4,
paddingRight: 4,
},
appBarTitle: {
alignItems: 'center',
justifyContent: 'center',
left: 0,
position: 'absolute',
width: windowSize.width
},
appBarTitleText: {
fontSize: 18,
fontWeight: 'bold',
},
appBarFillBlank: {
flex: 1,
},
})
|
app/jsx/shared/SVGWrapper.js | venturehive/canvas-lms | /*
* Copyright (C) 2015 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import $ from 'jquery'
const DOCUMENT_NODE = 9;
const ELEMENT_NODE = 1;
class SVGWrapper extends React.Component {
static propTypes = {
url: PropTypes.string.isRequired,
fillColor: PropTypes.string
}
componentDidMount () {
this.fetchSVG();
}
componentWillReceiveProps (newProps) {
if (newProps.url !== this.props.url) {
this.fetchSVG();
}
}
fetchSVG () {
$.ajax(this.props.url, {
success: function (data) {
this.svg = data;
if (data.nodeType === DOCUMENT_NODE) {
this.svg = data.firstChild;
}
if (this.svg.nodeType !== ELEMENT_NODE && this.svg.nodeName !== 'SVG') {
throw new Error(`SVGWrapper: SVG Element must be returned by request to ${this.props.url}`);
}
if (this.props.fillColor) {
this.svg.setAttribute('style', `fill:${this.props.fillColor}`);
}
this.svg.setAttribute('focusable', false);
this.rootSpan.appendChild(this.svg);
}.bind(this)
});
}
render () {
return <span ref={(c) => { this.rootSpan = c; }} />;
}
}
export default SVGWrapper
|
pages/work/index.js | gregcorby/gregcorby.com | import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
export default class Sass extends React.Component {
render () {
return (
<div className="page-container" id="content-container">
<div className="work-container">
<h2 className="work-header">Some things I've<br />put together.</h2>
<div id="opentable" className="project">
<div className="project-images">
<img src="/images/ot-image.jpg" />
</div>
<div className="project-details">
<h2 className="title-name">Opentable <span>—<br /> Misc Projects</span></h2>
<a href="http://www.opentable.com" target="_blank">Learn More →</a>
</div>
</div>
<div id="creativemarket" className="project">
<div className="project-images">
<img src="/images/cm-image.jpg" />
</div>
<div className="project-details">
<h2 className="title-name">Creative Market <span>—<br /> Misc Projects</span></h2>
<a href="http://www.creativemarket.com" target="_blank">Learn More →</a>
</div>
</div>
<div id="detour" className="project">
<div className="project-images">
<img src="/images/detour-image.jpg" />
</div>
<div className="project-details">
<h2 className="title-name">Detour <span>—<br /> Misc Brochures & Guides</span></h2>
<a href="http://www.detour.com" target="_blank">Learn More →</a>
</div>
</div>
<div id="landscape" className="project">
<div className="project-images">
<img src="/images/landscape-image.jpg" />
</div>
<div className="project-details">
<h2 className="title-name">Landscape <span>—<br /> Web App</span></h2>
</div>
</div>
<div id="sneakz" className="project">
<div className="project-images">
<img src="/images/sneakz-image.jpg" />
</div>
<div className="project-details">
<h2 className="title-name">Sneakz <span>—<br /> Design & Development</span></h2>
<a href="http://www.sneakz.com" target="_blank">Learn More →</a>
</div>
</div>
<div id="strongboalt" className="project">
<div className="project-images">
<img src="/images/strongboalt-image.jpg" />
</div>
<div className="project-details">
<h2 className="title-name">Strongboalt <span>—<br /> Design & Development</span></h2>
<a href="http://www.strongboalt.com" target="_blank">Learn More →</a>
</div>
</div>
<div id="outsite" className="project">
<div className="project-images">
<img src="/images/outsite-image.jpg" />
</div>
<div className="project-details">
<h2 className="title-name">Outsite <span>—<br /> Mobile Booking App</span></h2>
<a href="http://www.outsite.co" target="_blank">Learn More →</a>
</div>
</div>
</div>
</div>
)
}
componentDidMount(){
var container = document.getElementById('content-container');
document.body.classList.add('work-page');
setTimeout(function() {
container.classList.add('loaded');
document.body.classList.add('loaded');
}, 300);
setTimeout(function() {
document.body.classList.add('load-img');
}, 800);
}
componentWillUnmount() {
var container = document.getElementById('content-container');
container.classList.remove('loaded');
document.body.classList.remove('loaded');
document.body.classList.remove('work-page');
document.body.classList.remove('load-img');
}
}
|
src/universal/components/About.js | jcoreio/crater | // @flow
import React from 'react'
import {Link} from 'react-router'
const About = (): React.Element<any> => (
<div>
<h1>About</h1>
<p>
This is an app skeleton that uses Meteor, Webpack, and React.
</p>
<p>
Unlike a traditional Meteor app, it allows you to avoid building any of your app code with
Meteor's isobuild, which in my experience has been slow and even hangs on large Webpack bundles.
It also uses react-hot-loader and Webpack hot reloading, allowing you to iterate much faster
than possible with Meteor's dev tools.
</p>
<Link to="/">Home</Link>
</div>
)
export default About
|
src/components/UpdateItemTray/index.js | instructure/canvas-planner | /*
* Copyright (C) 2017 - 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 they 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, { Component } from 'react';
import _ from 'lodash';
import themeable from '@instructure/ui-themeable/lib';
import Container from '@instructure/ui-core/lib/components/Container';
import FormFieldGroup from '@instructure/ui-core/lib/components/FormFieldGroup';
import ScreenReaderContent from '@instructure/ui-core/lib/components/ScreenReaderContent';
import Button from '@instructure/ui-core/lib/components/Button';
import formatMessage from '../../format-message';
import PropTypes from 'prop-types';
import TextInput from '@instructure/ui-core/lib/components/TextInput';
import Select from '@instructure/ui-core/lib/components/Select';
import TextArea from '@instructure/ui-core/lib/components/TextArea';
import DateInput from '@instructure/ui-core/lib/components/DateInput';
import moment from 'moment-timezone';
import styles from './styles.css';
import theme from './theme.js';
export class UpdateItemTray extends Component {
static propTypes = {
courses: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
longName: PropTypes.string,
})).isRequired,
noteItem: PropTypes.object,
onSavePlannerItem: PropTypes.func.isRequired,
onDeletePlannerItem: PropTypes.func.isRequired,
locale: PropTypes.string.isRequired,
timeZone: PropTypes.string.isRequired,
};
constructor (props) {
super(props);
const updates = this.getNoteUpdates(props);
if (!updates.date) {
updates.date = props.noteItem && props.noteItem.date ? props.noteItem.date : moment.tz(props.timeZone).format();
}
this.state = {
updates,
titleMessages: [],
dateMessages: [],
};
}
componentWillReceiveProps (nextProps) {
const updates = this.getNoteUpdates(nextProps);
this.setState({updates}, this.updateMessages);
}
getNoteUpdates (props) {
const updates = _.cloneDeep(props.noteItem) || {};
if (updates.context) {
updates.courseId = updates.context.id;
delete updates.context;
}
return updates;
}
updateMessages = () => {
if (!this.state.updates.date) {
this.setState({dateMessages: [{type: 'error', text: formatMessage('Date is required')}]});
} else {
this.setState({dateMessages: []});
}
}
handleSave = () => {
const updates = Object.assign({}, this.state.updates);
if (updates.courseId) {
updates.context = { id: updates.courseId };
} else {
updates.context = { id: null };
}
delete updates.courseId;
this.props.onSavePlannerItem(updates);
}
handleChange = (field, value) => {
this.setState({
updates: {
...this.state.updates,
[field]: value
}
}, this.updateMessages);
}
handleCourseIdChange = (e) => {
let value = e.target.value;
if (value === 'none') value = undefined;
this.handleChange('courseId', value);
}
handleTitleChange = (e) => {
const value = e.target.value;
if (value === '') {
this.setState({
titleMessages: [{type: 'error', text: formatMessage('title is required')}]
});
} else {
this.setState({titleMessages: []});
}
this.handleChange('title', value);
}
handleDateChange = (e, date) => {
const value = date ? moment(date).format() : ''; // works if date is a moment obj (instui 3) or iso string (instui 4)
this.handleChange('date', value);
}
handleDeleteClick = () => {
// eslint-disable-next-line no-restricted-globals
if (confirm(formatMessage('Are you sure you want to delete this planner item?'))) {
this.props.onDeletePlannerItem(this.props.noteItem);
}
}
findCurrentValue (field) {
return this.state.updates[field] || '';
}
isValid () {
if (this.state.updates.title && this.state.updates.date) {
return this.state.updates.title.replace(/\s/g, '').length > 0;
}
return false;
}
renderDeleteButton () {
if (this.props.noteItem == null) return;
return <Button
variant="light"
margin="0 x-small 0 0"
onClick={this.handleDeleteClick}>
{formatMessage("Delete")}
</Button>;
}
renderSaveButton () {
return <Button
variant="primary"
margin="0 0 0 x-small"
disabled={!this.isValid()}
onClick={this.handleSave}>
{formatMessage("Save")}
</Button>;
}
renderTitleInput () {
const value = this.findCurrentValue('title');
return (
<TextInput
label={formatMessage("Title")}
value={value}
messages={this.state.titleMessages}
onChange={this.handleTitleChange}
/>
);
}
renderDateInput () {
return (
<DateInput
required={true}
messages={this.state.dateMessages}
label={formatMessage("Date")}
nextLabel={formatMessage("Next Month")}
previousLabel={formatMessage("Previous Month")}
locale={this.props.locale}
timeZone={this.props.timeZone}
placement="start"
dateValue={this.state.updates.date}
onDateChange={this.handleDateChange}
/>
);
}
renderCourseSelectOptions () {
if (!this.props.courses) return [];
return this.props.courses.map(course => {
return <option key={course.id} value={course.id}>{course.longName}</option>;
});
}
renderCourseSelect () {
let courseId = this.findCurrentValue('courseId');
if (courseId == null) courseId = 'none';
return (
<Select
label={formatMessage("Course")}
value={courseId}
onChange={this.handleCourseIdChange}
>
<option value="none">{formatMessage("Optional: Add Course")}</option>
{this.renderCourseSelectOptions()}
</Select>
);
}
renderDetailsInput () {
const value = this.findCurrentValue('details');
return (
<TextArea
label={formatMessage("Details")}
height="10rem"
autoGrow={false}
value={value}
onChange={(e) => this.handleChange('details', e.target.value)}
/>
);
}
renderTrayHeader () {
if (this.props.noteItem) {
return (
<h2>{formatMessage('Edit {title}', { title: this.props.noteItem.title })}</h2>
);
} else {
return (
<h2>{formatMessage("Add To Do")}</h2>
);
}
}
render () {
return (
<div className={styles.root}>
<Container
as="div"
padding="large medium medium"
>
<FormFieldGroup
rowSpacing="small"
description={
<ScreenReaderContent>
{this.renderTrayHeader()}
</ScreenReaderContent>
}
>
{this.renderTitleInput()}
{this.renderDateInput()}
{this.renderCourseSelect()}
{this.renderDetailsInput()}
</FormFieldGroup>
<Container as="div" margin="small 0 0" textAlign="end">
{this.renderDeleteButton()}
{this.renderSaveButton()}
</Container>
</Container>
</div>
);
}
}
export default themeable(theme, styles)(UpdateItemTray);
|
src/containers/book_list.js | gui-santos/exp-redux | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { selectBook } from '../actions/index';
import { bindActionCreators } from 'redux';
class BookList extends Component {
renderList() {
return this.props.books.map((book) => {
return (
<li
key={book.title}
onClick={() => this.props.selectBook(book)}
className="list-group-item">
{book.title}
</li>
);
});
}
render() {
return (
<ul className="list-group col-sm-4">
{this.renderList()}
</ul>
);
}
}
function mapStateToProps(state) {
// whatever is returned here will show up as props on the BookList
return {
books: state.books
}
}
// anything returned from this will be a props on the BookList
function mapDispatchToProps(dispatch) {
// whenever selecBook is called, the result is passed to all reducers
return bindActionCreators({ selectBook: selectBook }, dispatch);
}
// promote BookList to container - it needs to know about the dispatch method, selectBook
// make it available as a prop
export default connect (mapStateToProps, mapDispatchToProps) (BookList); |
docs/app/Examples/views/Comment/Content/CommentExampleReplyForm.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Button, Comment, Form } from 'semantic-ui-react'
const CommentExampleReplyForm = () => (
<Comment.Group>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/steve.jpg' />
<Comment.Content>
<Comment.Author as='a'>Steve Jobes</Comment.Author>
<Comment.Metadata>
<div>2 days ago</div>
</Comment.Metadata>
<Comment.Text>Revolutionary!</Comment.Text>
<Comment.Actions>
<Comment.Action active>Reply</Comment.Action>
</Comment.Actions>
<Form reply onSubmit={e => e.preventDefault()}>
<Form.TextArea />
<Button content='Add Reply' labelPosition='left' icon='edit' primary />
</Form>
</Comment.Content>
</Comment>
</Comment.Group>
)
export default CommentExampleReplyForm
|
styleguide/screens/Patterns/Patterns.js | NGMarmaduke/bloom | import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Accessibility from './Accessibility/Accessibility';
import Animation from './Animation/Animation';
import Badge from './Badge/Badge';
import Buttons from './Buttons/Buttons';
import Cards from './Cards/Cards';
import Carousel from './Carousel/Carousel';
import Dropdown from './Dropdown/Dropdown';
import Figure from './Figure/Figure';
import FittedImage from './FittedImage/FittedImage';
import HorizontalOverflowBar from './HorizontalOverflowBar/HorizontalOverflowBar';
import InputField from './InputField/InputField';
import Inputs from './Inputs/Inputs';
import LeftRight from './LeftRight/LeftRight';
import Loader from './Loader/Loader';
import Markdown from './Markdown/Markdown';
import Medallion from './Medallion/Medallion';
import Modals from './Modals/Modals';
import Pagination from './Pagination/Pagination';
import Panels from './Panels/Panels';
import SocialLinks from './SocialLinks/SocialLinks';
import Tabs from './Tabs/Tabs';
import TabBar from './TabBar/TabBar';
import Tether from './Tether/Tether';
const Patterns = () => (
<Switch>
<Route path="/patterns/accessibility" component={ Accessibility } />
<Route path="/patterns/animation" component={ Animation } />
<Route path="/patterns/badge" component={ Badge } />
<Route path="/patterns/buttons" component={ Buttons } />
<Route path="/patterns/horizontal-overflow-bar" component={ HorizontalOverflowBar } />
<Route path="/patterns/cards" component={ Cards } />
<Route path="/patterns/carousel" component={ Carousel } />
<Route path="/patterns/dropdown" component={ Dropdown } />
<Route path="/patterns/figure" component={ Figure } />
<Route path="/patterns/fitted-image" component={ FittedImage } />
<Route path="/patterns/input-field" component={ InputField } />
<Route path="/patterns/inputs" component={ Inputs } />
<Route path="/patterns/leftright" component={ LeftRight } />
<Route path="/patterns/loader" component={ Loader } />
<Route path="/patterns/markdown" component={ Markdown } />
<Route path="/patterns/medallion" component={ Medallion } />
<Route path="/patterns/modals" component={ Modals } />
<Route path="/patterns/pagination" component={ Pagination } />
<Route path="/patterns/panels" component={ Panels } />
<Route path="/patterns/social-links" component={ SocialLinks } />
<Route path="/patterns/tabs" component={ Tabs } />
<Route path="/patterns/tab-bar" component={ TabBar } />
<Route path="/patterns/tether" component={ Tether } />
</Switch>
);
export default Patterns;
|
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js | lzpfmh/actor-platform | import _ from 'lodash';
import React from 'react';
import { Styles, RaisedButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ContactStore from 'stores/ContactStore';
import ContactActionCreators from 'actions/ContactActionCreators';
import AddContactStore from 'stores/AddContactStore';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import ContactsSectionItem from './ContactsSectionItem.react';
import AddContactModal from 'components/modals/AddContact.react.js';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isAddContactModalOpen: AddContactStore.isModalOpen(),
contacts: ContactStore.getContacts()
};
};
class ContactsSection extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
ContactActionCreators.hideContactList();
ContactStore.removeChangeListener(this.onChange);
AddContactStore.removeChangeListener(this.onChange);
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ContactActionCreators.showContactList();
ContactStore.addChangeListener(this.onChange);
AddContactStore.addChangeListener(this.onChange);
ThemeManager.setTheme(ActorTheme);
}
onChange = () => {
this.setState(getStateFromStores());
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
render() {
let contacts = this.state.contacts;
let contactList = _.map(contacts, (contact, i) => {
return (
<ContactsSectionItem contact={contact} key={i}/>
);
});
let addContactModal;
if (this.state.isAddContactModalOpen) {
addContactModal = <AddContactModal/>;
}
return (
<section className="sidebar__contacts">
<ul className="sidebar__list sidebar__list--contacts">
{contactList}
</ul>
<footer>
<RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/>
{addContactModal}
</footer>
</section>
);
}
}
export default ContactsSection;
|
app/javascript/mastodon/features/compose/components/search.js | salvadorpla/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Overlay from 'react-overlays/lib/Overlay';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { searchEnabled } from '../../../initial_state';
import Icon from 'mastodon/components/icon';
const messages = defineMessages({
placeholder: { id: 'search.placeholder', defaultMessage: 'Search' },
});
class SearchPopout extends React.PureComponent {
static propTypes = {
style: PropTypes.object,
};
render () {
const { style } = this.props;
const extraInformation = searchEnabled ? <FormattedMessage id='search_popout.tips.full_text' defaultMessage='Simple text returns statuses you have written, favourited, boosted, or have been mentioned in, as well as matching usernames, display names, and hashtags.' /> : <FormattedMessage id='search_popout.tips.text' defaultMessage='Simple text returns matching display names, usernames and hashtags' />;
return (
<div style={{ ...style, position: 'absolute', width: 285, zIndex: 2 }}>
<Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}>
{({ opacity, scaleX, scaleY }) => (
<div className='search-popout' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}>
<h4><FormattedMessage id='search_popout.search_format' defaultMessage='Advanced search format' /></h4>
<ul>
<li><em>#example</em> <FormattedMessage id='search_popout.tips.hashtag' defaultMessage='hashtag' /></li>
<li><em>@username@domain</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li>
<li><em>URL</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li>
<li><em>URL</em> <FormattedMessage id='search_popout.tips.status' defaultMessage='status' /></li>
</ul>
{extraInformation}
</div>
)}
</Motion>
</div>
);
}
}
export default @injectIntl
class Search extends React.PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
value: PropTypes.string.isRequired,
submitted: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
onShow: PropTypes.func.isRequired,
openInRoute: PropTypes.bool,
intl: PropTypes.object.isRequired,
};
state = {
expanded: false,
};
handleChange = (e) => {
this.props.onChange(e.target.value);
}
handleClear = (e) => {
e.preventDefault();
if (this.props.value.length > 0 || this.props.submitted) {
this.props.onClear();
}
}
handleKeyUp = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
this.props.onSubmit();
if (this.props.openInRoute) {
this.context.router.history.push('/search');
}
} else if (e.key === 'Escape') {
document.querySelector('.ui').parentElement.focus();
}
}
handleFocus = () => {
this.setState({ expanded: true });
this.props.onShow();
}
handleBlur = () => {
this.setState({ expanded: false });
}
render () {
const { intl, value, submitted } = this.props;
const { expanded } = this.state;
const hasValue = value.length > 0 || submitted;
return (
<div className='search'>
<label>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.placeholder)}</span>
<input
className='search__input'
type='text'
placeholder={intl.formatMessage(messages.placeholder)}
value={value}
onChange={this.handleChange}
onKeyUp={this.handleKeyUp}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
/>
</label>
<div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}>
<Icon id='search' className={hasValue ? '' : 'active'} />
<Icon id='times-circle' className={hasValue ? 'active' : ''} aria-label={intl.formatMessage(messages.placeholder)} />
</div>
<Overlay show={expanded && !hasValue} placement='bottom' target={this}>
<SearchPopout />
</Overlay>
</div>
);
}
}
|
client/src/Components/oldMasterForm/Education.js | teamcrux/EmploymentOptions | import React from 'react';
import { Field } from 'redux-form';
import selectState from '../SelectState';
const Education = () => {
return (
<div className="section">
<div className="section">
<h3>School</h3>
<div>
<label htmlFor="school_name">School name</label>
<Field name="school_name" component="input" type="text"/>
</div>
<div>
<label htmlFor="ged">GED?</label>
<label><Field name="ged" id="ged" component="input" value="true" type="radio"/> Yes</label>
<label><Field name="ged" id="ged" component="input" value="false" type="radio"/> No</label>
</div>
<div>
<label htmlFor="diploma">Diploma?</label>
<label><Field name="diploma" id="diploma" component="input" value="true" type="radio"/> Yes</label>
<label><Field name="diploma" id="diploma" component="input" value="false" type="radio"/> No</label>
</div>
<h4>Address</h4>
<div>
<label htmlFor="sch_street1">Street Address 1</label>
<Field name="sch_street1" component="input" type="text"/>
</div>
<div>
<label htmlFor="sch_street2">Street Address 2</label>
<Field name="sch_street2" component="input" type="text"/>
</div>
<div>
<label htmlFor="sch_city">City</label>
<Field name="sch_city" component="input" type="text"/>
</div>
<div>
<label htmlFor="sch_state">State</label>
<Field name="sch_state" id="sch_state" component={selectState}></Field>
</div>
<div>
<label htmlFor="sch_zip">Zip</label>
<Field name="sch_zip" component="input" type="text"/>
</div>
</div>
<div className="section">
<h3>College</h3>
<div>
<label htmlFor="col_name">College name</label>
<Field name="col_name" component="input" type="text"/>
</div>
<div>
<label htmlFor="cert_name">Qualification/Certificate</label>
<Field name="cert_name" component="input" type="text"/>
</div>
<div>
<h4>Address</h4>
<div>
<label htmlFor="col_street1">Street Address 1</label>
<Field name="col_street1" component="input" type="text"/>
</div>
<div>
<label htmlFor="col_street2">Street Address 2</label>
<Field name="col_street2" component="input" type="text"/>
</div>
<div>
<label htmlFor="col_city">City</label>
<Field name="col_city" component="input" type="text"/>
</div>
<div>
<label htmlFor="col_state">State</label>
<Field name="col_state" id="col_state" component={selectState}></Field>
</div>
<div>
<label htmlFor="col_zip">Zip</label>
<Field name="col_zip" component="input" type="text"/>
</div>
</div>
</div>
<div className="section">
<h3>Vocational/Specialized Training</h3>
<div>
<label htmlFor="voc_cert_name">Qualification/Certificate</label>
<Field name="voc_cert_name" component="input" type="text"/>
</div>
</div>
</div>
)
};
export default Education
|
src/components/SelectableList.js | nickooms/racing-webgl2 | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { List, makeSelectable } from 'material-ui/List';
const TempSelectableList = makeSelectable(List);
function wrapState(ComposedComponent) {
return class SelectableList extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
defaultValue: PropTypes.number.isRequired,
};
componentWillMount() {
this.setState({ selectedIndex: this.props.defaultValue });
}
handleRequestChange = (event, index) => this.setState({ selectedIndex: index });
render() {
return (
<ComposedComponent value={this.state.selectedIndex} onChange={this.handleRequestChange}>
{this.props.children}
</ComposedComponent>
);
}
};
}
const SelectableList = wrapState(TempSelectableList);
export default SelectableList;
|
src/components/Main.js | vinhnglx/Dzone-news | require('normalize.css/normalize.css');
require('styles/App.scss');
import React from 'react';
import Stream from './Stream';
import CategoryList from './CategoryList';
class App extends React.Component {
render() {
return (
<section className="row">
<article className="col-md-8">
<div className="row">
<div className="col-md-12">
<div className="blog-post">
<Stream />
</div>
</div>
</div>
</article>
<CategoryList />
</section>
);
}
}
export default App;
|
pages/error/index.js | zendesk/copenhelp | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import history from '../../core/history';
import Link from '../../components/Link';
import s from './styles.css';
class ErrorPage extends React.Component {
static propTypes = {
error: React.PropTypes.object,
};
componentDidMount() {
document.title = this.props.error && this.props.error.status === 404 ?
'Page Not Found' : 'Error';
}
goBack = event => {
event.preventDefault();
history.goBack();
};
render() {
const [code, title] = this.props.error && this.props.error.status === 404 ?
['404', 'Page not found'] :
['Error', 'Oups, something went wrong'];
return (
<div className={s.container}>
<main className={s.content}>
<h1 className={s.code}>{code}</h1>
<p className={s.title}>{title}</p>
{code === '404' &&
<p className={s.text}>
The page you're looking for does not exist or an another error occurred.
</p>
}
<p className={s.text}>
<a href="/" onClick={this.goBack}>Go back</a>, or head over to the
<Link to="/">home page</Link> to choose a new direction.
</p>
</main>
</div>
);
}
}
export default ErrorPage;
|
examples/with-flow/pages/index.js | BlancheXu/test | // @flow
import React from 'react'
import Page from '../components/Page'
export default () => (
<Page>
<div>Hello World</div>
</Page>
)
|
client/components/events/EventList.js | yanigisawa/voting-tornado | import React from 'react';
import {PropTypes} from 'prop-types';
import EventItemRow from './EventItemRow';
const EventList = ({events, allowEventEdit, allowEventVoting}) => {
return (
<div>
<table className="table">
<thead>
<tr>
<th>Title</th>
{allowEventVoting && <th>Vote</th>}
<th>Start Date</th>
<th>End Date</th>
{allowEventEdit && <th>Edit</th>}
</tr>
</thead>
<tbody>
{events && events.map(event =>
<EventItemRow key={event.id.toString()} event={event} allowEventEdit={allowEventEdit} allowEventVoting={allowEventVoting} />
)}
</tbody>
</table>
</div>
);
};
EventList.propTypes = {
events: PropTypes.array.isRequired,
allowEventEdit: PropTypes.bool.isRequired,
allowEventVoting: PropTypes.bool.isRequired
};
export default EventList;
|
src/stories/index.js | Silvakilla/React-Component-Library | import '../index.css';
import React from 'react';
import {storiesOf} from '@storybook/react';
import Text from '../Components/Text/Text';
import Input from '../Components/Input/Input';
import { Panel } from '../Components/Panel/Panel';
const documentation = storiesOf('Documentation', module);
documentation.add('PropTypes - Types',() => {
return (
<Text data={
<div>
<h3>All Types which can be used with PropTypes</h3>
<p>
PropTypes.array
</p>
<p>
PropTypes.bool
</p>
<p>
PropTypes.func
</p>
<p>
PropTypes.number
</p>
<p>
PropTypes.object
</p>
<p>
PropTypes.string
</p>
<p>
PropTypes.symbol
</p>
<p>
PropTypes.node
</p>
<p>
PropTypes.element
</p>
<p>
PropTypes.instanceOf(Message)
</p>
<p>
PropTypes.oneOf(PropTypes.string,...)
</p>
<p>
PropTypes.oneOfType([PropTypes.string,PropTypes.number])
</p>
<p>
PropTypes.arrayOf(PropTypes.number)
</p>
<p>
PropTypes.PropTypes.shape([curly brackets]color: PropTypes.string, fontSize: PropTypes.number[curly brackets])
</p>
<p>
PropTypes.func.isRequired
</p>
</div>
}/>
);
});
const componentStories = storiesOf('React Component Library', module);
componentStories.add('Output',() =>{
return (
<div>
<Text data='Test'/>
<Text data={['Array-Test','Array-Test 2']}/>
<Text data={<p>P-Element-Test</p>}/>
</div>
);
});
componentStories.add('Input',() => {
return (
<div>
<h2>Text-Input with RegEx</h2>
<Input type="text" placeholder="text" pattern="[A-Za-z0-9]{5}" />
<h2>Other Inputs</h2>
<Input type="email" placeholder="email" />
<Input type="password" placeholder="password" />
</div>
)
});
componentStories.add('Panel',() => {
return(
<div>
<Panel style={{border:'1px solid black',width:'380px',height:'120px'}}>
<p>Text</p>
</Panel>
</div>
)
}); |
src/client/components/status-bar/index.js | adamgruber/mochawesome-report-generator | /* eslint-disable max-len */
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames/bind';
import styles from './status-bar.css';
const cx = classNames.bind(styles);
const StatusBar = ({ stats }) => {
const {
hasOther,
hasSkipped,
other,
skipped,
pendingPercent,
passPercent,
passPercentClass,
} = stats;
const cxname = cx('component', {
'has-failed-hooks': hasOther,
'has-skipped-tests': hasSkipped,
});
const skippedText = `${skipped} Skipped Test${skipped > 1 ? 's' : ''}`;
const failedText = `${other} Failed Hook${other > 1 ? 's' : ''}`;
return (
<div className={cxname}>
<div className="container">
<div className="row">
{!!hasOther && (
<div className={cx('item', 'hooks', 'danger')}>{failedText}</div>
)}
{!!hasSkipped && (
<div className={cx('item', 'skipped', 'danger')}>{skippedText}</div>
)}
<div
className={cx(
'item',
'pending-pct'
)}>{`${pendingPercent}% Pending`}</div>
<div
className={cx(
'item',
'passing-pct',
passPercentClass
)}>{`${passPercent}% Passing`}</div>
</div>
</div>
</div>
);
};
StatusBar.propTypes = {
stats: PropTypes.object,
};
export default StatusBar;
|
src/icons/Mouse.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class Mouse extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M256,32c-0.46,0-0.917,0.011-1.376,0.015l5.747,0.057C258.92,32.029,257.464,32,256,32z"></path>
<path d="M378.553,193.211c-0.195,0.064-0.414,0.16-0.619,0.269c-34.234,13.289-76.337,22.52-121.886,22.475
c-45.52-0.076-87.626-9.398-121.81-22.772c-0.19-0.104-0.429-0.192-0.647-0.265c-1.531-0.554-3.146-0.897-4.841-0.917
c-0.254-0.001-0.5-0.013-0.75,0v176.012C128,429.892,185.308,480,256,480c21.992,0,42.687-4.803,60.766-13.355
c0.095-0.045,0.191-0.087,0.286-0.133c0.026-0.013,0.054-0.026,0.08-0.039c4.87-2.344,9.581-4.963,14.122-7.828
C363.219,438.275,384,405.271,384,368.012V192c-0.191-0.008-0.496,0-0.689,0C381.584,192.014,380.092,192.651,378.553,193.211z
M317.132,466.424c-0.026,0.013-0.054,0.026-0.08,0.039c-0.095,0.045-0.191,0.088-0.286,0.133c0.095-0.045,0.191-0.088,0.286-0.133
C317.078,466.45,317.105,466.437,317.132,466.424c4.87-2.342,9.581-4.961,14.122-7.825
C326.758,461.463,322.044,464.083,317.132,466.424z"></path>
<path d="M331.254,458.599c-4.541,2.864-9.252,5.483-14.122,7.825C322.044,464.083,326.758,461.463,331.254,458.599z"></path>
<path d="M260.371,32.072l-5.747-0.057C184.566,32.662,128,82.547,128,144v22.708c2.158,2.024,4.593,3.755,7.251,5.115
c0.673,0.337,1.386,0.659,2.059,0.996c0.032,0.027,0.077,0.01,0.109,0.036c22.757,10.35,51.429,15.801,83.415,19.006
c0.694,0.078,1.397,0.107,2.148,0.12C234.24,191.997,239.996,192,240,181.411V96c0-8.836,7.164-16,16-16c8.836,0,16,7.164,16,16
v86.328c-0.088,9.672,5.926,9.72,17.2,9.749c0.717-0.016,1.415-0.045,2.081-0.105c0.062-0.003,0.141,0.005,0.244-0.02
c31.682-3.119,60.143-8.405,82.808-18.59c1.162-0.545,2.291-1.056,3.407-1.581c2.271-1.232,4.365-2.743,6.26-4.466V144
C384,83.425,329.039,34.09,260.371,32.072z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M256,32c-0.46,0-0.917,0.011-1.376,0.015l5.747,0.057C258.92,32.029,257.464,32,256,32z"></path>
<path d="M378.553,193.211c-0.195,0.064-0.414,0.16-0.619,0.269c-34.234,13.289-76.337,22.52-121.886,22.475
c-45.52-0.076-87.626-9.398-121.81-22.772c-0.19-0.104-0.429-0.192-0.647-0.265c-1.531-0.554-3.146-0.897-4.841-0.917
c-0.254-0.001-0.5-0.013-0.75,0v176.012C128,429.892,185.308,480,256,480c21.992,0,42.687-4.803,60.766-13.355
c0.095-0.045,0.191-0.087,0.286-0.133c0.026-0.013,0.054-0.026,0.08-0.039c4.87-2.344,9.581-4.963,14.122-7.828
C363.219,438.275,384,405.271,384,368.012V192c-0.191-0.008-0.496,0-0.689,0C381.584,192.014,380.092,192.651,378.553,193.211z
M317.132,466.424c-0.026,0.013-0.054,0.026-0.08,0.039c-0.095,0.045-0.191,0.088-0.286,0.133c0.095-0.045,0.191-0.088,0.286-0.133
C317.078,466.45,317.105,466.437,317.132,466.424c4.87-2.342,9.581-4.961,14.122-7.825
C326.758,461.463,322.044,464.083,317.132,466.424z"></path>
<path d="M331.254,458.599c-4.541,2.864-9.252,5.483-14.122,7.825C322.044,464.083,326.758,461.463,331.254,458.599z"></path>
<path d="M260.371,32.072l-5.747-0.057C184.566,32.662,128,82.547,128,144v22.708c2.158,2.024,4.593,3.755,7.251,5.115
c0.673,0.337,1.386,0.659,2.059,0.996c0.032,0.027,0.077,0.01,0.109,0.036c22.757,10.35,51.429,15.801,83.415,19.006
c0.694,0.078,1.397,0.107,2.148,0.12C234.24,191.997,239.996,192,240,181.411V96c0-8.836,7.164-16,16-16c8.836,0,16,7.164,16,16
v86.328c-0.088,9.672,5.926,9.72,17.2,9.749c0.717-0.016,1.415-0.045,2.081-0.105c0.062-0.003,0.141,0.005,0.244-0.02
c31.682-3.119,60.143-8.405,82.808-18.59c1.162-0.545,2.291-1.056,3.407-1.581c2.271-1.232,4.365-2.743,6.26-4.466V144
C384,83.425,329.039,34.09,260.371,32.072z"></path>
</g>
</IconBase>;
}
};Mouse.defaultProps = {bare: false} |
docs/app/Examples/views/Item/Content/ItemExampleDescriptions.js | koenvg/Semantic-UI-React | import React from 'react'
import { Item } from 'semantic-ui-react'
const description = [
'Cute dogs come in a variety of shapes and sizes. Some cute dogs are cute for their adorable faces, others for their',
'tiny stature, and even others for their massive size.',
].join(' ')
const ItemExampleDescriptions = () => (
<Item.Group>
<Item>
<Item.Image size='small' src='http://semantic-ui.com/images/wireframe/image.png' />
<Item.Content>
<Item.Header as='a'>Cute Dog</Item.Header>
<Item.Description>
<p>{description}</p>
<p>
Many people also have their own barometers for what makes a cute dog.
</p>
</Item.Description>
</Item.Content>
</Item>
<Item>
<Item.Image size='small' src='http://semantic-ui.com/images/wireframe/image.png' />
<Item.Content>
<Item.Header as='a'>Cute Dog</Item.Header>
<Item.Description content={description} />
</Item.Content>
</Item>
<Item>
<Item.Image size='small' src='http://semantic-ui.com/images/wireframe/image.png' />
<Item.Content header='Cute Dog' description={description} />
</Item>
</Item.Group>
)
export default ItemExampleDescriptions
|
client/src/PlayPause.js | jghibiki/Doc | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import Button from '@material-ui/core/Button';
import SkipPreviousIcon from '@material-ui/icons/SkipPrevious';
import PlayArrowIcon from '@material-ui/icons/PlayArrow';
import SkipNextIcon from '@material-ui/icons/SkipNext';
import PauseIcon from '@material-ui/icons/Pause';
import ws_client from './WebSocketClient.js';
var styles = theme => ({
magicMode: {
display: 'flex',
alignItems: 'center',
paddingLeft: theme.spacing.unit,
paddingBottom: theme.spacing.unit,
},
button: {
margin: theme.spacing.unit,
},
});
class PlayPause extends Component {
constructor(props){
super(props);
this.ws = props.ws
this.props = props;
this.state = {
playing: true
}
ws_client.subscribe("toggle.play_pause", data => {
// update playback state
this.setState({
playing: !this.state.playing
})
});
ws_client.subscribe("get.play_pause", data => {
// update playback state
this.setState({
playing: data.payload.playing
})
});
ws_client.registerInitHook(()=>{
ws_client.send({type:"command", key:"get.play_pause"});
});
}
sendSkipSong(){
ws_client.send({
type: "command",
key: "set.skip",
details: {}
}, true);
}
sendTogglePlayPause(){
ws_client.send({
type: "command",
key: "toggle.play_pause"
}, true);
}
render(){
const { classes, theme } = this.props;
return (
<div className={classes.controls}>
<IconButton aria-label="Previous" onClick={()=>alert("Looked uneaven without a previous arrow... :)")} >
{theme.direction === 'rtl' ? <SkipNextIcon /> : <SkipPreviousIcon />}
</IconButton>
<IconButton aria-label="Play/pause" onClick={this.sendTogglePlayPause}>
{this.state.playing ? <PauseIcon className={classes.playIcon} /> : <PlayArrowIcon className={classes.playIcon} /> }
</IconButton>
<IconButton aria-label="Next" onClick={this.sendSkipSong}>
{theme.direction === 'rtl' ? <SkipPreviousIcon /> : <SkipNextIcon />}
</IconButton>
</div>
)
}
}
PlayPause.propTypes = {
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
};
export default withStyles(styles, {withTheme: true})(PlayPause);
|
static/src/js/index.js | enginyoyen/blackcrystal | import React from 'react';
import { createHistory, createHashHistory } from 'history';
import Root from './Root';
import ReactDOM from 'react-dom';
import '../lib/jquery-2.2.0.min.js';
import '../css/style.css';
import '../css/AdminLTE.min.css';
import '../css/skins/_all-skins.min.css';
import '../css/ionicons.min.css';
import '../css/bootstrap.min.css';
import '../css/bootstrap-theme.min.css';
const rootEl = document.getElementById('root');
// Use hash location for Github Pages
// but switch to HTML5 history locally.
const history = process.env.NODE_ENV === 'production' ?
createHashHistory() :
createHistory();
ReactDOM.render(<Root history={history} />, rootEl);
|
src/main.js | lunachi/react-webpack2-staging | import React from 'react';
import ReactDOM from 'react-dom';
import Demo from './views/demo/index';
ReactDOM.render(
<Demo/>,
document.getElementById('app')
);
|
src/components/Options/Option/OptionString.js | chrisxclash/play-midnight | import React from 'react';
import StyledOption from './Option.styled';
const Option = ({ title, children }) => (
<StyledOption>
<div className="Option__header">
<div className="Option__content">
<div className="Option__title">{title}</div>
<div className="Option__description">{children}</div>
</div>
</div>
</StyledOption>
);
export default Option;
|
packages/@lyra/components/src/labels/story.js | VegaPublish/vega-studio | import React from 'react'
import {storiesOf} from 'part:@lyra/storybook'
import DefaultLabel from 'part:@lyra/components/labels/default'
import {withKnobs, number, text} from 'part:@lyra/storybook/addons/knobs'
import Lyra from 'part:@lyra/storybook/addons/lyra'
storiesOf('Labels')
.addDecorator(withKnobs)
.add('Default', () => {
return (
<Lyra
part="part:@lyra/components/labels/default"
propTables={[DefaultLabel]}
>
<DefaultLabel
level={number('level (prop)', 0)}
htmlFor="thisNeedsToBeUnique"
>
{text('children (prop)', 'Label')}
</DefaultLabel>
</Lyra>
)
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.