var ResizeExample = createReactClass({ getInitialState() { return { dataList: new FakeObjectDataListStore(ROWS), columnWidths: columnWidths } }, _rowGetter(index) { return this.state.dataList.getObjectAt(index); }, _onColumnResizeEndCallback(newColumnWidth, dataKey) { var columnWidths = this.state.columnWidths; columnWidths[dataKey] = newColumnWidth; isColumnResizing = false; this.setState({ columnWidths }) }, render() { return ( <Table rowHeight={30} headerHeight={50} rowGetter={this._rowGetter} rowsCount={this.state.dataList.getSize()} isColumnResizing={isColumnResizing} onColumnResizeEndCallback={this._onColumnResizeEndCallback} width={1000} height={500} {...this.props}> <Column dataKey="firstName" fixed={true} label="First Name" width={columnWidths['firstName']} isResizable={true} /> <Column label="Last Name (min/max constrained)" dataKey="lastName" width={columnWidths['lastName']} isResizable={true} minWidth={70} maxWidth={170} /> <Column label="Company" dataKey="companyName" width={columnWidths['companyName']} isResizable={true} /> <Column label="Sentence" dataKey="sentence" width={columnWidths['sentence']} isResizable={true} /> </Table> ); } });
* LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @format */ 'use strict'; const React = require('React'); const createReactClass = require('create-react-class'); const {getComponentName, getReactComponent} = require('../RelayContainerUtils'); const CreateClassComponent = createReactClass({ displayName: 'CreateClassComponent', render: () => <div />, }); class ReactComponentSubclass extends React.Component { render() { return <div />; } } const FunctionalComponent = () => <div />; describe('RelayContainerUtils', () => { describe('getReactComponent', () => { it('returns a component that extends React.Component', () => { expect(getReactComponent(ReactComponentSubclass)).toBe( ReactComponentSubclass,
const Main = createClass({ /** * As an alternative to `MuiThemeProvider` you can add a theme directly into context. * See the [Material-UI themes](http://www.material-ui.com/#/customization/themes) docs for details. * * childContextTypes: { * muiTheme: PropTypes.object, * }, * getChildContext(){ * return { * muiTheme: getMuiTheme(), * } * }, */ getInitialState() { return { canSubmit: false, }; }, errorMessages: { wordsError: "Please only use letters", numericError: "Please provide a number", urlError: "Please provide a valid URL", }, styles: { paperStyle: { width: 300, margin: 'auto', padding: 20, }, switchStyle: { marginBottom: 16, }, submitStyle: { marginTop: 32, }, }, enableButton() { this.setState({ canSubmit: true, }); }, disableButton() { this.setState({ canSubmit: false, }); }, submitForm(data) { alert(JSON.stringify(data, null, 4)); }, notifyFormError(data) { console.error('Form error:', data); }, render() { let {paperStyle, switchStyle, submitStyle } = this.styles; let { wordsError, numericError, urlError } = this.errorMessages; return ( <MuiThemeProvider muiTheme={getMuiTheme()}> <Paper style={paperStyle}> <Formsy.Form onValid={this.enableButton} onInvalid={this.disableButton} onValidSubmit={this.submitForm} onInvalidSubmit={this.notifyFormError} > <FormsyDate name="date" required floatingLabelText="Date" /> <FormsyTime name="time" required floatingLabelText="Time" /> <FormsySelect name="frequency" required floatingLabelText="How often do you?" menuItems={this.selectFieldItems} > <MenuItem value={'never'} primaryText="Never" /> <MenuItem value={'nightly'} primaryText="Every Night" /> <MenuItem value={'weeknights'} primaryText="Weeknights" /> </FormsySelect> <FormsyAutoComplete name="frequency-auto-complete" required floatingLabelText="How often do you?" dataSource={[ 'Never', 'Every Night', 'Weeknights' ]} /> <FormsyCheckbox name="agree" label="Do you agree to disagree?" style={switchStyle} /> <FormsyToggle name="toggle" label="Toggle" style={switchStyle} /> <FormsyRadioGroup name="shipSpeed" defaultSelected="not_light"> <FormsyRadio value="light" label="prepare for light speed" style={switchStyle} /> <FormsyRadio value="not_light" label="light speed too slow" style={switchStyle} /> <FormsyRadio value="ludicrous" label="go to ludicrous speed" style={switchStyle} disabled={true} /> </FormsyRadioGroup> <FormsyText name="name" validations="isWords" validationError={wordsError} required hintText="What is your name?" floatingLabelText="Name" /> <FormsyText name="age" validations="isNumeric" validationError={numericError} hintText="Are you a wrinkly?" floatingLabelText="Age (optional)" /> <FormsyText name="url" validations="isUrl" validationError={urlError} required hintText="http://www.example.com" floatingLabelText="URL" updateImmediately /> <RaisedButton style={submitStyle} type="submit" label="Submit" disabled={!this.state.canSubmit} /> </Formsy.Form> </Paper> </MuiThemeProvider> ); }, });
var NavigatorIOS = createReactClass({ displayName: 'NavigatorIOS', propTypes: { /** * NavigatorIOS uses `route` objects to identify child views, their props, * and navigation bar configuration. Navigation operations such as push * operations expect routes to look like this the `initialRoute`. */ initialRoute: PropTypes.shape({ /** * The React Class to render for this route */ component: PropTypes.func.isRequired, /** * The title displayed in the navigation bar and the back button for this * route. */ title: PropTypes.string.isRequired, /** * If set, a title image will appear instead of the text title. */ titleImage: Image.propTypes.source, /** * Use this to specify additional props to pass to the rendered * component. `NavigatorIOS` will automatically pass in `route` and * `navigator` props to the comoponent. */ passProps: PropTypes.object, /** * If set, the left navigation button image will be displayed using this * source. Note that this doesn't apply to the header of the current * view, but to those views that are subsequently pushed. */ backButtonIcon: Image.propTypes.source, /** * If set, the left navigation button text will be set to this. Note that * this doesn't apply to the left button of the current view, but to * those views that are subsequently pushed */ backButtonTitle: PropTypes.string, /** * If set, the left navigation button image will be displayed using * this source. */ leftButtonIcon: Image.propTypes.source, /** * If set, the left navigation button will display this text. */ leftButtonTitle: PropTypes.string, /** * If set, the left header button will appear with this system icon * * Supported icons are `done`, `cancel`, `edit`, `save`, `add`, * `compose`, `reply`, `action`, `organize`, `bookmarks`, `search`, * `refresh`, `stop`, `camera`, `trash`, `play`, `pause`, `rewind`, * `fast-forward`, `undo`, `redo`, and `page-curl` */ leftButtonSystemIcon: PropTypes.oneOf(Object.keys(SystemIcons)), /** * This function will be invoked when the left navigation bar item is * pressed. */ onLeftButtonPress: PropTypes.func, /** * If set, the right navigation button image will be displayed using * this source. */ rightButtonIcon: Image.propTypes.source, /** * If set, the right navigation button will display this text. */ rightButtonTitle: PropTypes.string, /** * If set, the right header button will appear with this system icon * * See leftButtonSystemIcon for supported icons */ rightButtonSystemIcon: PropTypes.oneOf(Object.keys(SystemIcons)), /** * This function will be invoked when the right navigation bar item is * pressed. */ onRightButtonPress: PropTypes.func, /** * Styles for the navigation item containing the component. */ wrapperStyle: ViewPropTypes.style, /** * Boolean value that indicates whether the navigation bar is hidden. */ navigationBarHidden: PropTypes.bool, /** * Boolean value that indicates whether to hide the 1px hairline * shadow. */ shadowHidden: PropTypes.bool, /** * The color used for the buttons in the navigation bar. */ tintColor: PropTypes.string, /** * The background color of the navigation bar. */ barTintColor: PropTypes.string, /** * The style of the navigation bar. Supported values are 'default', 'black'. * Use 'black' instead of setting `barTintColor` to black. This produces * a navigation bar with the native iOS style with higher translucency. */ barStyle: PropTypes.oneOf(['default', 'black']), /** * The text color of the navigation bar title. */ titleTextColor: PropTypes.string, /** * Boolean value that indicates whether the navigation bar is * translucent. */ translucent: PropTypes.bool, }).isRequired, /** * Boolean value that indicates whether the navigation bar is hidden * by default. */ navigationBarHidden: PropTypes.bool, /** * Boolean value that indicates whether to hide the 1px hairline shadow * by default. */ shadowHidden: PropTypes.bool, /** * The default wrapper style for components in the navigator. * A common use case is to set the `backgroundColor` for every scene. */ itemWrapperStyle: ViewPropTypes.style, /** * The default color used for the buttons in the navigation bar. */ tintColor: PropTypes.string, /** * The default background color of the navigation bar. */ barTintColor: PropTypes.string, /** * The style of the navigation bar. Supported values are 'default', 'black'. * Use 'black' instead of setting `barTintColor` to black. This produces * a navigation bar with the native iOS style with higher translucency. */ barStyle: PropTypes.oneOf(['default', 'black']), /** * The default text color of the navigation bar title. */ titleTextColor: PropTypes.string, /** * Boolean value that indicates whether the navigation bar is * translucent by default */ translucent: PropTypes.bool, /** * Boolean value that indicates whether the interactive pop gesture is * enabled. This is useful for enabling/disabling the back swipe navigation * gesture. * * If this prop is not provided, the default behavior is for the back swipe * gesture to be enabled when the navigation bar is shown and disabled when * the navigation bar is hidden. Once you've provided the * `interactivePopGestureEnabled` prop, you can never restore the default * behavior. */ interactivePopGestureEnabled: PropTypes.bool, }, navigator: (undefined: ?Object), componentWillMount: function() { // Precompute a pack of callbacks that's frequently generated and passed to // instances. this.navigator = { push: this.push, pop: this.pop, popN: this.popN, replace: this.replace, replaceAtIndex: this.replaceAtIndex, replacePrevious: this.replacePrevious, replacePreviousAndPop: this.replacePreviousAndPop, resetTo: this.resetTo, popToRoute: this.popToRoute, popToTop: this.popToTop, }; }, componentDidMount: function() { this._enableTVEventHandler(); }, componentWillUnmount: function() { this._disableTVEventHandler(); }, getDefaultProps: function(): Object { return { translucent: true, }; }, getInitialState: function(): State { return { idStack: [getuid()], routeStack: [this.props.initialRoute], // The navigation index that we wish to push/pop to. requestedTopOfStack: 0, // The last index that native has sent confirmation of completed push/pop // for. At this point, we can discard any views that are beyond the // `requestedTopOfStack`. A value of `null` means we have not received // any confirmation, ever. We may receive an `observedTopOfStack` without // ever requesting it - native can instigate pops of its own with the // backswipe gesture. observedTopOfStack: 0, progress: 1, fromIndex: 0, toIndex: 0, // Whether or not we are making a navigator request to push/pop. (Used // for performance optimization). makingNavigatorRequest: false, // Whether or not we are updating children of navigator and if so (not // `null`) which index marks the beginning of all updates. Used for // performance optimization. updatingAllIndicesAtOrBeyond: 0, }; }, _toFocusOnNavigationComplete: (undefined: any), _handleFocusRequest: function(item: any) { if (this.state.makingNavigatorRequest) { this._toFocusOnNavigationComplete = item; } else { this._getFocusEmitter().emit('focus', item); } }, _focusEmitter: (undefined: ?EventEmitter), _getFocusEmitter: function(): EventEmitter { // Flow not yet tracking assignments to instance fields. var focusEmitter = this._focusEmitter; if (!focusEmitter) { focusEmitter = new EventEmitter(); this._focusEmitter = focusEmitter; } return focusEmitter; }, getChildContext: function(): { onFocusRequested: Function, focusEmitter: EventEmitter, } { return { onFocusRequested: this._handleFocusRequest, focusEmitter: this._getFocusEmitter(), }; }, childContextTypes: { onFocusRequested: PropTypes.func, focusEmitter: PropTypes.instanceOf(EventEmitter), }, _tryLockNavigator: function(cb: () => void) { this.refs[TRANSITIONER_REF].requestSchedulingNavigation( (acquiredLock) => acquiredLock && cb() ); }, _handleNavigatorStackChanged: function(e: Event) { var newObservedTopOfStack = e.nativeEvent.stackLength - 1; invariant( newObservedTopOfStack <= this.state.requestedTopOfStack, 'No navigator item should be pushed without JS knowing about it %s %s', newObservedTopOfStack, this.state.requestedTopOfStack ); var wasWaitingForConfirmation = this.state.requestedTopOfStack !== this.state.observedTopOfStack; if (wasWaitingForConfirmation) { invariant( newObservedTopOfStack === this.state.requestedTopOfStack, 'If waiting for observedTopOfStack to reach requestedTopOfStack, ' + 'the only valid observedTopOfStack should be requestedTopOfStack.' ); } // Mark the most recent observation regardless of if we can lock the // navigator. `observedTopOfStack` merely represents what we've observed // and this first `setState` is only executed to update debugging // overlays/navigation bar. // Also reset progress, toIndex, and fromIndex as they might not end // in the correct states for a two possible reasons: // Progress isn't always 0 or 1 at the end, the system rounds // If the Navigator is offscreen these values won't be updated // TOOD: Revisit this decision when no longer relying on native navigator. var nextState = { observedTopOfStack: newObservedTopOfStack, makingNavigatorRequest: false, updatingAllIndicesAtOrBeyond: null, progress: 1, toIndex: newObservedTopOfStack, fromIndex: newObservedTopOfStack, }; this.setState(nextState, this._eliminateUnneededChildren); }, _eliminateUnneededChildren: function() { // Updating the indices that we're deleting and that's all. (Truth: Nothing // even uses the indices in this case, but let's make this describe the // truth anyways). var updatingAllIndicesAtOrBeyond = this.state.routeStack.length > this.state.observedTopOfStack + 1 ? this.state.observedTopOfStack + 1 : null; this.setState({ idStack: this.state.idStack.slice(0, this.state.observedTopOfStack + 1), routeStack: this.state.routeStack.slice(0, this.state.observedTopOfStack + 1), // Now we rerequest the top of stack that we observed. requestedTopOfStack: this.state.observedTopOfStack, makingNavigatorRequest: true, updatingAllIndicesAtOrBeyond: updatingAllIndicesAtOrBeyond, }); }, /** * Navigate forward to a new route. * @param route The new route to navigate to. */ push: function(route: Route) { invariant(!!route, 'Must supply route to push'); // Make sure all previous requests are caught up first. Otherwise reject. if (this.state.requestedTopOfStack === this.state.observedTopOfStack) { this._tryLockNavigator(() => { var nextStack = this.state.routeStack.concat([route]); var nextIDStack = this.state.idStack.concat([getuid()]); this.setState({ // We have to make sure that we've also supplied enough views to // satisfy our request to adjust the `requestedTopOfStack`. idStack: nextIDStack, routeStack: nextStack, requestedTopOfStack: nextStack.length - 1, makingNavigatorRequest: true, updatingAllIndicesAtOrBeyond: nextStack.length - 1, }); }); } }, /** * Go back N scenes at once. When N=1, behavior matches `pop()`. * @param n The number of scenes to pop. */ popN: function(n: number) { if (n === 0) { return; } // Make sure all previous requests are caught up first. Otherwise reject. if (this.state.requestedTopOfStack === this.state.observedTopOfStack) { if (this.state.requestedTopOfStack > 0) { this._tryLockNavigator(() => { var newRequestedTopOfStack = this.state.requestedTopOfStack - n; invariant(newRequestedTopOfStack >= 0, 'Cannot pop below 0'); this.setState({ requestedTopOfStack: newRequestedTopOfStack, makingNavigatorRequest: true, updatingAllIndicesAtOrBeyond: this.state.requestedTopOfStack - n, }); }); } } }, /** * Pop back to the previous scene. */ pop: function() { this.popN(1); }, /** * Replace a route in the navigation stack. * * @param route The new route that will replace the specified one. * @param index The route into the stack that should be replaced. * If it is negative, it counts from the back of the stack. */ replaceAtIndex: function(route: Route, index: number) { invariant(!!route, 'Must supply route to replace'); if (index < 0) { index += this.state.routeStack.length; } if (this.state.routeStack.length <= index) { return; } // I don't believe we need to lock for a replace since there's no // navigation actually happening var nextIDStack = this.state.idStack.slice(); var nextRouteStack = this.state.routeStack.slice(); nextIDStack[index] = getuid(); nextRouteStack[index] = route; this.setState({ idStack: nextIDStack, routeStack: nextRouteStack, makingNavigatorRequest: false, updatingAllIndicesAtOrBeyond: index, }); }, /** * Replace the route for the current scene and immediately * load the view for the new route. * @param route The new route to navigate to. */ replace: function(route: Route) { this.replaceAtIndex(route, -1); }, /** * Replace the route/view for the previous scene. * @param route The new route to will replace the previous scene. */ replacePrevious: function(route: Route) { this.replaceAtIndex(route, -2); }, /** * Go back to the topmost item in the navigation stack. */ popToTop: function() { this.popToRoute(this.state.routeStack[0]); }, /** * Go back to the item for a particular route object. * @param route The new route to navigate to. */ popToRoute: function(route: Route) { var indexOfRoute = this.state.routeStack.indexOf(route); invariant( indexOfRoute !== -1, 'Calling pop to route for a route that doesn\'t exist!' ); var numToPop = this.state.routeStack.length - indexOfRoute - 1; this.popN(numToPop); }, /** * Replaces the previous route/view and transitions back to it. * @param route The new route that replaces the previous scene. */ replacePreviousAndPop: function(route: Route) { // Make sure all previous requests are caught up first. Otherwise reject. if (this.state.requestedTopOfStack !== this.state.observedTopOfStack) { return; } if (this.state.routeStack.length < 2) { return; } this._tryLockNavigator(() => { this.replacePrevious(route); this.setState({ requestedTopOfStack: this.state.requestedTopOfStack - 1, makingNavigatorRequest: true, }); }); }, /** * Replaces the top item and pop to it. * @param route The new route that will replace the topmost item. */ resetTo: function(route: Route) { invariant(!!route, 'Must supply route to push'); // Make sure all previous requests are caught up first. Otherwise reject. if (this.state.requestedTopOfStack !== this.state.observedTopOfStack) { return; } this.replaceAtIndex(route, 0); this.popToRoute(route); }, _handleNavigationComplete: function(e: Event) { // Don't propagate to other NavigatorIOS instances this is nested in: e.stopPropagation(); if (this._toFocusOnNavigationComplete) { this._getFocusEmitter().emit('focus', this._toFocusOnNavigationComplete); this._toFocusOnNavigationComplete = null; } this._handleNavigatorStackChanged(e); }, _routeToStackItem: function(routeArg: Route, i: number) { var {component, wrapperStyle, passProps, ...route} = routeArg; var {itemWrapperStyle, ...props} = this.props; var shouldUpdateChild = this.state.updatingAllIndicesAtOrBeyond != null && this.state.updatingAllIndicesAtOrBeyond >= i; var Component = component; return ( <StaticContainer key={'nav' + i} shouldUpdate={shouldUpdateChild}> <RCTNavigatorItem {...props} {...route} style={[ styles.stackItem, itemWrapperStyle, wrapperStyle ]}> <Component navigator={this.navigator} route={route} {...passProps} /> </RCTNavigatorItem> </StaticContainer> ); }, _renderNavigationStackItems: function() { var shouldRecurseToNavigator = this.state.makingNavigatorRequest || this.state.updatingAllIndicesAtOrBeyond !== null; // If not recursing update to navigator at all, may as well avoid // computation of navigator children. var items = shouldRecurseToNavigator ? this.state.routeStack.map(this._routeToStackItem) : null; return ( <StaticContainer shouldUpdate={shouldRecurseToNavigator}> <NavigatorTransitionerIOS ref={TRANSITIONER_REF} style={styles.transitioner} // $FlowFixMe(>=0.41.0) vertical={this.props.vertical} requestedTopOfStack={this.state.requestedTopOfStack} onNavigationComplete={this._handleNavigationComplete} interactivePopGestureEnabled={this.props.interactivePopGestureEnabled}> {items} </NavigatorTransitionerIOS> </StaticContainer> ); }, _tvEventHandler: (undefined: ?TVEventHandler), _enableTVEventHandler: function() { this._tvEventHandler = new TVEventHandler(); this._tvEventHandler.enable(this, function(cmp, evt) { if (evt && evt.eventType === 'menu') { cmp.pop(); } }); }, _disableTVEventHandler: function() { if (this._tvEventHandler) { this._tvEventHandler.disable(); delete this._tvEventHandler; } }, render: function() { return ( // $FlowFixMe(>=0.41.0) <View style={this.props.style}> {this._renderNavigationStackItems()} </View> ); }, });
module.exports = createClass({ displayName: 'React Horizontal Scroll', propTypes: { children: PropTypes.element, className: PropTypes.string, relative: PropTypes.bool }, getInitialState: function () { return { offset: 0, width: 0, height: 0, offsetLeft: 0, offsetTop: 0, scrollLeft: 0, scrollWidth: 0, canScrollLeft: false, canScrollRight: false } }, componentDidMount: function () { const element = ReactDOM.findDOMNode(this) this.setState({ height: window.innerHeight, width: element.offsetWidth, offsetLeft: element.offsetLeft, offsetTop: element.offsetTop }) intervalId = setInterval(function () { this.setScrollState() }.bind(this), 250) element.addEventListener('scroll', this.onScroll) window.addEventListener('resize', this.onResize) }, componentWillUnmount: function () { const element = ReactDOM.findDOMNode(this) if (intervalId) { clearInterval(intervalId) } element.removeEventListener('scroll', this.onScroll) window.removeEventListener('resize', this.onResize) }, componentDidUpdate: function () { const target = ReactDOM.findDOMNode(this) const offset = this.state.offset const position = offset || 0 target.scrollLeft = position }, onScroll: function (event) { event.preventDefault() event.stopPropagation() const offset = event.target.scrollLeft this.setScrollState(offset) }, onResize: function (event) { event.preventDefault() event.stopPropagation() this.setScrollState() }, setScrollState: function (offset) { const element = ReactDOM.findDOMNode(this) const scrollWidth = element.scrollWidth const scrollLeft = this.props.relative ? (element.scrollLeft + 1) : element.scrollLeft let canScrollRight = false if (offset === undefined) { offset = this.state.offset } if (scrollLeft < (element.scrollWidth - element.offsetWidth)) { canScrollRight = true } if (!scrollLeft && !(element.scrollWidth - element.offsetWidth)) { canScrollRight = true } this.setState({ height: window.innerHeight, width: element.offsetWidth, offset: offset, scrollLeft: element.scrollLeft, scrollWidth: scrollWidth, offsetLeft: element.offsetLeft, offsetTop: element.offsetTop, canScrollLeft: offset > 0, canScrollRight: canScrollRight }) }, scrollLeft: function () { const element = ReactDOM.findDOMNode(this) const offset = element.scrollLeft - element.scrollWidth * 0.15 this.setScrollState(offset) }, scrollRight: function () { const element = ReactDOM.findDOMNode(this) const offset = element.scrollLeft + element.scrollWidth * 0.15 this.setScrollState(offset) }, render: function () { const body = document.body let className = 'horizontal-scrolling' const windowInnerHeight = window.innerHeight const relative = this.props.relative || false const offsetTop = this.state.offsetTop const offsetLeft = this.state.offsetLeft const height = this.state.height const width = this.state.width const scrollWidth = this.state.scrollWidth const scrollTop = body.scrollTop const bottom = relative ? (height - scrollTop) : (windowInnerHeight - scrollTop) let top = Math.max(offsetTop, scrollTop) const left = offsetLeft const right = offsetLeft + width - 60 let canScrollLeft = this.state.canScrollLeft let canScrollRight = this.state.canScrollRight top = ((bottom - top - 35) / 2) + top // 70px arrow height if (offsetTop >= windowInnerHeight || offsetTop + height < scrollTop) { canScrollLeft = false canScrollRight = false } if (scrollWidth <= width) { canScrollLeft = false canScrollRight = false } if (this.props.className) { className = sprintf('%s %s', className, this.props.className) } return ( <div className={className}> <Arrow onClick={this.scrollLeft} show={canScrollLeft} top={top} left={left} relative={relative} /> <Arrow onClick={this.scrollRight} show={canScrollRight} top={top} left={right} relative={relative} direction='right' /> {this.props.children} </div> ) } })
const SupplierAdd = createClass({ propTypes: { add: PropTypes.func, cantAdd: PropTypes.func, cancelToggle: PropTypes.func, fetch: PropTypes.func, SupplierAdd: PropTypes.object }, add() { var vals = getFieldValues(this.refs, ['name', 'lon', 'lat', 'description', 'address', 'phone', 'email']) if (Object.keys(vals.incorrect).length === 0) { this.props.add(vals.correct) } else { return this.props.cantAdd(vals.incorrect) } }, componentWillReceiveProps(next) { if (this.props.supplierAdd.open && !next.supplierAdd.open && !next.supplierAdd.canceled) { next.fetch() } }, render() { const actions = [ <FlatButton label={<Translate id='Cancel' />} secondary onTouchTap={this.props.cancelToggle} />, <FlatButton label={<Translate id='Submit' />} primary onTouchTap={this.add} /> ] return ( <Dialog ref='dialog' actions={actions} title={<h3 style={{padding: '24px'}}><Translate id='Supplier add' /></h3>} modal open={this.props.supplierAdd.open}> <TextField ref='name' hintText={<Translate id='Name' />} floatingLabelText={<Translate id='Name' />} errorText={this.props.supplierAdd.fieldError.name} /> <br /> <TextField ref='lon' hintText={<Translate id='Longitude' />} floatingLabelText={<Translate id='Longitude' />} errorText={this.props.supplierAdd.fieldError.lon} /> <TextField ref='lat' hintText={<Translate id='Latitude' />} floatingLabelText={<Translate id='Latitude' />} errorText={this.props.supplierAdd.fieldError.lat} /> <br /> <TextField ref='address' hintText={<Translate id='Address' />} floatingLabelText={<Translate id='Address' />} errorText={this.props.supplierAdd.fieldError.address} /> <TextField ref='phone' hintText={<Translate id='Phone' />} floatingLabelText={<Translate id='Phone' />} errorText={this.props.supplierAdd.fieldError.phone} /> <br /> <TextField ref='email' hintText={<Translate id='Email' />} floatingLabelText={<Translate id='Email' />} errorText={this.props.supplierAdd.fieldError.email} /> <TextField ref='description' hintText={<Translate id='Description' />} floatingLabelText={<Translate id='Description' />} errorText={this.props.supplierAdd.fieldError.description} /> </Dialog> ) } })
const SwipeableRow = createReactClass({ displayName: 'SwipeableRow', _panResponder: {}, _previousLeft: CLOSED_LEFT_POSITION, mixins: [TimerMixin], propTypes: { children: PropTypes.any, isOpen: PropTypes.bool, preventSwipeRight: PropTypes.bool, maxSwipeDistance: PropTypes.number.isRequired, onOpen: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, onSwipeEnd: PropTypes.func.isRequired, onSwipeStart: PropTypes.func.isRequired, // Should bounce the row on mount shouldBounceOnMount: PropTypes.bool, /** * A ReactElement that is unveiled when the user swipes */ slideoutView: PropTypes.node.isRequired, /** * The minimum swipe distance required before fully animating the swipe. If * the user swipes less than this distance, the item will return to its * previous (open/close) position. */ swipeThreshold: PropTypes.number.isRequired, }, getInitialState(): Object { return { currentLeft: new Animated.Value(this._previousLeft), /** * In order to render component A beneath component B, A must be rendered * before B. However, this will cause "flickering", aka we see A briefly * then B. To counter this, _isSwipeableViewRendered flag is used to set * component A to be transparent until component B is loaded. */ isSwipeableViewRendered: false, rowHeight: (null: ?number), }; }, getDefaultProps(): Object { return { isOpen: false, preventSwipeRight: false, maxSwipeDistance: 0, onOpen: emptyFunction, onClose: emptyFunction, onSwipeEnd: emptyFunction, onSwipeStart: emptyFunction, swipeThreshold: 30, }; }, UNSAFE_componentWillMount(): void { this._panResponder = PanResponder.create({ onMoveShouldSetPanResponderCapture: this._handleMoveShouldSetPanResponderCapture, onPanResponderGrant: this._handlePanResponderGrant, onPanResponderMove: this._handlePanResponderMove, onPanResponderRelease: this._handlePanResponderEnd, onPanResponderTerminationRequest: this._onPanResponderTerminationRequest, onPanResponderTerminate: this._handlePanResponderEnd, onShouldBlockNativeResponder: (event, gestureState) => false, }); }, componentDidMount(): void { if (this.props.shouldBounceOnMount) { /** * Do the on mount bounce after a delay because if we animate when other * components are loading, the animation will be laggy */ this.setTimeout(() => { this._animateBounceBack(ON_MOUNT_BOUNCE_DURATION); }, ON_MOUNT_BOUNCE_DELAY); } }, UNSAFE_componentWillReceiveProps(nextProps: Object): void { /** * We do not need an "animateOpen(noCallback)" because this animation is * handled internally by this component. */ if (this.props.isOpen && !nextProps.isOpen) { this._animateToClosedPosition(); } }, render(): React.Element<any> { // The view hidden behind the main view let slideOutView; if (this.state.isSwipeableViewRendered && this.state.rowHeight) { slideOutView = ( <View style={[ styles.slideOutContainer, {height: this.state.rowHeight}, ]}> {this.props.slideoutView} </View> ); } // The swipeable item const swipeableView = ( <Animated.View onLayout={this._onSwipeableViewLayout} style={{transform: [{translateX: this.state.currentLeft}]}}> {this.props.children} </Animated.View> ); return ( <View {...this._panResponder.panHandlers}> {slideOutView} {swipeableView} </View> ); }, close(): void { this.props.onClose(); this._animateToClosedPosition(); }, _onSwipeableViewLayout(event: Object): void { this.setState({ isSwipeableViewRendered: true, rowHeight: event.nativeEvent.layout.height, }); }, _handleMoveShouldSetPanResponderCapture( event: Object, gestureState: Object, ): boolean { // Decides whether a swipe is responded to by this component or its child return gestureState.dy < 10 && this._isValidSwipe(gestureState); }, _handlePanResponderGrant(event: Object, gestureState: Object): void { }, _handlePanResponderMove(event: Object, gestureState: Object): void { if (this._isSwipingExcessivelyRightFromClosedPosition(gestureState)) { return; } this.props.onSwipeStart(); if (this._isSwipingRightFromClosed(gestureState)) { this._swipeSlowSpeed(gestureState); } else { this._swipeFullSpeed(gestureState); } }, _isSwipingRightFromClosed(gestureState: Object): boolean { const gestureStateDx = isRTL() ? -gestureState.dx : gestureState.dx; return this._previousLeft === CLOSED_LEFT_POSITION && gestureStateDx > 0; }, _swipeFullSpeed(gestureState: Object): void { this.state.currentLeft.setValue(this._previousLeft + gestureState.dx); }, _swipeSlowSpeed(gestureState: Object): void { this.state.currentLeft.setValue( this._previousLeft + gestureState.dx / SLOW_SPEED_SWIPE_FACTOR, ); }, _isSwipingExcessivelyRightFromClosedPosition(gestureState: Object): boolean { /** * We want to allow a BIT of right swipe, to allow users to know that * swiping is available, but swiping right does not do anything * functionally. */ const gestureStateDx = isRTL() ? -gestureState.dx : gestureState.dx; return ( this._isSwipingRightFromClosed(gestureState) && gestureStateDx > RIGHT_SWIPE_THRESHOLD ); }, _onPanResponderTerminationRequest( event: Object, gestureState: Object, ): boolean { return false; }, _animateTo( toValue: number, duration: number = SWIPE_DURATION, callback: Function = emptyFunction, ): void { Animated.timing( this.state.currentLeft, { duration, toValue, useNativeDriver: true, }, ).start(() => { this._previousLeft = toValue; callback(); }); }, _animateToOpenPosition(): void { const maxSwipeDistance = isRTL() ? -this.props.maxSwipeDistance : this.props.maxSwipeDistance; this._animateTo(-maxSwipeDistance); }, _animateToOpenPositionWith( speed: number, distMoved: number, ): void { /** * Ensure the speed is at least the set speed threshold to prevent a slow * swiping animation */ speed = ( speed > HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD ? speed : HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD ); /** * Calculate the duration the row should take to swipe the remaining distance * at the same speed the user swiped (or the speed threshold) */ const duration = Math.abs((this.props.maxSwipeDistance - Math.abs(distMoved)) / speed); const maxSwipeDistance = isRTL() ? -this.props.maxSwipeDistance : this.props.maxSwipeDistance; this._animateTo(-maxSwipeDistance, duration); }, _animateToClosedPosition(duration: number = SWIPE_DURATION): void { this._animateTo(CLOSED_LEFT_POSITION, duration); }, _animateToClosedPositionDuringBounce(): void { this._animateToClosedPosition(RIGHT_SWIPE_BOUNCE_BACK_DURATION); }, _animateBounceBack(duration: number): void { /** * When swiping right, we want to bounce back past closed position on release * so users know they should swipe right to get content. */ const swipeBounceBackDistance = isRTL() ? -RIGHT_SWIPE_BOUNCE_BACK_DISTANCE : RIGHT_SWIPE_BOUNCE_BACK_DISTANCE; this._animateTo( -swipeBounceBackDistance, duration, this._animateToClosedPositionDuringBounce, ); }, // Ignore swipes due to user's finger moving slightly when tapping _isValidSwipe(gestureState: Object): boolean { if (this.props.preventSwipeRight && this._previousLeft === CLOSED_LEFT_POSITION && gestureState.dx > 0) { return false; } return Math.abs(gestureState.dx) > HORIZONTAL_SWIPE_DISTANCE_THRESHOLD; }, _shouldAnimateRemainder(gestureState: Object): boolean { /** * If user has swiped past a certain distance, animate the rest of the way * if they let go */ return ( Math.abs(gestureState.dx) > this.props.swipeThreshold || gestureState.vx > HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD ); }, _handlePanResponderEnd(event: Object, gestureState: Object): void { const horizontalDistance = isRTL() ? -gestureState.dx : gestureState.dx; if (this._isSwipingRightFromClosed(gestureState)) { this.props.onOpen(); this._animateBounceBack(RIGHT_SWIPE_BOUNCE_BACK_DURATION); } else if (this._shouldAnimateRemainder(gestureState)) { if (horizontalDistance < 0) { // Swiped left this.props.onOpen(); this._animateToOpenPositionWith(gestureState.vx, horizontalDistance); } else { // Swiped right this.props.onClose(); this._animateToClosedPosition(); } } else { if (this._previousLeft === CLOSED_LEFT_POSITION) { this._animateToClosedPosition(); } else { this._animateToOpenPosition(); } } this.props.onSwipeEnd(); }, });
const classnames = require('classnames'); const React = require('react'); const PropTypes = require('prop-types'); const createReactClass = require('create-react-class'); export default createReactClass({ displayName: 'ButtonGroup', propTypes: { children: PropTypes.node.isRequired, className: PropTypes.string, }, render () { const className = classnames('ButtonGroup', this.props.className); return <div {...this.props} className={className} />; }, });
const LightboxModal = createReactClass({ setupCarousel() { $(this.refs.images).slick({ nextArrow: this.refs.slick_next, prevArrow: this.refs.slick_previous, slidesToShow: 1, slidesToScroll: 1, useCSS: true, cssEase: 'cubic-bezier(.24,.36,0,1)', // adaptiveHeight: true, dots: true, }); }, render() { return ( <Modal isOpen={this.props.isOpen} onRequestClose={this.props.closeModal} onAfterOpen={this.setupCarousel} className="lightbox-modal" overlayClassName="lightbox-modal__overlay modal__overlay" contentLabel="Modal" > <div className="lightbox-modal__image-wrap"> <div ref="images"> {this.props.images.map((image, index) => ( <div key={index} className="lightbox-modal__image" style={{ backgroundImage: `url('${image.url}')` }} /> ))} </div> <button ref="slick_previous" className="button button--icon lightbox-modal__button lightbox-modal__button--left" data-gtm-trigger="PropertyDetail:Lightbox:Previous" > <img alt="Property Detail Lightbox Left" src="/images/property_detail/lightbox-left-icon.svg" /> </button> <button ref="slick_next" className="button button--icon lightbox-modal__button lightbox-modal__button--right" data-gtm-trigger="PropertyDetail:Lightbox:Next" > <img alt="Property Detail Lightbox Right" src="/images/property_detail/lightbox-right-icon.svg" /> </button> <img alt="Property Detail Lightbox Close" onClick={this.props.closeModal} className="lightbox-modal__close" src="/images/search-modal/close-icon.svg" /> </div> </Modal> ); }, });
export default createReactClass({ displayName: 'PrettyTag', propTypes: { onClick: PropTypes.func, classes: PropTypes.object, }, mixins: [HelperMixin], render: function() { return this.renderWithConfig(); }, renderDefault: function() { const classes = cx( _.extend({}, this.props.classes, { 'pretty-part': true }) ); return ( // CodeMirror widgets need some work to make them accessible. // eslint-disable-next-line jsx-a11y/interactive-supports-focus, jsx-a11y/click-events-have-key-events <span className={classes} onClick={this.props.onClick} renderWith={this.renderWith('PrettyTag')} role="button" > {this.props.children} </span> ); }, });
export default createReactClass({ displayName: "Example", mixins: [Highlighter], getInitialState() { return { markdown: null }; }, fetchMarkdownForProps(props) { window.scrollTo(0, 0); const exampleName = props.params.example; const markdownFile = Examples[`${exampleName}_docs`]; fetch(markdownFile) .then(response => { return response.text(); }) .then(markdown => { this.setState({ markdown }); }); }, componentDidMount() { this.fetchMarkdownForProps(this.props); }, componentWillReceiveProps(nextProps) { this.fetchMarkdownForProps(nextProps); }, renderMarkdown() { if (this.state.markdown) { return ( <div className="row"> <div className="col-md-12"> <Markdown source={this.state.markdown} /> </div> </div> ); } else { return ( <div className="row"> <div className="col-md-12">Loading...</div> </div> ); } }, render() { const exampleName = this.props.params.example; const ExampleMetaData = Meta[exampleName]; const Component = Examples[exampleName]; const sourceCode = `https://github.com/esnet/react-timeseries-charts/tree/master/src/website/packages/charts/examples/${exampleName}/Index.js`; return ( <div> <div className="row"> <div className="col-md-12"> <div className="row"> <div className="col-md-12"> <h3>{ExampleMetaData.title}</h3> <p> <a style={{ fontSize: "small" }} href={sourceCode} target="_blank" rel="noopener noreferrer" > Source Code » </a> </p> <p>{ExampleMetaData.description}</p> </div> </div> <hr /> <Component /> <hr /> {this.renderMarkdown()} </div> </div> </div> ); } });
export default createReactClass({ displayName: 'AddItem', mixins: [HelperMixin], getDefaultProps: function() { return { label: '+', }; }, render: function() { return this.renderWithConfig(); }, renderDefault: function() { const tabIndex = this.props.readOnly ? null : 0; const onKeyDown = event => { if (event.keyCode === 13) { this.props.onClick(event); } }; return ( <button className={cx(this.props.classes)} onClick={this.props.onClick} onKeyDown={onKeyDown} renderWith={this.renderWith('AddItem')} tabIndex={tabIndex} > {this.props.label} </button> ); }, });
} else { return obj; } }; var ItemEdit = module.exports.ItemEdit = createReactClass({ render: function() { var context = this.props.context; var title = listing_titles.lookup(context)({context: context}); var url = this.props.context['@id'] + '?frame=edit'; return ( <div className={itemClass(context, 'view-item')}> <header className="row"> <div className="col-sm-12"> <h2>Edit {title}</h2> </div> </header> <fetched.FetchedData loadingComplete={this.props.loadingComplete}> <fetched.Param name="data" url={url} etagName="etag" /> <EditForm {...this.props} /> </fetched.FetchedData> </div> ); } }); var EditForm = module.exports.EditForm = createReactClass({ contextTypes: { fetch: PropTypes.func },
let Overlay = createReactClass({ displayName: 'Overlay', mixins: [ FluxMixin ], //NB: layerContainer and map might be provided as props rather than context (e.g. <Map><GetsProps><GetsContext /></GetsProps></Map> // in which case, we copy those props into context. Props override context. contextTypes: { layerContainer: PropTypes.object, map: PropTypes.object }, propTypes: { addOverlay: PropTypes.func, checked: PropTypes.bool, children: PropTypes.node, layerContainer: PropTypes.object, map: PropTypes.object, name: PropTypes.string, removeLayer: PropTypes.func, removeLayerControl: PropTypes.func }, childContextTypes: { layerContainer: PropTypes.object, map: PropTypes.object }, getDefaultProps() { return { name: 'Overlay' }; }, render() { let {addOverlay, checked, children, name, removeLayer, removeLayerControl} = this.props; children = filterChildren(this, children, ALLOWED_CHILDREN); return ( <LeafletLayersControl.Overlay addOverlay={addOverlay} checked={checked} children={React.Children.only(children)} name={name} removeLayer={removeLayer} removeLayerControl={removeLayerControl} /> ); }, });
"use strict"; var React = require('react'); var createReactClass = require('create-react-class'); var Constants = require('../Constants'); var ExampleHeader = createReactClass({ render() { return ( <div className="exampleHeader"> <div className="exampleControls"> </div> <h1 className="exampleTitle"> <span className="exampleTitleName"> Example: </span> {' '} <a href={this.props.page.file}>{this.props.page.title}</a> </h1> <p className="exampleDescription"> <a className="exampleCode" href={this.props.page.file}>Example code</a> {this.props.page.description} </p> </div> ); } }); module.exports = ExampleHeader;
import jsx from '@/src/jsx'; export default createReactClass({ displayName: 'MoveItemBack', mixins: [HelperMixin], getDefaultProps: function() { return { label: 'â–²', }; }, render: function() { return this.renderWithConfig(); }, renderDefault: function() { return ( <button className={cx(this.props.classes)} onClick={this.props.onClick} renderWith={this.renderWith('MoveItemBack')} tabIndex={0} > {this.props.label} </button> ); }, });
var TaskPageApp = createReactClass({ mixins: [ Reflux.connect(taskStore, "allTasks"), ], getInitialState: function() { return { allTasks: [] }; }, componentDidMount: function () { // Add event listeners in componentDidMount this.listenTo(taskStore, this.updateAllTasks); taskActions.getAllTasks(); }, updateAllTasks: function (updateMessage) { this.setState({allTasks: updateMessage.allTasks}); }, render: function(){ return ( <div> <div> <TaskTable tableData={this.state.allTasks} /> </div> </div> ); } });
import createReactClass from 'create-react-class'; import ScrollableTabBarMixin from './ScrollableTabBarMixin'; import TabBarMixin from './TabBarMixin'; import RefMixin from './RefMixin'; var ScrollableTabBar = createReactClass({ displayName: 'ScrollableTabBar', mixins: [RefMixin, TabBarMixin, ScrollableTabBarMixin], render: function render() { var inkBarNode = this.getInkBarNode(); var tabs = this.getTabs(); var scrollbarNode = this.getScrollBarNode([inkBarNode, tabs]); return this.getRootNode(scrollbarNode); } }); export default ScrollableTabBar;
var Radio = createReactClass({ propTypes: { className: PropTypes.string, disabled: PropTypes.bool, inline: PropTypes.bool, innerRef: PropTypes.func, label: PropTypes.string, }, getRef (ref) { this.target = ref; if (this.props.innerRef) { this.props.innerRef(ref); } }, render () { const componentClass = classNames('Radio', { 'Radio--disabled': this.props.disabled, 'Radio--inline': this.props.inline, }, this.props.className); const props = blacklist(this.props, 'className', 'label'); return ( <label className={componentClass}> <input ref={this.getRef} type="radio" className="Radio__input" {...props} /> {this.props.label && <span className="Radio__label">{this.props.label}</span>} </label> ); }, });
import createReactClass from 'create-react-class'; import cx from 'classnames'; import HelperMixin from '@/src/mixins/helper'; /** @jsx jsx */ import jsx from '@/src/jsx'; export default createReactClass({ displayName: 'Sample', mixins: [HelperMixin], render: function() { return this.renderWithConfig(); }, renderDefault: function() { const choice = this.props.choice; return !choice.sample ? null : ( <div className={cx(this.props.className)} renderWith={this.renderWith('Sample')} > {choice.sample} </div> ); }, });
var TrainersList= createReactClass({ mixins: [FluxMixin, StoreWatchMixin('OrganizationStore')], getDefaultProps: function(){ return { } }, getStateFromFlux: function(){ var flux = this.getFlux(); var store = flux.store('OrganizationStore'); return { loading: store.loading, trainers: store.trainers } }, getInitialState: function(){ return { selectedTrainer: undefined } }, componentWillReceiveProps: function(nextProps){ }, componentDidMount: function(){ }, onClick: function(g){ this.setState({ selectedTrainer: g }); }, onDelete: function(){ this.setState({ selectedTrainer: undefined }); }, onUpdate: function(){ }, getSelectedTrainerContent: function(){ var trainer = this.state.selectedTrainer; return ( <div> <TrainerPanel trainerId={trainer.id} onDelete={this.onDelete} onUpdate={this.onUpdate} /> </div> ); }, componentStyle: { placeholder: { }, listPlaceholder: { //textAlign: 'center', //minHeight: 150 }, item: { display: 'inline-block', verticalAlign: 'top', //backgroundColor: 'white', //border: '1px solid rgb(239, 240, 241)', //borderRadius: 3, //padding: 7, margin: 5, cursor: 'pointer' }, dialogPanelStyle: { width: 800, padding: 10 } }, onClick: function(u){ this.setState({ selectedTrainer: u }); }, render: function(){ var trainers = this.state.trainers; return ( <div style={this.componentStyle.placeholder} > <div style={this.componentStyle.listPlaceholder}> {trainers.map(function(u, k){ var key = 'trainer_' + k + '_' + u.id; var onClick = this.onClick.bind(this, u); return ( <div style={this.componentStyle.item} onClick={onClick} key={key} > <TrainersItem trainerId={u.id} /> </div> ); }, this)} </div> {this.state.selectedTrainer == undefined ? null : <Dialog onClose={this.setState.bind(this, {selectedTrainer: undefined})} level={100} content={this.getSelectedTrainerContent()} dialogPanelStyle={this.componentStyle.dialogPanelStyle} /> } </div> ); } });
const TextInput = createReactClass({ displayName: 'TextInput', statics: { /* TODO(brentvatne) docs are needed for this */ State: TextInputState, }, propTypes: { ...ViewPropTypes, /** * Can tell `TextInput` to automatically capitalize certain characters. * * - `characters`: all characters. * - `words`: first letter of each word. * - `sentences`: first letter of each sentence (*default*). * - `none`: don't auto capitalize anything. */ autoCapitalize: PropTypes.oneOf([ 'none', 'sentences', 'words', 'characters', ]), /** * If `false`, disables auto-correct. The default value is `true`. */ autoCorrect: PropTypes.bool, /** * If `false`, disables spell-check style (i.e. red underlines). * The default value is inherited from `autoCorrect`. * @platform ios */ spellCheck: PropTypes.bool, /** * If `true`, focuses the input on `componentDidMount`. * The default value is `false`. */ autoFocus: PropTypes.bool, /** * If true, will increase the height of the textbox if need be. If false, * the textbox will become scrollable once the height is reached. The * default value is false. * @platform android */ autoGrow: PropTypes.bool, /** * Specifies whether fonts should scale to respect Text Size accessibility settings. The * default is `true`. */ allowFontScaling: PropTypes.bool, /** * If `false`, text is not editable. The default value is `true`. */ editable: PropTypes.bool, /** * Determines which keyboard to open, e.g.`numeric`. * * The following values work across platforms: * * - `default` * - `numeric` * - `email-address` * - `phone-pad` * * *iOS Only* * * The following values work on iOS only: * * - `ascii-capable` * - `numbers-and-punctuation` * - `url` * - `number-pad` * - `name-phone-pad` * - `decimal-pad` * - `twitter` * - `web-search` * * *Android Only* * * The following values work on Android only: * * - `visible-password` */ keyboardType: PropTypes.oneOf([ // Cross-platform 'default', 'email-address', 'numeric', 'phone-pad', // iOS-only 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', // Android-only 'visible-password', ]), /** * Determines the color of the keyboard. * @platform ios */ keyboardAppearance: PropTypes.oneOf([ 'default', 'light', 'dark', ]), /** * Determines how the return key should look. On Android you can also use * `returnKeyLabel`. * * *Cross platform* * * The following values work across platforms: * * - `done` * - `go` * - `next` * - `search` * - `send` * * *Android Only* * * The following values work on Android only: * * - `none` * - `previous` * * *iOS Only* * * The following values work on iOS only: * * - `default` * - `emergency-call` * - `google` * - `join` * - `route` * - `yahoo` */ returnKeyType: PropTypes.oneOf([ // Cross-platform 'done', 'go', 'next', 'search', 'send', // Android-only 'none', 'previous', // iOS-only 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo', ]), /** * Sets the return key to the label. Use it instead of `returnKeyType`. * @platform android */ returnKeyLabel: PropTypes.string, /** * Limits the maximum number of characters that can be entered. Use this * instead of implementing the logic in JS to avoid flicker. */ maxLength: PropTypes.number, /** * If autogrow is `true`, limits the height that the TextInput box can grow * to. Once it reaches this height, the TextInput becomes scrollable. */ maxHeight: PropTypes.number, /** * Sets the number of lines for a `TextInput`. Use it with multiline set to * `true` to be able to fill the lines. * @platform android */ numberOfLines: PropTypes.number, /** * When `false`, if there is a small amount of space available around a text input * (e.g. landscape orientation on a phone), the OS may choose to have the user edit * the text inside of a full screen text input mode. When `true`, this feature is * disabled and users will always edit the text directly inside of the text input. * Defaults to `false`. * @platform android */ disableFullscreenUI: PropTypes.bool, /** * If `true`, the keyboard disables the return key when there is no text and * automatically enables it when there is text. The default value is `false`. * @platform ios */ enablesReturnKeyAutomatically: PropTypes.bool, /** * If `true`, the text input can be multiple lines. * The default value is `false`. */ multiline: PropTypes.bool, /** * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` * The default value is `simple`. * @platform android */ textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']), /** * Callback that is called when the text input is blurred. */ onBlur: PropTypes.func, /** * Callback that is called when the text input is focused. */ onFocus: PropTypes.func, /** * Callback that is called when the text input's text changes. */ onChange: PropTypes.func, /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText: PropTypes.func, /** * Callback that is called when the text input's content size changes. * This will be called with * `{ nativeEvent: { contentSize: { width, height } } }`. * * Only called for multiline text inputs. */ onContentSizeChange: PropTypes.func, /** * Callback that is called when text input ends. */ onEndEditing: PropTypes.func, /** * Callback that is called when the text input selection is changed. * This will be called with * `{ nativeEvent: { selection: { start, end } } }`. */ onSelectionChange: PropTypes.func, /** * Callback that is called when the text input's submit button is pressed. * Invalid if `multiline={true}` is specified. */ onSubmitEditing: PropTypes.func, /** * Callback that is called when a key is pressed. * This will be called with `{ nativeEvent: { key: keyValue } }` * where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and * the typed-in character otherwise including `' '` for space. * Fires before `onChange` callbacks. * @platform ios */ onKeyPress: PropTypes.func, /** * Invoked on mount and layout changes with `{x, y, width, height}`. */ onLayout: PropTypes.func, /** * Invoked on content scroll with `{ nativeEvent: { contentOffset: { x, y } } }`. * May also contain other properties from ScrollEvent but on Android contentSize * is not provided for performance reasons. */ onScroll: PropTypes.func, /** * The string that will be rendered before text input has been entered. */ placeholder: PropTypes.string, /** * The text color of the placeholder string. */ placeholderTextColor: ColorPropType, /** * If `true`, the text input obscures the text entered so that sensitive text * like passwords stay secure. The default value is `false`. Does not work with 'multiline={true}'. */ secureTextEntry: PropTypes.bool, /** * The highlight and cursor color of the text input. */ selectionColor: ColorPropType, /** * An instance of `DocumentSelectionState`, this is some state that is responsible for * maintaining selection information for a document. * * Some functionality that can be performed with this instance is: * * - `blur()` * - `focus()` * - `update()` * * > You can reference `DocumentSelectionState` in * > [`vendor/document/selection/DocumentSelectionState.js`](https://github.com/facebook/react-native/blob/master/Libraries/vendor/document/selection/DocumentSelectionState.js) * * @platform ios */ selectionState: PropTypes.instanceOf(DocumentSelectionState), /** * The start and end of the text input's selection. Set start and end to * the same value to position the cursor. */ selection: PropTypes.shape({ start: PropTypes.number.isRequired, end: PropTypes.number, }), /** * The value to show for the text input. `TextInput` is a controlled * component, which means the native value will be forced to match this * value prop if provided. For most uses, this works great, but in some * cases this may cause flickering - one common cause is preventing edits * by keeping value the same. In addition to simply setting the same value, * either set `editable={false}`, or set/update `maxLength` to prevent * unwanted edits without flicker. */ value: PropTypes.string, /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you do not want to deal with listening * to events and updating the value prop to keep the controlled state in sync. */ defaultValue: PropTypes.string, /** * When the clear button should appear on the right side of the text view. * @platform ios */ clearButtonMode: PropTypes.oneOf([ 'never', 'while-editing', 'unless-editing', 'always', ]), /** * If `true`, clears the text field automatically when editing begins. * @platform ios */ clearTextOnFocus: PropTypes.bool, /** * If `true`, all text will automatically be selected on focus. */ selectTextOnFocus: PropTypes.bool, /** * If `true`, the text field will blur when submitted. * The default value is true for single-line fields and false for * multiline fields. Note that for multiline fields, setting `blurOnSubmit` * to `true` means that pressing return will blur the field and trigger the * `onSubmitEditing` event instead of inserting a newline into the field. */ blurOnSubmit: PropTypes.bool, /** * Note that not all Text styles are supported, an incomplete list of what is not supported includes: * * - `borderLeftWidth` * - `borderTopWidth` * - `borderRightWidth` * - `borderBottomWidth` * - `borderTopLeftRadius` * - `borderTopRightRadius` * - `borderBottomRightRadius` * - `borderBottomLeftRadius` * * see [Issue#7070](https://github.com/facebook/react-native/issues/7070) * for more detail. * * [Styles](docs/style.html) */ style: Text.propTypes.style, /** * The color of the `TextInput` underline. * @platform android */ underlineColorAndroid: ColorPropType, /** * If defined, the provided image resource will be rendered on the left. * The image resource must be inside `/android/app/src/main/res/drawable` and referenced * like * ``` * <TextInput * inlineImageLeft='search_icon' * /> * ``` * @platform android */ inlineImageLeft: PropTypes.string, /** * Padding between the inline image, if any, and the text input itself. * @platform android */ inlineImagePadding: PropTypes.number, /** * Determines the types of data converted to clickable URLs in the text input. * Only valid if `multiline={true}` and `editable={false}`. * By default no data types are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * If `true`, caret is hidden. The default value is `false`. */ caretHidden: PropTypes.bool, }, getDefaultProps(): Object { return { allowFontScaling: true, }; }, /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ mixins: [NativeMethodsMixin, TimerMixin], getInitialState: function() { return {layoutHeight: this._layoutHeight}; }, /** * Returns `true` if the input is currently focused; `false` otherwise. */ isFocused: function(): boolean { return TextInputState.currentlyFocusedField() === ReactNative.findNodeHandle(this._inputRef); }, contextTypes: { onFocusRequested: PropTypes.func, focusEmitter: PropTypes.instanceOf(EventEmitter), }, _inputRef: (undefined: any), _focusSubscription: (undefined: ?Function), _lastNativeText: (undefined: ?string), _lastNativeSelection: (undefined: ?Selection), _layoutHeight: (-1: number), componentDidMount: function() { this._lastNativeText = this.props.value; if (!this.context.focusEmitter) { if (this.props.autoFocus) { this.requestAnimationFrame(this.focus); } return; } this._focusSubscription = this.context.focusEmitter.addListener( 'focus', (el) => { if (this === el) { this.requestAnimationFrame(this.focus); } else if (this.isFocused()) { this.blur(); } } ); if (this.props.autoFocus) { this.context.onFocusRequested(this); } }, componentWillUnmount: function() { this._focusSubscription && this._focusSubscription.remove(); if (this.isFocused()) { this.blur(); } }, getChildContext: function(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: PropTypes.bool }, /** * Removes all text from the `TextInput`. */ clear: function() { this.setNativeProps({text: ''}); }, render: function() { if (Platform.OS === 'ios') { return this._renderIOS(); } else if (Platform.OS === 'android') { return this._renderAndroid(); } }, _getText: function(): ?string { return typeof this.props.value === 'string' ? this.props.value : ( typeof this.props.defaultValue === 'string' ? this.props.defaultValue : '' ); }, _setNativeRef: function(ref: any) { this._inputRef = ref; }, _renderIOS: function() { var textContainer; var props = Object.assign({}, this.props); props.style = [this.props.style]; if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } if (!props.multiline) { if (__DEV__) { for (var propKey in onlyMultiline) { if (props[propKey]) { const error = new Error( 'TextInput prop `' + propKey + '` is only supported with multiline.' ); warning(false, '%s', error.stack); } } } textContainer = <RCTTextField ref={this._setNativeRef} {...props} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} />; } else { var children = props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(props.value && childCount), 'Cannot specify both value and children.' ); if (childCount >= 1) { children = <Text style={props.style} allowFontScaling={props.allowFontScaling}>{children}</Text>; } if (props.inputView) { children = [children, props.inputView]; } props.style.unshift(styles.multilineInput); textContainer = <RCTTextView ref={this._setNativeRef} {...props} children={children} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onContentSizeChange={this.props.onContentSizeChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} dataDetectorTypes={this.props.dataDetectorTypes} onScroll={this._onScroll} />; } return ( <TouchableWithoutFeedback onLayout={props.onLayout} onPress={this._onPress} rejectResponderTermination={true} accessible={props.accessible} accessibilityLabel={props.accessibilityLabel} accessibilityTraits={props.accessibilityTraits} nativeID={this.props.nativeID} testID={props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _renderAndroid: function() { const props = Object.assign({}, this.props); props.style = this.props.style; if (this.state.layoutHeight >= 0) { props.style = [props.style, {height: this.state.layoutHeight}]; } props.autoCapitalize = UIManager.AndroidTextInput.Constants.AutoCapitalizationType[ props.autoCapitalize || 'sentences' ]; /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment * suppresses an error when upgrading Flow's support for React. To see the * error delete this comment and run Flow. */ var children = this.props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(this.props.value && childCount), 'Cannot specify both value and children.' ); if (childCount > 1) { children = <Text>{children}</Text>; } if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } const textContainer = <AndroidTextInput ref={this._setNativeRef} {...props} mostRecentEventCount={0} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onContentSizeChange={this._onContentSizeChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} text={this._getText()} children={children} disableFullscreenUI={this.props.disableFullscreenUI} textBreakStrategy={this.props.textBreakStrategy} onScroll={this._onScroll} />; return ( <TouchableWithoutFeedback onLayout={this._onLayout} onPress={this._onPress} accessible={this.props.accessible} accessibilityLabel={this.props.accessibilityLabel} accessibilityComponentType={this.props.accessibilityComponentType} nativeID={this.props.nativeID} testID={this.props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _onFocus: function(event: Event) { if (this.props.onFocus) { this.props.onFocus(event); } if (this.props.selectionState) { this.props.selectionState.focus(); } }, _onPress: function(event: Event) { if (this.props.editable || this.props.editable === undefined) { this.focus(); } }, _onChange: function(event: Event) { // Make sure to fire the mostRecentEventCount first so it is already set on // native when the text value is set. if (this._inputRef) { this._inputRef.setNativeProps({ mostRecentEventCount: event.nativeEvent.eventCount, }); } var text = event.nativeEvent.text; this.props.onChange && this.props.onChange(event); this.props.onChangeText && this.props.onChangeText(text); if (!this._inputRef) { // calling `this.props.onChange` or `this.props.onChangeText` // may clean up the input itself. Exits here. return; } this._lastNativeText = text; this.forceUpdate(); }, _onContentSizeChange: function(event: Event) { let contentHeight = event.nativeEvent.contentSize.height; if (this.props.autoGrow) { if (this.props.maxHeight) { contentHeight = Math.min(this.props.maxHeight, contentHeight); } this.setState({layoutHeight: Math.max(this._layoutHeight, contentHeight)}); } this.props.onContentSizeChange && this.props.onContentSizeChange(event); }, _onLayout: function(event: Event) { const height = event.nativeEvent.layout.height; if (height) { this._layoutHeight = event.nativeEvent.layout.height; } this.props.onLayout && this.props.onLayout(event); }, _onSelectionChange: function(event: Event) { this.props.onSelectionChange && this.props.onSelectionChange(event); if (!this._inputRef) { // calling `this.props.onSelectionChange` // may clean up the input itself. Exits here. return; } this._lastNativeSelection = event.nativeEvent.selection; if (this.props.selection || this.props.selectionState) { this.forceUpdate(); } }, componentDidUpdate: function () { // This is necessary in case native updates the text and JS decides // that the update should be ignored and we should stick with the value // that we have in JS. const nativeProps = {}; if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') { nativeProps.text = this.props.value; } // Selection is also a controlled prop, if the native value doesn't match // JS, update to the JS value. const {selection} = this.props; if (this._lastNativeSelection && selection && (this._lastNativeSelection.start !== selection.start || this._lastNativeSelection.end !== selection.end)) { nativeProps.selection = this.props.selection; } if (Object.keys(nativeProps).length > 0 && this._inputRef) { this._inputRef.setNativeProps(nativeProps); } if (this.props.selectionState && selection) { this.props.selectionState.update(selection.start, selection.end); } }, _onBlur: function(event: Event) { this.blur(); if (this.props.onBlur) { this.props.onBlur(event); } if (this.props.selectionState) { this.props.selectionState.blur(); } }, _onTextInput: function(event: Event) { /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment * suppresses an error when upgrading Flow's support for React. To see the * error delete this comment and run Flow. */ this.props.onTextInput && this.props.onTextInput(event); }, _onScroll: function(event: Event) { this.props.onScroll && this.props.onScroll(event); }, });
var React = require("react"); var PropTypes = require('prop-types'); var createReactClass = require('create-react-class'); var ChecklistItem = createReactClass({ propTypes: { value: PropTypes.any, label: PropTypes.string }, handleCheckToggle: function() { this.props.onChange(this.props.value); }, render: function() { var checkBoxId = String(this.props.value) + "-" + String(this.props.label); return ( <li className="rcm-checklist-item" onClick={this.handleCheckToggle}> <input id={checkBoxId} type="checkbox" checked={this.props.checked} readOnly="true"/><label>{this.props.label}</label> </li> ); } }); module.exports = ChecklistItem;
const TouchableBounce = createReactClass({ displayName: 'TouchableBounce', mixins: [Touchable.Mixin, NativeMethodsMixin], propTypes: { /** * When true, indicates that the view is an accessibility element. By default, * all the touchable elements are accessible. */ accessible: PropTypes.bool, onPress: PropTypes.func, onPressIn: PropTypes.func, onPressOut: PropTypes.func, // The function passed takes a callback to start the animation which should // be run after this onPress handler is done. You can use this (for example) // to update UI before starting the animation. onPressWithCompletion: PropTypes.func, // the function passed is called after the animation is complete onPressAnimationComplete: PropTypes.func, /** * When the scroll view is disabled, this defines how far your touch may * move off of the button, before deactivating the button. Once deactivated, * try moving it back and you'll see that the button is once again * reactivated! Move it back and forth several times while the scroll view * is disabled. Ensure you pass in a constant to reduce memory allocations. */ pressRetentionOffset: EdgeInsetsPropType, /** * This defines how far your touch can start away from the button. This is * added to `pressRetentionOffset` when moving off of the button. * ** NOTE ** * The touch area never extends past the parent view bounds and the Z-index * of sibling views always takes precedence if a touch hits two overlapping * views. */ hitSlop: EdgeInsetsPropType, releaseVelocity: PropTypes.number.isRequired, releaseBounciness: PropTypes.number.isRequired, }, getDefaultProps: function() { return {releaseBounciness: 10, releaseVelocity: 10}; }, getInitialState: function(): State { return { ...this.touchableGetInitialState(), scale: new Animated.Value(1), }; }, bounceTo: function( value: number, velocity: number, bounciness: number, callback?: ?Function, ) { Animated.spring(this.state.scale, { toValue: value, velocity, bounciness, useNativeDriver: true, }).start(callback); }, /** * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are * defined on your component. */ touchableHandleActivePressIn: function(e: Event) { this.bounceTo(0.93, 0.1, 0); this.props.onPressIn && this.props.onPressIn(e); }, touchableHandleActivePressOut: function(e: Event) { this.bounceTo(1, 0.4, 0); this.props.onPressOut && this.props.onPressOut(e); }, touchableHandlePress: function(e: Event) { const onPressWithCompletion = this.props.onPressWithCompletion; if (onPressWithCompletion) { onPressWithCompletion(() => { this.state.scale.setValue(0.93); this.bounceTo( 1, this.props.releaseVelocity, this.props.releaseBounciness, this.props.onPressAnimationComplete, ); }); return; } this.bounceTo( 1, this.props.releaseVelocity, this.props.releaseBounciness, this.props.onPressAnimationComplete, ); this.props.onPress && this.props.onPress(e); }, touchableGetPressRectOffset: function(): typeof PRESS_RETENTION_OFFSET { return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET; }, touchableGetHitSlop: function(): ?Object { return this.props.hitSlop; }, touchableGetHighlightDelayMS: function(): number { return 0; }, render: function(): React.Element<any> { return ( <Animated.View /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This * comment suppresses an error when upgrading Flow's support for React. * To see the error delete this comment and run Flow. */ style={[{transform: [{scale: this.state.scale}]}, this.props.style]} accessible={this.props.accessible !== false} /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This * comment suppresses an error when upgrading Flow's support for React. * To see the error delete this comment and run Flow. */ accessibilityLabel={this.props.accessibilityLabel} /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This * comment suppresses an error when upgrading Flow's support for React. * To see the error delete this comment and run Flow. */ accessibilityComponentType={this.props.accessibilityComponentType} /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This * comment suppresses an error when upgrading Flow's support for React. * To see the error delete this comment and run Flow. */ accessibilityTraits={this.props.accessibilityTraits} /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This * comment suppresses an error when upgrading Flow's support for React. * To see the error delete this comment and run Flow. */ nativeID={this.props.nativeID} /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This * comment suppresses an error when upgrading Flow's support for React. * To see the error delete this comment and run Flow. */ testID={this.props.testID} hitSlop={this.props.hitSlop} onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder} onResponderTerminationRequest={ this.touchableHandleResponderTerminationRequest } onResponderGrant={this.touchableHandleResponderGrant} onResponderMove={this.touchableHandleResponderMove} onResponderRelease={this.touchableHandleResponderRelease} onResponderTerminate={this.touchableHandleResponderTerminate}> { // $FlowFixMe(>=0.41.0) this.props.children } {Touchable.renderDebugView({ color: 'orange', hitSlop: this.props.hitSlop, })} </Animated.View> ); }, });
const ProductAdd = createClass({ propTypes: { add: PropTypes.func, cantAdd: PropTypes.func, cancelToggle: PropTypes.func, fetchProducts: PropTypes.func, filesForUpload: PropTypes.array, uploadedList: PropTypes.array, uploadRequestId: PropTypes.number, productAdd: PropTypes.object }, componentWillReceiveProps(next) { if (this.props.productAdd.open && !next.productAdd.open && !next.productAdd.canceled) { next.fetchProducts() } if (next.uploadedList.length && next.uploadRequestId !== this.props.uploadRequestId) { // fire add action after successfully upload var vals = getFieldValues(this.refs, ['name', 'category', 'supplier', 'description', 'barcode', 'price', 'quantityTypeId', 'articleNum']) this.props.add(Object.assign({}, vals.correct, {files: next.uploadedList})) } }, add() { var vals = getFieldValues(this.refs, ['name', 'category', 'supplier', 'description', 'barcode', 'price', 'quantityTypeId', 'articleNum']) if (Object.keys(vals.incorrect).length === 0) { if (this.props.filesForUpload.length) { this.props.upload(this.props.filesForUpload) } else { this.props.add(vals.correct) } } else { return this.props.cantAdd(vals.incorrect) } }, render() { const actions = [ <FlatButton label={<Translate id='Cancel' />} secondary onTouchTap={this.props.cancelToggle} />, <FlatButton label={<Translate id='Submit' />} primary onTouchTap={this.add} /> ] return ( <Dialog actions={actions} title={<h3 style={{padding: '24px'}}><Translate id='Product add' /></h3>} modal open={this.props.productAdd.open}> <TextField ref='name' hintText={<Translate id='Product name' />} floatingLabelText={<Translate id='Product name' />} errorText={this.props.productAdd.fieldError.name} /> <TextField ref='price' hintText={<Translate id='Price' />} floatingLabelText={<Translate id='Price' />} errorText={this.props.productAdd.fieldError.price} /><br /> <TextField ref='description' hintText={<Translate id='Product description' />} floatingLabelText={<Translate id='Product description' />} errorText={this.props.productAdd.fieldError.description} /> <TextField ref='barcode' hintText={<Translate id='Product Bar code' />} floatingLabelText={<Translate id='Product Bar code' />} errorText={this.props.productAdd.fieldError.barcode} /><br /> <TextField ref='articleNum' hintText={<Translate id='Product Article Number' />} floatingLabelText={<Translate id='Product Article Number' />} errorText={(this.props.productAdd.fieldError && this.props.productAdd.fieldError.articleNum) || ''} /> <ProductCatDropDown ref='category' value={1} /> <SupplierDropDown ref='supplier' value={1} /> <QuantityType ref='quantityTypeId' value={1} /><br /> <hr /> <Upload /> </Dialog> ) } })
import React from 'react'; import createReactClass from 'create-react-class'; import PureRenderMixin from 'mixins/PureRenderMixin'; let CustomExample = createReactClass({ displayName: 'CustomExample', mixins: [PureRenderMixin], render() { return ( <div> CUSTOM COMPONENT EXAMPLE </div> ); }, }); export default CustomExample;
export default createReactClass({ displayName: 'ScrollLock', componentDidMount() { this.scrollLock(); }, shouldComponentUpdate: shouldPureComponentUpdate, componentDidUpdate() { this.scrollLock(); }, componentWillUnmount() { this.scrollRelease(); }, cancelScrollEvent(event) { event.stopImmediatePropagation(); event.preventDefault(); event.returnValue = false; return false; }, scrollLock() { const domNode = ReactDOM.findDOMNode(this); if (domNode) { domNode.addEventListener('wheel', this.onScrollHandler, false); } }, scrollRelease() { const domNode = ReactDOM.findDOMNode(this); if (domNode) { domNode.removeEventListener('wheel', this.onScrollHandler, false); } }, onScrollHandler(event) { const domNode = ReactDOM.findDOMNode(this); const scrollTop = domNode.scrollTop; const scrollHeight = domNode.scrollHeight; const height = domNode.clientHeight; const wheelDelta = event.deltaY; const isDeltaPositive = wheelDelta > 0; if (scrollHeight === height) { return true; } if (isDeltaPositive && wheelDelta > scrollHeight - height - scrollTop) { domNode.scrollTop = scrollHeight; return this.cancelScrollEvent(event); } else if (!isDeltaPositive && -wheelDelta > scrollTop) { domNode.scrollTop = 0; return this.cancelScrollEvent(event); } }, render() { return this.props.children; } });
const SegmentedControlIOS = createReactClass({ displayName: 'SegmentedControlIOS', mixins: [NativeMethodsMixin], propTypes: { ...DeprecatedViewPropTypes, /** * The labels for the control's segment buttons, in order. */ values: PropTypes.arrayOf(PropTypes.string), /** * The index in `props.values` of the segment to be (pre)selected. */ selectedIndex: PropTypes.number, /** * Callback that is called when the user taps a segment; * passes the segment's value as an argument */ onValueChange: PropTypes.func, /** * Callback that is called when the user taps a segment; * passes the event as an argument */ onChange: PropTypes.func, /** * If false the user won't be able to interact with the control. * Default value is true. */ enabled: PropTypes.bool, /** * Accent color of the control. */ tintColor: PropTypes.string, /** * If true, then selecting a segment won't persist visually. * The `onValueChange` callback will still work as expected. */ momentary: PropTypes.bool, }, getDefaultProps: function(): DefaultProps { return { values: [], enabled: true, }; }, _onChange: function(event: Event) { this.props.onChange && this.props.onChange(event); this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value); }, render: function() { return ( <RCTSegmentedControl {...this.props} ref={SEGMENTED_CONTROL_REFERENCE} style={[styles.segmentedControl, this.props.style]} onChange={this._onChange} /> ); }, });
const ActivityIndicator = ((createReactClass({ displayName: 'ActivityIndicator', mixins: [NativeMethodsMixin], propTypes: { ...ViewPropTypes, /** * Whether to show the indicator (true, the default) or hide it (false). * * See http://facebook.github.io/react-native/docs/activityindicator.html#animating */ animating: PropTypes.bool, /** * The foreground color of the spinner (default is gray). * * See http://facebook.github.io/react-native/docs/activityindicator.html#color */ color: ColorPropType, /** * Size of the indicator (default is 'small'). * Passing a number to the size prop is only supported on Android. * * See http://facebook.github.io/react-native/docs/activityindicator.html#size */ size: PropTypes.oneOfType([ PropTypes.oneOf(['small', 'large']), PropTypes.number, ]), /** * Whether the indicator should hide when not animating (true by default). * * @platform ios * * See http://facebook.github.io/react-native/docs/activityindicator.html#hideswhenstopped */ hidesWhenStopped: PropTypes.bool, }, getDefaultProps(): DefaultProps { return { animating: true, color: Platform.OS === 'ios' ? GRAY : null, hidesWhenStopped: true, size: 'small', }; }, render() { const {onLayout, style, ...props} = this.props; let sizeStyle; switch (props.size) { case 'small': sizeStyle = styles.sizeSmall; break; case 'large': sizeStyle = styles.sizeLarge; break; default: sizeStyle = {height: props.size, width: props.size}; break; } const nativeProps = { ...props, style: sizeStyle, styleAttr: 'Normal', indeterminate: true, }; return ( <View onLayout={onLayout} style={[styles.container, style]}> {Platform.OS === 'ios' ? ( <RCTActivityIndicator {...nativeProps} /> ) : ( <ProgressBarAndroid {...nativeProps} /> )} </View> ); }, }): any): React.ComponentType<Props>);
var StatesField = createReactClass({ displayName: 'StatesField', propTypes: { label: PropTypes.string, searchable: PropTypes.bool, }, getDefaultProps () { return { label: 'States:', searchable: true, }; }, getInitialState () { return { country: 'AU', disabled: false, searchable: this.props.searchable, selectValue: 'new-south-wales', clearable: true, }; }, switchCountry (e) { var newCountry = e.target.value; console.log('Country changed to ' + newCountry); this.setState({ country: newCountry, selectValue: null }); }, updateValue (newValue) { console.log('State changed to ' + newValue); this.setState({ selectValue: newValue }); }, focusStateSelect () { this.refs.stateSelect.focus(); }, toggleCheckbox (e) { let newState = {}; newState[e.target.name] = e.target.checked; this.setState(newState); }, render () { var options = STATES[this.state.country]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select ref="stateSelect" autofocus options={options} simpleValue clearable={this.state.clearable} name="selected-state" disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} /> <div style={{ marginTop: 14 }}> <button type="button" onClick={this.focusStateSelect}>Focus Select</button> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Searchable</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Disabled</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="clearable" checked={this.state.clearable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Clearable</span> </label> </div> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/> <span className="checkbox-label">Australia</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/> <span className="checkbox-label">United States</span> </label> </div> </div> ); } });