code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
render() { const currentValue = this._getCurrentValue(); const tabIndex = !this.props.disabled ? this.props.tabIndex : -1; let characterStyle = { ...style.characterStyle, ...this.props.characterStyle, }; if (this.state.isActive) { characterStyle = { ...characterStyle, ...style.activeCharacterStyle, ...this.props.activeCharacterStyle, }; } else if (this.state.isHover) { characterStyle = { ...characterStyle, ...style.hoverCharacterStyle, ...this.props.hoverCharacterStyle, }; } let wrapperStyle = { ...style.style, ...this.props.style, }; if (this.props.disabled) { wrapperStyle = { ...wrapperStyle, ...style.disabledStyle, ...this.props.disabledStyle, }; if (this.state.isHover) { wrapperStyle = { ...wrapperStyle, ...style.disabledHoverStyle, ...this.props.disabledHoverStyle, }; } } else { if (this.state.isFocus && this.preventFocusStyleForTouchAndClick) { wrapperStyle = { ...wrapperStyle, ...style.focusStyle, ...this.props.focusStyle, }; } if (this.state.isHover) { wrapperStyle = { ...wrapperStyle, ...style.hoverStyle, ...this.props.hoverStyle, }; } } return ( <div ref="wrapper" style={ wrapperStyle } className={ unionClassNames(this.props.className, this.ratingWrapperStyleId) } onKeyDown={ this._onKeyDown } onMouseEnter={ this._onMouseEnter } onMouseMove={ this._onMouseMove } onMouseLeave={ this._onMouseLeave } onMouseUp={ this._onMouseUp } onMouseDown={ this._onMouseDown } onTouchStart={ this._onTouchStart } onTouchMove={ this._onTouchMove } onTouchEnd={ this._onTouchEnd } onTouchCancel={ this._onTouchCancel } onContextMenu={ this._onContextMenu } onBlur={ this._onBlur } onFocus={ this._onFocus } tabIndex={ tabIndex } aria-label = { this.props['aria-label'] } aria-valuemax = { 5 } aria-valuemin = { 1 } aria-valuenow = { this.state.value } aria-disabled = { this.props.disabled } {...this.state.wrapperProps} > { React.Children.map([1, 2, 3, 4, 5], (value) => { const ratingStyle = (currentValue >= value) ? characterStyle : {}; return ( <span data-belle-value= { value } style={ ratingStyle } {...this.state.characterProps} > { this.props.character } </span> ); }) } </div> ); }
Returns the HTML function to be rendered by this component.
render
javascript
nikgraf/belle
src/components/Rating.js
https://github.com/nikgraf/belle/blob/master/src/components/Rating.js
MIT
function isPlaceholder(reactElement) { return isComponentOfType(Placeholder, reactElement); }
Returns true if the provided property is a Placeholder component from Belle.
isPlaceholder
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
function isOption(reactElement) { return isComponentOfType(Option, reactElement); }
Returns true if the provided property is a Option component from Belle.
isOption
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
function isSeparator(reactElement) { return isComponentOfType(Separator, reactElement); }
Returns true if the provided property is a Separator component from Belle.
isSeparator
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
function validateChildrenAreOptionsAndMaximumOnePlaceholder(props, propName, componentName) { const validChildren = filterReactChildren(props[propName], (node) => ( (isOption(node) || isSeparator(node) || isPlaceholder(node)) )); if (React.Children.count(props[propName]) !== React.Children.count(validChildren)) { return new Error(`Invalid children supplied to \`${componentName}\`, expected an Option, Separator or Placeholder component from Belle.`); } const placeholders = filterReactChildren(props[propName], (node) => isPlaceholder(node)); if (React.Children.count(placeholders) > 1) { return new Error(`Invalid children supplied to \`${componentName}\`, expected only one Placeholder component.`); } return undefined; }
Verifies that the children is an array containing only Options & at maximum one Placeholder.
validateChildrenAreOptionsAndMaximumOnePlaceholder
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
function updatePseudoClassStyle(styleId, properties) { const hoverStyle = { ...style.hoverStyle, ...properties.hoverStyle, }; const disabledHoverStyle = { ...style.disabledHoverStyle, ...properties.disabledHoverStyle, }; const styles = [ { id: styleId, style: hoverStyle, pseudoClass: 'hover', }, { id: styleId, style: disabledHoverStyle, pseudoClass: 'hover', disabled: true, }, ]; injectStyles(styles); }
Update hover style for the speficied styleId. @param styleId {string} - a unique id that exists as class attribute in the DOM @param properties {object} - the components properties optionally containing hoverStyle
updatePseudoClassStyle
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
function sanitizeSelectedOptionWrapperProps(properties) { return omit(properties, Object.keys(selectPropTypes)); }
Returns an object with properties that are relevant for the wrapping div of the selected option.
sanitizeSelectedOptionWrapperProps
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
function sanitizeWrapperProps(properties) { return omit(properties, [ 'style', 'ref', 'tabIndex', 'onKeyDown', 'onBlur', 'onFocus', ]); }
Returns an object with properties that are relevant for the wrapping div of the selected option.
sanitizeWrapperProps
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
function sanitizeMenuProps(properties) { return omit(properties, [ 'style', 'ref', 'aria-labelledby', 'role', ]); }
Returns an object with properties that are relevant for the wrapping div of the selected option.
sanitizeMenuProps
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
function sanitizeCaretProps(properties) { return omit(properties, [ 'style', 'ref', ]); }
Returns an object with properties that are relevant for the wrapping div of the selected option.
sanitizeCaretProps
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
constructor(properties) { super(properties); let selectedValue; let focusedOptionValue; if (properties.children) { this.children = flattenReactChildren(properties.children); this.options = filter(this.children, isOption); } if (has(properties, 'valueLink')) { selectedValue = properties.valueLink.value; focusedOptionValue = selectedValue; } else if (has(properties, 'value')) { selectedValue = properties.value; focusedOptionValue = selectedValue; } else if (has(properties, 'defaultValue')) { selectedValue = properties.defaultValue; focusedOptionValue = selectedValue; } else if (!isEmpty(this.children) && !some(this.children, isPlaceholder)) { const firstOption = first(this.options); selectedValue = firstOption ? firstOption.props.value : void 0; focusedOptionValue = selectedValue; } else if (!isEmpty(this.children)) { const firstOption = first(this.options); focusedOptionValue = firstOption ? firstOption.props.value : void 0; } this.state = { isOpen: false, isFocused: false, selectedValue, focusedOptionValue, selectedOptionWrapperProps: sanitizeSelectedOptionWrapperProps(properties), wrapperProps: sanitizeWrapperProps(properties.wrapperProps), menuProps: sanitizeMenuProps(properties.menuProps), caretProps: sanitizeCaretProps(properties.caretProps), isTouchedToToggle: false, }; }
Select component. In its simplest form the select component behaves almost identical to the native HTML select which the exception that it comes with beautiful styles. Example: <Select defaultValue="rome"> <Option value="vienna">Vienna</Option> <Option value="rome">Rome</Option> </Select> For more advanced examples please see: nikgraf.github.io/belle/#/component/select This component was inpired by: - Jet Watson: https://github.com/JedWatson/react-select - Instructure React Team: https://github.com/instructure-react/react-select-box
constructor
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
getChildContext() { return { isDisabled: this.props.disabled, isHoveredValue: this.state.focusedOptionValue, }; }
Select component. In its simplest form the select component behaves almost identical to the native HTML select which the exception that it comes with beautiful styles. Example: <Select defaultValue="rome"> <Option value="vienna">Vienna</Option> <Option value="rome">Rome</Option> </Select> For more advanced examples please see: nikgraf.github.io/belle/#/component/select This component was inpired by: - Jet Watson: https://github.com/JedWatson/react-select - Instructure React Team: https://github.com/instructure-react/react-select-box
getChildContext
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
componentWillMount() { const id = uniqueId(); // Note: To ensure server side rendering creates the same results React's internal // id for this element is leveraged. this.selectedOptionWrapperId = this.props.id ? this.props.id : `belle-select-id-${id}`; this._styleId = `style-id${id}`; updatePseudoClassStyle(this._styleId, this.props); if (canUseDOM) { this.mouseUpOnDocumentCallback = this._onMouseUpOnDocument; document.addEventListener('mouseup', this.mouseUpOnDocumentCallback); } }
Generates the style-id & inject the focus & hover style.
componentWillMount
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
componentWillReceiveProps(properties) { if (properties.children) { this.children = flattenReactChildren(properties.children); this.options = filter(this.children, isOption); } const newState = { selectedOptionWrapperProps: sanitizeSelectedOptionWrapperProps(properties), wrapperProps: sanitizeWrapperProps(properties.wrapperProps), menuProps: sanitizeMenuProps(properties.menuProps), caretProps: sanitizeCaretProps(properties.caretProps), }; if (has(properties, 'valueLink')) { newState.selectedValue = properties.valueLink.value; newState.focusedOptionValue = properties.valueLink.value; } else if (has(properties, 'value')) { newState.selectedValue = properties.value; newState.focusedOptionValue = properties.value; } this.setState(newState); removeStyle(this._styleId); updatePseudoClassStyle(this._styleId, properties); }
Generates the style-id & inject the focus & hover style.
componentWillReceiveProps
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
componentWillUpdate(nextProperties, nextState) { const shouldPositionOptions = has(nextProperties, 'shouldPositionOptions') ? nextProperties.shouldPositionOptions : config.shouldPositionOptions; if (shouldPositionOptions) { const menuNode = ReactDOM.findDOMNode(this.refs.menu); this.cachedMenuScrollTop = menuNode.scrollTop; if (!this.state.isOpen && nextState.isOpen) { menuNode.style.display = 'none'; } } }
In case shouldPositionOptions is active the scrollTop position is stored to be applied later on. The menu is hidden to make sure it is not displayed beofre repositioned.
componentWillUpdate
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
componentDidUpdate(previousProperties, previousState) { const shouldPositionOptions = has(this.props, 'shouldPositionOptions') ? this.props.shouldPositionOptions : config.shouldPositionOptions; if (shouldPositionOptions && !this.props.disabled) { const menuNode = ReactDOM.findDOMNode(this.refs.menu); // the menu was just opened if (!previousState.isOpen && this.state.isOpen && this.children && this.children.length > 0) { const positionOptions = has(this.props, 'positionOptions') ? this.props.positionOptions : config.positionOptions; positionOptions(this); // restore the old scrollTop position } else { menuNode.scrollTop = this.cachedMenuScrollTop; } const separators = filter(this.children, isSeparator); const childrenPresent = !isEmpty(this.options) || !isEmpty(separators); if (!previousState.isOpen && this.state.isOpen && childrenPresent) { const menuStyle = { ...style.menuStyle, ...this.props.menuStyle, }; menuNode.style.display = menuStyle.display; } } }
In case shouldPositionOptions is active when opening the menu it is repositioned & switched to be visible.
componentDidUpdate
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
componentWillUnmount() { removeStyle(this._styleId); if (canUseDOM) { document.removeEventListener('mouseup', this.mouseUpOnDocumentCallback); } }
Remove a component's associated styles whenever it gets removed from the DOM.
componentWillUnmount
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
_getIndexOfFocusedOption() { return findIndex(this.options, (element) => ( element.props.value === this.state.focusedOptionValue )); }
Returns the index of the entry with a certain value from the component's children. The index search includes only option components.
_getIndexOfFocusedOption
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
_getValueForIndex(index) { return this.options[index].props.value; }
Returns the value of the child with a certain index.
_getValueForIndex
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
_triggerChange(value) { if (has(this.props, 'valueLink')) { this.props.valueLink.requestChange(value); this.setState({ isOpen: false, }); } else if (has(this.props, 'value')) { this.setState({ isOpen: false, }); } else { this.setState({ focusedOptionValue: value, selectedValue: value, isOpen: false, }); } if (this.props.onUpdate) { this.props.onUpdate({ value }); } }
After an option has been selected the menu gets closed and the selection processed. Depending on the component's properties the value gets updated and the provided change callback for onUpdate or valueLink is called.
_triggerChange
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
_renderChildren() { let optionsIndex = 0; return ( React.Children.map(this.children, (entry, index) => { if (isOption(entry)) { // filter out all non-Option Components const localOptionIndex = optionsIndex; const isHovered = entry.props.value === this.state.focusedOptionValue; const element = ( <SelectItem onItemClick={ this._onClickAtOption } onItemTouchStart={ this._onTouchStartAtOption } onItemTouchMove={ this._onTouchMoveAtOption } onItemTouchEnd={ this._onTouchEndAtOption } onItemTouchCancel={ this._onTouchCancelAtOption } onItemMouseEnter={ this._onMouseEnterAtOption } isHovered={ isHovered } index={localOptionIndex} key={ index } > { entry } </SelectItem> ); optionsIndex++; return element; } else if (isSeparator(entry)) { return ( <li key={ index } role="presentation" > { entry } </li> ); } return null; }) ); }
After an option has been selected the menu gets closed and the selection processed. Depending on the component's properties the value gets updated and the provided change callback for onUpdate or valueLink is called.
_renderChildren
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
render() { const defaultStyle = { ...style.style, ...this.props.style, }; const hoverStyle = { ...defaultStyle, ...style.hoverStyle, ...this.props.hoverStyle, }; const focusStyle = { ...defaultStyle, ...style.focusStyle, ...this.props.focusStyle, }; const activeStyle = { ...defaultStyle, ...style.activeStyle, ...this.props.activeStyle, }; const disabledStyle = { ...defaultStyle, ...style.disabledStyle, ...this.props.disabledStyle, }; const disabledHoverStyle = { ...disabledStyle, ...style.disabledHoverStyle, ...this.props.disabledHoverStyle, }; const menuStyle = { ...style.menuStyle, ...this.props.menuStyle, }; const caretToCloseStyle = { ...style.caretToCloseStyle, ...this.props.caretToCloseStyle, }; const caretToOpenStyle = { ...style.caretToOpenStyle, ...this.props.caretToOpenStyle, }; const disabledCaretToOpenStyle = { ...caretToOpenStyle, ...style.disabledCaretToOpenStyle, ...this.props.disabledCaretToOpenStyle, }; const wrapperStyle = { ...style.wrapperStyle, ...this.props.wrapperStyle, }; let selectedOptionOrPlaceholder; if (this.state.selectedValue !== void 0) { const selectedEntry = find(this.children, (entry) => ( entry.props.value === this.state.selectedValue )); if (selectedEntry) { selectedOptionOrPlaceholder = React.cloneElement(selectedEntry, { _isDisplayedAsSelected: true, }); } } else { selectedOptionOrPlaceholder = find(this.children, isPlaceholder); } const separators = filter(this.children, isSeparator); const childrenNotPresent = isEmpty(this.options) && isEmpty(separators); const computedMenuStyle = this.props.disabled || !this.state.isOpen || childrenNotPresent ? { display: 'none' } : menuStyle; const hasCustomTabIndex = this.props.wrapperProps && this.props.wrapperProps.tabIndex; let tabIndex = hasCustomTabIndex ? this.props.wrapperProps.tabIndex : '0'; let selectedOptionWrapperStyle; if (this.props.disabled) { if (this.state.isTouchedToToggle) { selectedOptionWrapperStyle = disabledHoverStyle; } else { selectedOptionWrapperStyle = disabledStyle; } tabIndex = -1; } else { if (this.state.isActive) { selectedOptionWrapperStyle = activeStyle; } else if (this.state.isFocused) { selectedOptionWrapperStyle = focusStyle; } else if (this.state.isTouchedToToggle) { selectedOptionWrapperStyle = hoverStyle; } else { selectedOptionWrapperStyle = defaultStyle; } } let caretStyle; if (this.props.disabled) { caretStyle = disabledCaretToOpenStyle; } else if (this.state.isOpen) { caretStyle = caretToCloseStyle; } else { caretStyle = caretToOpenStyle; } return ( <div style={ wrapperStyle } tabIndex={ tabIndex } onKeyDown={ this._onKeyDown } onBlur={ this._onBlur } onFocus={ this._onFocus } ref="wrapper" {...this.state.wrapperProps} > <div onClick={ this._onClickToggleMenu } onTouchStart={ this._onTouchStartToggleMenu } onTouchEnd={ this._onTouchEndToggleMenu } onTouchCancel={ this._onTouchCancelToggleMenu } onContextMenu={ this._onContextMenu } onMouseDown = { this._onMouseDown } onMouseUp = { this._onMouseUp } style={ selectedOptionWrapperStyle } className={ unionClassNames(this.props.className, this._styleId) } ref="selectedOptionWrapper" role="button" aria-expanded={ this.state.isOpen } id={ this.selectedOptionWrapperId } {...this.state.selectedOptionWrapperProps} > { selectedOptionOrPlaceholder } <span style={ caretStyle } {...this.state.caretProps} /> </div> <ul style={ computedMenuStyle } role="listbox" aria-labelledby={ this.selectedOptionWrapperId } ref="menu" {...this.state.menuProps} > { this._renderChildren() } </ul> </div> ); }
After an option has been selected the menu gets closed and the selection processed. Depending on the component's properties the value gets updated and the provided change callback for onUpdate or valueLink is called.
render
javascript
nikgraf/belle
src/components/Select.js
https://github.com/nikgraf/belle/blob/master/src/components/Select.js
MIT
render() { return ( <li onMouseDown={ this._onClick } onTouchStart={ this._onTouchStart } onTouchMove={ this._onTouchMove } onTouchEnd={ this._onTouchEnd } onTouchCancel={ this._onTouchCancel } onMouseEnter={ this._onMouseEnter } role="option" aria-selected={ this.props.isHovered } > { this.props.children } </li> ); }
Belle internal component to wrap an Option in a Select. This component exists to avoid binding functions in JSX.
render
javascript
nikgraf/belle
src/components/SelectItem.js
https://github.com/nikgraf/belle/blob/master/src/components/SelectItem.js
MIT
function sanitizeChildProps(properties) { return omit(properties, Object.keys(separatorPropTypes)); }
Returns an object with properties that are relevant for the wrapping div.
sanitizeChildProps
javascript
nikgraf/belle
src/components/Separator.js
https://github.com/nikgraf/belle/blob/master/src/components/Separator.js
MIT
constructor(properties) { super(properties); this.state = { childProps: sanitizeChildProps(properties), }; }
Separator component. This component should be used together with Belle's Select.
constructor
javascript
nikgraf/belle
src/components/Separator.js
https://github.com/nikgraf/belle/blob/master/src/components/Separator.js
MIT
componentWillReceiveProps(properties) { this.setState({ childProps: sanitizeChildProps(properties) }); }
Update the childProperties based on the updated properties passed to the Separator.
componentWillReceiveProps
javascript
nikgraf/belle
src/components/Separator.js
https://github.com/nikgraf/belle/blob/master/src/components/Separator.js
MIT
render() { const computedStyle = { ...style.style, ...this.props.style, }; return ( <div style={ computedStyle } {...this.state.childProps}> { this.props.children } </div> ); }
Update the childProperties based on the updated properties passed to the Separator.
render
javascript
nikgraf/belle
src/components/Separator.js
https://github.com/nikgraf/belle/blob/master/src/components/Separator.js
MIT
render() { const { style, characterProps, characterStyle, ...childProps } = this.props; const computedCharStyle = { ...spinnerStyle.characterStyle, ...characterStyle }; return ( <span {...childProps} style={{ ...spinnerStyle.style, ...style }}> <span {...characterProps} style={ computedCharStyle }> . </span> <span {...characterProps} style={{ ...computedCharStyle, ...animationDelay('400ms') }}> . </span> <span {...characterProps} style={{ ...computedCharStyle, ...animationDelay('800ms') }}> . </span> </span> ); }
Spinner component to be used as loading indicator.
render
javascript
nikgraf/belle
src/components/Spinner.js
https://github.com/nikgraf/belle/blob/master/src/components/Spinner.js
MIT
function sanitizeChildProps(properties) { const childProps = omit(properties, Object.keys(textInputPropTypes)); if (typeof properties.valueLink === 'object') { childProps.value = properties.valueLink.value; } return childProps; }
Returns an object with properties that are relevant for the TextInput's textarea. As the height of the textarea needs to be calculated valueLink can not be passed down to the textarea, but made available through this component.
sanitizeChildProps
javascript
nikgraf/belle
src/components/TextInput.js
https://github.com/nikgraf/belle/blob/master/src/components/TextInput.js
MIT
function updatePseudoClassStyle(styleId, properties) { const hoverStyle = { ...style.hoverStyle, ...properties.hoverStyle, }; const focusStyle = { ...style.focusStyle, ...properties.focusStyle, }; const disabledHoverStyle = { ...style.disabledHoverStyle, ...properties.disabledHoverStyle, }; const styles = [ { id: styleId, style: hoverStyle, pseudoClass: 'hover', }, { id: styleId, style: focusStyle, pseudoClass: 'focus', }, { id: styleId, style: disabledHoverStyle, pseudoClass: 'hover', disabled: true, }, ]; injectStyles(styles); }
Update hover & focus style for the speficied styleId. @param styleId {string} - a unique id that exists as class attribute in the DOM @param properties {object} - the components properties optionally containing hoverStyle & focusStyle
updatePseudoClassStyle
javascript
nikgraf/belle
src/components/TextInput.js
https://github.com/nikgraf/belle/blob/master/src/components/TextInput.js
MIT
constructor(properties) { super(properties); let inputValue; if (has(properties, 'valueLink')) { inputValue = properties.valueLink.value; } else if (has(properties, 'value')) { inputValue = properties.value; } else if (has(properties, 'defaultValue')) { inputValue = properties.defaultValue; } this.state = { height: 'auto', inputValue, }; this.textareaProps = sanitizeChildProps(properties); }
TextInput component with great UX like autogrowing & handling states Note on styling: Right now this component doen't allow to change style after initialisation. Note on resizing: If you fill a textarea only with spaces and the cursor reaches the right end it won't break the line. This leads to unexpected behaviour for the automatic resizing. This component was highly inspired by the great work from these guys - Andrey Popp: https://github.com/andreypopp/react-textarea-autosize - Eugene: https://gist.github.com/eugene1g/5dbaa7d35d0c7d5c2c56
constructor
javascript
nikgraf/belle
src/components/TextInput.js
https://github.com/nikgraf/belle/blob/master/src/components/TextInput.js
MIT
componentWillMount() { const id = uniqueId(); this._styleId = `style-id${id}`; updatePseudoClassStyle(this._styleId, this.props); }
Generates the style-id & inject the focus & hover style.
componentWillMount
javascript
nikgraf/belle
src/components/TextInput.js
https://github.com/nikgraf/belle/blob/master/src/components/TextInput.js
MIT
componentWillReceiveProps(properties) { // Makes sure we have inputValue available when triggering a resize. const newState = { inputValue: this.state.inputValue, }; if (has(properties, 'valueLink')) { newState.inputValue = properties.valueLink.value; } else if (has(properties, 'value')) { newState.inputValue = properties.value; } this.textareaProps = sanitizeChildProps(properties); removeStyle(this._styleId); updatePseudoClassStyle(this._styleId, properties); this.setState(newState, () => this._triggerResize(newState.inputValue)); }
Update the properties passed to the textarea and resize as with the new properties the height might have changed.
componentWillReceiveProps
javascript
nikgraf/belle
src/components/TextInput.js
https://github.com/nikgraf/belle/blob/master/src/components/TextInput.js
MIT
_triggerResize(textareaValue) { const height = calculateTextareaHeight(ReactDOM.findDOMNode(this), textareaValue, this.props.minRows, this.props.maxRows, this.props.minHeight, this.props.maxHeight); this.setState({ height }); }
Calculate the height and store the new height in the state to trigger a render.
_triggerResize
javascript
nikgraf/belle
src/components/TextInput.js
https://github.com/nikgraf/belle/blob/master/src/components/TextInput.js
MIT
render() { let textareaStyle = { ...style.style, ...this.props.style, }; if (this.props.disabled) { textareaStyle = { ...textareaStyle, ...style.disabledStyle, ...this.props.disabledStyle, }; } textareaStyle.height = this.state.height; return ( <textarea style={ textareaStyle } value = {this.state.inputValue} className={ unionClassNames(this.props.className, this._styleId) } onChange={ this._onChange } onKeyDown={ this._onKeyDown } disabled={ this.props.disabled } { ...this.textareaProps } /> ); }
Calculate the height and store the new height in the state to trigger a render.
render
javascript
nikgraf/belle
src/components/TextInput.js
https://github.com/nikgraf/belle/blob/master/src/components/TextInput.js
MIT
function validateChoices(props, propName, componentName) { const propValue = props[propName]; if (!propValue) { return undefined; } if (!Array.isArray(propValue) || propValue.length !== 2) { return new Error(`Invalid ${propName} supplied to \`${componentName}\`, expected exactly two Choice components.`); } for (let i = 0; i < propValue.length; ++i) { const item = propValue[i]; if (!item || !isComponentOfType(Choice, item)) { return new Error(`Invalid ${propName}[${i}] supplied to \`${componentName}\`, expected a Choice component from Belle.`); } } if (first(propValue).props.value === last(propValue).props.value) { return new Error(`Invalid ${propName} supplied to \`${componentName}\`, expected different value properties for the provided Choice components.`); } return undefined; }
Verifies that the children is an array containing only two choices with a different value.
validateChoices
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
function sanitizeChildProps(properties) { return omit(properties, Object.keys(togglePropTypes)); }
Verifies that the children is an array containing only two choices with a different value.
sanitizeChildProps
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
function sanitizeSliderProps(properties) { return omit(properties, [ 'style', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel', ]); }
Verifies that the children is an array containing only two choices with a different value.
sanitizeSliderProps
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
function sanitizeSliderWrapperProps(properties) { return omit(properties, [ 'ref', 'style', ]); }
Verifies that the children is an array containing only two choices with a different value.
sanitizeSliderWrapperProps
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
function sanitizeChoiceProps(properties) { return omit(properties, [ 'ref', 'style', ]); }
Verifies that the children is an array containing only two choices with a different value.
sanitizeChoiceProps
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
function sanitizeHandleProps(properties) { return omit(properties, [ 'onMouseDown', 'onMouseMove', 'onMouseUp', 'onMouseLeave', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel', 'ref', 'style', ]); }
Verifies that the children is an array containing only two choices with a different value.
sanitizeHandleProps
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
function updatePseudoClassStyle(styleId, properties, preventFocusStyleForTouchAndClick) { let focusStyle; if (preventFocusStyleForTouchAndClick) { focusStyle = { outline: 0 }; } else { focusStyle = { ...style.focusStyle, ...properties.focusStyle, }; } const styles = [ { id: styleId, style: focusStyle, pseudoClass: 'focus', }, ]; injectStyles(styles); }
Update focus style for the speficied styleId. @param styleId {string} - a unique id that exists as class attribute in the DOM @param properties {object} - the components properties optionally containing custom styles
updatePseudoClassStyle
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
componentWillMount() { const id = uniqueId(); this.styleId = `style-id${id}`; updatePseudoClassStyle(this.styleId, this.props, this.preventFocusStyleForTouchAndClick); }
Generates the style-id & inject the focus style.
componentWillMount
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
componentWillReceiveProps(properties) { const newState = { firstChoiceProps: sanitizeChoiceProps(properties.firstChoiceProps), childProps: sanitizeChildProps(properties), secondChoiceProps: sanitizeChoiceProps(properties.secondChoiceProps), handleProps: sanitizeHandleProps(properties.handleProps), sliderProps: sanitizeSliderProps(properties.sliderProps), sliderWrapperProps: sanitizeSliderWrapperProps(properties.sliderWrapperProps), }; if (has(properties, 'valueLink')) { newState.value = properties.valueLink.value; } else if (has(properties, 'value')) { newState.value = properties.value; } this.setState(newState); this.preventFocusStyleForTouchAndClick = has(properties, 'preventFocusStyleForTouchAndClick') ? properties.preventFocusStyleForTouchAndClick : config.preventFocusStyleForTouchAndClick; removeStyle(this.styleId); updatePseudoClassStyle(this.styleId, properties, this.preventFocusStyleForTouchAndClick); }
Generates the style-id & inject the focus style.
componentWillReceiveProps
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
componentDidUpdate() { this.isFocused = false; }
Deactivate the focused attribute in order to make sure the focus animation only runs once when the component is focused on & not after re-rendering e.g when the user clicks on the toggle.
componentDidUpdate
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
_onArrowLeftKeyDown() { if (this.state.value === true) { this._triggerChange(false); } }
Flip value in case it is false.
_onArrowLeftKeyDown
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
_onArrowRightKeyDown() { if (this.state.value === false) { this._triggerChange(true); } }
Flip value in case it is true.
_onArrowRightKeyDown
javascript
nikgraf/belle
src/components/Toggle.js
https://github.com/nikgraf/belle/blob/master/src/components/Toggle.js
MIT
findIndexOfSelectedOption = (component) => { const filterFunction = (child) => (isComponentOfType(Option, child) || isComponentOfType(Separator, child)); return findIndex(filterReactChildren( component.props.children, filterFunction), (element) => (element.props.value === component.state.selectedValue) ); }
Returns the index of the entry with a certain value from the component's children. The index search includes separator & option components.
findIndexOfSelectedOption
javascript
nikgraf/belle
src/config/select.js
https://github.com/nikgraf/belle/blob/master/src/config/select.js
MIT
findIndexOfSelectedOption = (component) => { const filterFunction = (child) => (isComponentOfType(Option, child) || isComponentOfType(Separator, child)); return findIndex(filterReactChildren( component.props.children, filterFunction), (element) => (element.props.value === component.state.selectedValue) ); }
Returns the index of the entry with a certain value from the component's children. The index search includes separator & option components.
findIndexOfSelectedOption
javascript
nikgraf/belle
src/config/select.js
https://github.com/nikgraf/belle/blob/master/src/config/select.js
MIT
positionOptions(selectComponent) { const menuNode = ReactDOM.findDOMNode(selectComponent.refs.menu); const menuStyle = window.getComputedStyle(menuNode, null); const menuWidth = parseFloat(menuStyle.getPropertyValue('width')); // In case of a placeholder no option is focused on initially let optionIndex; if (selectComponent.state.selectedValue) { optionIndex = findIndexOfSelectedOption(selectComponent); } else { optionIndex = 0; } const option = menuNode.childNodes[optionIndex]; const menuHeight = parseFloat(menuStyle.getPropertyValue('height')); const menuTopBorderWidth = parseFloat(menuStyle.getPropertyValue('border-top-width')); // In order to work with legacy browsers the second paramter for pseudoClass // has to be provided http://caniuse.com/#feat=getcomputedstyle const optionStyle = window.getComputedStyle(option.childNodes[0], null); const optionPaddingTop = parseFloat(optionStyle.getPropertyValue('padding-top')); const optionPaddingLeft = parseFloat(optionStyle.getPropertyValue('padding-top')); const selectedOptionWrapperNode = ReactDOM.findDOMNode(selectComponent.refs.selectedOptionWrapper); const selectedOptionWrapperStyle = window.getComputedStyle(selectedOptionWrapperNode, null); const selectedOptionWrapperPaddingTop = parseFloat(selectedOptionWrapperStyle.getPropertyValue('padding-top')); const newTop = option.offsetTop + optionPaddingTop - selectedOptionWrapperPaddingTop + menuTopBorderWidth; const newLeft = option.offsetLeft + optionPaddingLeft; // Top positioning if (menuHeight < menuNode.scrollHeight) { if (newTop + menuHeight > menuNode.scrollHeight) { // In case scrolling is not enough the box needs to be moved more to // the top to match the same position. const maxScrollTop = menuNode.scrollHeight - menuHeight; menuNode.scrollTop = maxScrollTop; menuNode.style.top = `-${newTop - maxScrollTop}px`; } else { // In case it's the first entry scrolling is not used to respect the // menu's paddingTop. if (optionIndex === 0) { menuNode.scrollTop = 0; menuNode.style.top = `-${newTop}px`; } else { menuNode.scrollTop = newTop; } } } else { menuNode.style.top = `-${newTop}px`; } // Left positioning menuNode.style.left = `-${newLeft}px`; // Increasing the width // // Pro: // - It gives a option in the menu the same width // as in the selectedOptionWrapper. // - There is space to keep the text of the option on the exact same pixel // when opening. The menu is symetric in relation to the // selectedOptionWrapper. // // Con: // - Adding the padding could cause issue with design as it gets wider than // the original field. menuNode.style.width = `${menuWidth + newLeft * 2}px`; }
Repositions to the menu to position the focusedOption right on top of the selected one. @param selectComponent {object} - the Select component itself accessible with `this`
positionOptions
javascript
nikgraf/belle
src/config/select.js
https://github.com/nikgraf/belle/blob/master/src/config/select.js
MIT
function calculateStyling(node) { const reactId = node.getAttribute('data-reactid'); // calculate the computed style only once it's not in the cache if (!computedStyleCache[reactId]) { // In order to work with legacy browsers the second paramter for pseudoClass // has to be provided http://caniuse.com/#feat=getcomputedstyle const computedStyle = window.getComputedStyle(node, null); const boxSizing = ( computedStyle.getPropertyValue('box-sizing') || computedStyle.getPropertyValue('-moz-box-sizing') || computedStyle.getPropertyValue('-webkit-box-sizing') ); let verticalPaddingSize = 0; verticalPaddingSize = ( parseFloat(computedStyle.getPropertyValue('padding-bottom')) + parseFloat(computedStyle.getPropertyValue('padding-top')) ); let verticalBorderSize = 0; verticalBorderSize = ( parseFloat(computedStyle.getPropertyValue('border-bottom-width')) + parseFloat(computedStyle.getPropertyValue('border-top-width')) ); const sizingStyle = stylesToCopy .map(styleName => `${styleName}:${computedStyle.getPropertyValue(styleName)} !important`) .join(';'); // store the style, vertical padding size, vertical border size and // boxSizing inside the cache computedStyleCache[reactId] = { style: sizingStyle, verticalPaddingSize, verticalBorderSize, boxSizing, }; } return computedStyleCache[reactId]; }
Returns an object containing the computed style and the combined vertical padding size, combined vertical border size and box-sizing value. This style is returned as string to be applied as attribute of an element.
calculateStyling
javascript
nikgraf/belle
src/utils/calculate-textarea-height.js
https://github.com/nikgraf/belle/blob/master/src/utils/calculate-textarea-height.js
MIT
function calculateTextareaHeight(textareaElement, textareaValue = '-', minRows = null, maxRows = null, minHeight = null, maxHeight = null) { // Regarding textareaValue: IE will return a height of 0 in case the textare is empty. // To prevent reducing the size to 0 we simply use a dummy text. if (!canUseDOM) { return 0; } if (!hiddenTextarea) { hiddenTextarea = document.createElement('textarea'); document.body.appendChild(hiddenTextarea); hiddenTextarea.setAttribute('class', 'belle-input-helper'); } const { style, verticalPaddingSize, verticalBorderSize, boxSizing } = calculateStyling(textareaElement); hiddenTextarea.setAttribute('style', `${style};${hiddenTextareaStyle}`); hiddenTextarea.value = textareaValue; let calculatedMinHeight; let calculatedMaxHeight; let height = hiddenTextarea.scrollHeight; // for a textarea with border-box, the border width has to be added while // for content-box it's necessary to subtract the padding if (boxSizing === 'border-box') { // border-box: content + padding + border height = height + verticalBorderSize; } else if (boxSizing === 'content-box') { // content-box: content height = height - verticalPaddingSize; } if (minRows !== null && minHeight === null || maxRows !== null && maxHeight === null) { // measure height of a textarea with a single row hiddenTextarea.value = '-'; const singleRowHeight = hiddenTextarea.scrollHeight - verticalPaddingSize; if (minRows !== null && minHeight === null) { calculatedMinHeight = singleRowHeight * minRows; if (boxSizing === 'border-box') { calculatedMinHeight = calculatedMinHeight + verticalPaddingSize + verticalBorderSize; } } if (maxRows !== null && maxHeight === null) { calculatedMaxHeight = singleRowHeight * maxRows; if (boxSizing === 'border-box') { calculatedMaxHeight = calculatedMaxHeight + verticalPaddingSize + verticalBorderSize; } } } const finalMinHeight = minHeight || calculatedMinHeight; if (finalMinHeight) { height = Math.max(finalMinHeight, height); } const finalMaxHeight = maxHeight || calculatedMaxHeight; if (finalMaxHeight) { height = Math.min(finalMaxHeight, height); } return height; }
Returns an object containing height of the textare as if all the content would be visible. The minHeight & maxHeight are in the object as well and are based on minRows & maxRows. In order to improve the performance a hidden textarea is added to the DOM and used for further caluculations. In addition the styling of each textarea is cached to improve performance.
calculateTextareaHeight
javascript
nikgraf/belle
src/utils/calculate-textarea-height.js
https://github.com/nikgraf/belle/blob/master/src/utils/calculate-textarea-height.js
MIT
getWeekArrayForMonth = (month, year, firstDayOfWeek) => { const monthDay = new Date(year, month, 1); // Todo: simplify this calculation of first date let firstDate = (1 + firstDayOfWeek) - monthDay.getDay(); firstDate = firstDate <= 1 ? firstDate : firstDate - 7; monthDay.setDate(firstDate); const lastDate = new Date(year, month + 1, 0); const weekArray = []; while (monthDay <= lastDate) { const newWeek = []; for (let dayCounter = 0; dayCounter < 7; dayCounter++) { const weekDate = new Date(monthDay.getFullYear(), monthDay.getMonth(), monthDay.getDate()); newWeek.push(weekDate); monthDay.setDate(monthDay.getDate() + 1); } weekArray.push(newWeek); } return weekArray; }
The function will take a month and year value and will return an array of weeks for that month. Each element in this array will be in-turn an array of days in the week. @param {number} month: the month for which array of weeks is needed @param {number} year: the year for which array of weeks is needed @param {number} firstDayOfWeek: first day of the week in the locale @returns {Array}: Array of weeks in a month, each week is in turn array of days in that week
getWeekArrayForMonth
javascript
nikgraf/belle
src/utils/date-helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/date-helpers.js
MIT
getWeekArrayForMonth = (month, year, firstDayOfWeek) => { const monthDay = new Date(year, month, 1); // Todo: simplify this calculation of first date let firstDate = (1 + firstDayOfWeek) - monthDay.getDay(); firstDate = firstDate <= 1 ? firstDate : firstDate - 7; monthDay.setDate(firstDate); const lastDate = new Date(year, month + 1, 0); const weekArray = []; while (monthDay <= lastDate) { const newWeek = []; for (let dayCounter = 0; dayCounter < 7; dayCounter++) { const weekDate = new Date(monthDay.getFullYear(), monthDay.getMonth(), monthDay.getDate()); newWeek.push(weekDate); monthDay.setDate(monthDay.getDate() + 1); } weekArray.push(newWeek); } return weekArray; }
The function will take a month and year value and will return an array of weeks for that month. Each element in this array will be in-turn an array of days in the week. @param {number} month: the month for which array of weeks is needed @param {number} year: the year for which array of weeks is needed @param {number} firstDayOfWeek: first day of the week in the locale @returns {Array}: Array of weeks in a month, each week is in turn array of days in that week
getWeekArrayForMonth
javascript
nikgraf/belle
src/utils/date-helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/date-helpers.js
MIT
getLocaleData = (locale) => { const localeResult = {}; let lData; if (locale) { lData = i18n.localeData[locale]; } const monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; localeResult.monthNames = (lData && lData.monthNames) ? lData.monthNames : monthNames; localeResult.dayNamesMin = (lData && lData.dayNamesMin) ? lData.dayNamesMin : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; localeResult.firstDay = (lData && lData.firstDay) ? lData.firstDay : 0; localeResult.weekEnd = (lData && lData.weekEnd) ? lData.weekEnd : 0; localeResult.isRTL = (lData && lData.isRTL) ? lData.isRTL : false; return localeResult; }
Function will return locale data for locale. If data is not available in config files it will return default data. @param locale - locale for which data is needed. @returns {Object}: Object containing locale data.
getLocaleData
javascript
nikgraf/belle
src/utils/date-helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/date-helpers.js
MIT
getLocaleData = (locale) => { const localeResult = {}; let lData; if (locale) { lData = i18n.localeData[locale]; } const monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; localeResult.monthNames = (lData && lData.monthNames) ? lData.monthNames : monthNames; localeResult.dayNamesMin = (lData && lData.dayNamesMin) ? lData.dayNamesMin : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; localeResult.firstDay = (lData && lData.firstDay) ? lData.firstDay : 0; localeResult.weekEnd = (lData && lData.weekEnd) ? lData.weekEnd : 0; localeResult.isRTL = (lData && lData.isRTL) ? lData.isRTL : false; return localeResult; }
Function will return locale data for locale. If data is not available in config files it will return default data. @param locale - locale for which data is needed. @returns {Object}: Object containing locale data.
getLocaleData
javascript
nikgraf/belle
src/utils/date-helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/date-helpers.js
MIT
getDateForDateKey = (dateKey) => { const splittedDate = dateKey.split('-'); return new Date(parseInt(splittedDate[0], 10), parseInt(splittedDate[1], 10) - 1, parseInt(splittedDate[2], 10)); }
Returns the date for a date string representation. @param year {number} - any year @param month {number} - can be between 1 and 12 @param day {number} - can be between 1 and 31 depending on the month @returns {date} - the parse date
getDateForDateKey
javascript
nikgraf/belle
src/utils/date-helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/date-helpers.js
MIT
getDateForDateKey = (dateKey) => { const splittedDate = dateKey.split('-'); return new Date(parseInt(splittedDate[0], 10), parseInt(splittedDate[1], 10) - 1, parseInt(splittedDate[2], 10)); }
Returns the date for a date string representation. @param year {number} - any year @param month {number} - can be between 1 and 12 @param day {number} - can be between 1 and 31 depending on the month @returns {date} - the parse date
getDateForDateKey
javascript
nikgraf/belle
src/utils/date-helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/date-helpers.js
MIT
convertDateToDateKey = (date) => ( getDateKey(date.getFullYear(), date.getMonth() + 1, date.getDate()) )
Returns the string representation for a provided date. @param date {date} - a valid date @returns {string}: a string representing the date in the format yyyy-mm-dd
convertDateToDateKey
javascript
nikgraf/belle
src/utils/date-helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/date-helpers.js
MIT
convertDateToDateKey = (date) => ( getDateKey(date.getFullYear(), date.getMonth() + 1, date.getDate()) )
Returns the string representation for a provided date. @param date {date} - a valid date @returns {string}: a string representing the date in the format yyyy-mm-dd
convertDateToDateKey
javascript
nikgraf/belle
src/utils/date-helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/date-helpers.js
MIT
function has(obj, key) { return obj !== undefined && obj !== null && Object.prototype.hasOwnProperty.call(obj, key); }
Returns true if the object contain the given key. @param {object} obj - object to be inspected @param {string} key - name of the property
has
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function filter(iterable, predicate, context) { if (iterable) { const result = []; iterable.forEach((obj) => { if (predicate && predicate.call(context, obj)) { result.push(obj); } }); return result; } return undefined; }
Looks through each value in the list, returning an array of all the values that pass a truth test (predicate). @param {array} iterable - the iterable object to be filtered @param {function} predicate - function returning true when provided with an entry as argument @param {object} [context] - context for the predicate function call
filter
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function isArrayLike(obj) { if (Array.isArray(obj)) return true; if (typeof obj === 'string') return false; const length = obj.length; return typeof length === 'number' && length >= 0; }
Returns true if the provided object is an iterable, except for strings for which it will return false. @param {object} obj - object to be inspected
isArrayLike
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function keys(obj) { const objKeys = []; for (const key in obj) if (has(obj, key)) objKeys.push(key); return objKeys; }
Returns all the names of the object's own properties. This will not include properties inherited through prototypes. @param {object} obj - object to be used
keys
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function map(iterable, predicate) { if (iterable) { const result = []; iterable.forEach((elm, index) => { if (predicate) { result[index] = predicate(elm, index); } }); return result; } return undefined; }
Returns a new array of values by mapping each value in list through a transformation function (predicate). @param {array} iterable - source iterable @param {function} predicate - function returning the transformed array entry
map
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function mapObject(obj, predicate) { if (obj) { const result = []; const objKeys = keys(obj); objKeys.forEach((key, index) => { if (predicate) { result[index] = predicate(obj[key], key); } }); return result; } return undefined; }
Returns a new object by mapping each property in an object through a transformation function (predicate). @param {object} obj - object to be based upon @param {function} predicate - function to transform the property
mapObject
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function find(iterable, predicate, context) { if (iterable) { let result; for (let index = 0; index < iterable.length; index++) { if (predicate && predicate.call(context, iterable[index])) { result = iterable[index]; break; } } return result; } return undefined; }
Returns the first value that passes a truth test (predicate), or undefined if no value passes the test. Only works for iterable objects e.g. arrays. @param {array} iterable - the iterable object to be searched @param {function} predicate - function returning true in case of a positive match @param {object} [context] - context for the predicate function call
find
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function reverse(iterable) { if (iterable) { const result = []; for (let index = iterable.length - 1; index >= 0; index--) { result.push(iterable[index]); } return result; } return undefined; }
Reverse the array passed to it. @param {array} iterable - the array to be reversed.
reverse
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function shift(iterable, positions) { if (iterable) { if (positions && positions > 0) { const result = []; const arrayLength = iterable.length; for (let index = 0; index < iterable.length; index++) { result.push(iterable[(index + positions) % arrayLength]); } return result; } return iterable; } return undefined; }
Shifts given array by given number of positions. @param {array} iterable - the array to be shifted. @param {array} positions - number of positions shifting is needed.
shift
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function isEmpty(obj) { return !obj || (Array.isArray(obj) && obj.length === 0) || (Object.keys(obj).length === 0); }
Returns true if object contains no values (no enumerable own-properties). @param {Object} obj - an object
isEmpty
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function findIndex(iterable, predicate, context) { if (iterable) { let result; for (let index = 0; index < iterable.length; index++) { if (predicate && predicate.call(context, iterable[index])) { result = index; break; } } return result; } return undefined; }
Returns the index of the first value that passes a truth test (predicate), or undefined if no value passes the test. Only works for iterable objects e.g. arrays. @param {array} iterable - the iterable object to be searched @param {function} predicate - function returning true in case of a positive match @param {object} [context] - context for the predicate function call
findIndex
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function first(iterable) { if (iterable && iterable.length > 0) { return iterable[0]; } return undefined; }
Returns the first element of an iterable object. @param {array} iterable - must be an iterable object
first
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function last(iterable) { if (iterable && iterable.length > 0) { return iterable[iterable.length - 1]; } return undefined; }
Returns the last element of an iterable object. @param {array} iterable - must be an iterable object
last
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function size(iterable) { if (iterable) { return iterable.length; } return 0; }
Return the number of values in the list. @param {array} iterable - must be an iterable object
size
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function some(iterable, predicate, context) { if (iterable) { let result; for (let index = 0; index < iterable.length; index++) { if (predicate && predicate.call(context, iterable[index])) { result = true; break; } } return result; } return undefined; }
Returns true if any of the values in the list pass the predicate truth test. @param {array} iterable - iterable object to be searched @param {function} predicate - function returning true in case of a positive match @param {object} [context] - context for the predicate function call
some
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function union(...arrs) { if (arrs) { const result = []; arrs.forEach((arr) => { if (arr) { arr.forEach((obj) => { if (result.indexOf(obj) < 0) { result.push(obj); } }); } }); return result; } return undefined; }
Returns the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays. @param {...array} arrs - at least two iterable objects must be provide
union
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function flattenInternal(output, element) { if (element) { element.forEach((obj) => { if (Array.isArray(obj)) { flattenInternal(output, obj); } else { output.push(obj); } }); } }
Recursive function for flattening an iterable. @param {object} output - base object to be updated @param {object} element - input object to be merged into the output
flattenInternal
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function flatten(...arrays) { if (arrays) { const result = []; flattenInternal(result, arrays); return result; } return undefined; }
Flattens a nested array (the nesting can be to any depth). @param {...array} arrays - at least one array must be provided
flatten
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function filterReactChildren(children, predicate) { if (children) { const result = []; React.Children.forEach(children, (entry) => { if (predicate && predicate.call(this, entry)) { result.push(entry); } }); return result; } return undefined; }
Looks through a collection of React children elements, filtering them according to the predicate passed. @param {Array/Object} children - colleciton of >=1 react elements @param {function} predicate - function returning true when provided with an entry as argument
filterReactChildren
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function getArrayForReactChildren(children) { if (children) { const result = []; React.Children.forEach(children, (entry) => { result.push(entry); }); return result; } return undefined; }
Looks through a collection of React children elements, filtering them according to the predicate passed. @param {Array/Object} children - collection of >=1 react elements
getArrayForReactChildren
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function flattenReactChildren(children) { if (!isEmpty(children)) { if (Array.isArray(children)) { return flatten(children); } return getArrayForReactChildren(children); } return undefined; }
Looks through a collection of React children elements, filtering them according to the predicate passed. @param {Array/Object} children - collection of >=1 react elements
flattenReactChildren
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function uniqueId() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }
Looks through a collection of React children elements, filtering them according to the predicate passed. @param {Array/Object} children - collection of >=1 react elements
uniqueId
javascript
nikgraf/belle
src/utils/helpers.js
https://github.com/nikgraf/belle/blob/master/src/utils/helpers.js
MIT
function injectStyleTag() { if (!styleElement && canUseDOM) { styleElement = document.createElement('style'); document.body.appendChild(styleElement); styleElement.setAttribute('class', 'belle-style'); } }
Injects the provided style into the styleStore.
injectStyleTag
javascript
nikgraf/belle
src/utils/inject-style.js
https://github.com/nikgraf/belle/blob/master/src/utils/inject-style.js
MIT
function updateStore(styleId, style, pseudoClass, disabled) { styleStorage[styleId] = styleStorage[styleId] || {}; if (disabled) { styleStorage[styleId].disabledPseudoClasses = styleStorage[styleId].disabledPseudoClasses || {}; styleStorage[styleId].disabledPseudoClasses[pseudoClass] = style; } else { styleStorage[styleId].pseudoClasses = styleStorage[styleId].pseudoClasses || {}; styleStorage[styleId].pseudoClasses[pseudoClass] = style; } }
Injects the provided style into the styleStore.
updateStore
javascript
nikgraf/belle
src/utils/inject-style.js
https://github.com/nikgraf/belle/blob/master/src/utils/inject-style.js
MIT
function createMarkupOnPseudoClass(pseudoClasses, id, disabled) { return mapObject(pseudoClasses, (style, pseudoClass) => { if (style && Object.keys(style).length > 0) { const styleString = CSSPropertyOperations.createMarkupForStyles(style); const styleWithImportant = styleString.replace(/;/g, ' !important;'); return disabled ? `.${id}[disabled]:${pseudoClass} {${styleWithImportant}}` : `.${id}:${pseudoClass} {${styleWithImportant}}`; } return undefined; }); }
Constructs all the stored styles & injects them to the DOM.
createMarkupOnPseudoClass
javascript
nikgraf/belle
src/utils/inject-style.js
https://github.com/nikgraf/belle/blob/master/src/utils/inject-style.js
MIT
function updateStyling() { const styles = mapObject(styleStorage, (storageEntry, id) => { const pseudoClassesArray = []; if (storageEntry.pseudoClasses) { pseudoClassesArray.push(createMarkupOnPseudoClass(storageEntry.pseudoClasses, id, false)); } if (storageEntry.disabledPseudoClasses) { pseudoClassesArray.push(createMarkupOnPseudoClass(storageEntry.disabledPseudoClasses, id, true)); } return pseudoClassesArray; }); if (styleElement) { styleElement.innerHTML = flatten([animations, styles]).join(' '); } }
Constructs all the stored styles & injects them to the DOM.
updateStyling
javascript
nikgraf/belle
src/utils/inject-style.js
https://github.com/nikgraf/belle/blob/master/src/utils/inject-style.js
MIT
function injectStyles(styles) { injectStyleTag(); styles.forEach((style) => { updateStore(style.id, style.style, style.pseudoClass, style.disabled); }); updateStyling(); }
Injects a style tag and adds multiple passed styles. By using this function someone can make sure the DOM is updated only once. @example ``` const styles = [ { id: 'style-0.0.2', style: { color: '#F00' }, pseudoClass: 'hover' } ]; injectStyles(styles); ```
injectStyles
javascript
nikgraf/belle
src/utils/inject-style.js
https://github.com/nikgraf/belle/blob/master/src/utils/inject-style.js
MIT
function removeStyle(styleId) { delete styleStorage[styleId]; updateStyling(); }
Removes all pseudoClass styles based on the provided styleId.
removeStyle
javascript
nikgraf/belle
src/utils/inject-style.js
https://github.com/nikgraf/belle/blob/master/src/utils/inject-style.js
MIT
function removeAllStyles(styleIds) { styleIds.forEach((styleId) => { delete styleStorage[styleId]; }); updateStyling(); }
Removes all pseudoClass styles based on all provided styleIds.
removeAllStyles
javascript
nikgraf/belle
src/utils/inject-style.js
https://github.com/nikgraf/belle/blob/master/src/utils/inject-style.js
MIT
function isComponentOfType(classType, reactElement) { return reactElement && reactElement.type === classType; }
Returns true if the provided element is a component of the provided type. @param classType {ReactElement class} - the class of a React Element @param reactElement {ReactElement} - any React Element (not a real DOM node) @example // Checks if the component is an Autocomplete isComponentType(Autocomplete, this.props.children[0]);
isComponentOfType
javascript
nikgraf/belle
src/utils/is-component-of-type.js
https://github.com/nikgraf/belle/blob/master/src/utils/is-component-of-type.js
MIT
function unionClassNames(existingClassNames, additionalClassNames) { if (!existingClassNames && !additionalClassNames) return ''; if (!existingClassNames) return additionalClassNames; if (!additionalClassNames) return existingClassNames; return union(existingClassNames.split(' '), additionalClassNames.split(' ')).join(' '); }
Returns a string containing all classes without duplicates. @param existingClassNames {String} - one or multiple classes @param additionalClassNames {String} - one or multiple classes @example // returns 'style-id-23 button buy-button' unionClassNames('style-id-23 button', 'button buy-button') Originally inspired by https://github.com/rackt/react-autocomplete/blob/master/lib/union-class-names.js
unionClassNames
javascript
nikgraf/belle
src/utils/union-class-names.js
https://github.com/nikgraf/belle/blob/master/src/utils/union-class-names.js
MIT
function sign(value) { return value >= 0 ? 1 : -1; }
The number of radians in an arc second. @type {Number} @constant
sign
javascript
yszhao91/cga.js
build/@xort_cga.js
https://github.com/yszhao91/cga.js/blob/master/build/@xort_cga.js
MIT
function approximateEqual(v1, v2, precision) { if (precision === void 0) { precision = exports.delta4; } return Math.abs(v1 - v2) < precision; }
The number of radians in an arc second. @type {Number} @constant
approximateEqual
javascript
yszhao91/cga.js
build/@xort_cga.js
https://github.com/yszhao91/cga.js/blob/master/build/@xort_cga.js
MIT
function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); }
The number of radians in an arc second. @type {Number} @constant
clamp
javascript
yszhao91/cga.js
build/@xort_cga.js
https://github.com/yszhao91/cga.js/blob/master/build/@xort_cga.js
MIT
function lerp(x, y, t) { return (1 - t) * x + t * y; }
The number of radians in an arc second. @type {Number} @constant
lerp
javascript
yszhao91/cga.js
build/@xort_cga.js
https://github.com/yszhao91/cga.js/blob/master/build/@xort_cga.js
MIT
function smoothstep(x, min, max) { if (x <= min) return 0; if (x >= max) return 1; x = (x - min) / (max - min); return x * x * (3 - 2 * x); }
The number of radians in an arc second. @type {Number} @constant
smoothstep
javascript
yszhao91/cga.js
build/@xort_cga.js
https://github.com/yszhao91/cga.js/blob/master/build/@xort_cga.js
MIT
function smootherstep(x, min, max) { if (x <= min) return 0; if (x >= max) return 1; x = (x - min) / (max - min); return x * x * x * (x * (x * 6 - 15) + 10); }
The number of radians in an arc second. @type {Number} @constant
smootherstep
javascript
yszhao91/cga.js
build/@xort_cga.js
https://github.com/yszhao91/cga.js/blob/master/build/@xort_cga.js
MIT
function randInt(low, high) { return low + Math.floor(Math.random() * (high - low + 1)); }
The number of radians in an arc second. @type {Number} @constant
randInt
javascript
yszhao91/cga.js
build/@xort_cga.js
https://github.com/yszhao91/cga.js/blob/master/build/@xort_cga.js
MIT
Inherit = function (ce, ce2) { var p; if (typeof (Object.getOwnPropertyNames) === 'undefined') { for (p in ce2.prototype) if (typeof (ce.prototype[p]) === 'undefined' || ce.prototype[p] === Object.prototype[p]) ce.prototype[p] = ce2.prototype[p]; for (p in ce2) if (typeof (ce[p]) === 'undefined') ce[p] = ce2[p]; ce.$baseCtor = ce2; } else { var props = Object.getOwnPropertyNames(ce2.prototype); for (var i = 0; i < props.length; i++) if (typeof (Object.getOwnPropertyDescriptor(ce.prototype, props[i])) === 'undefined') Object.defineProperty(ce.prototype, props[i], Object.getOwnPropertyDescriptor(ce2.prototype, props[i])); for (p in ce2) if (typeof (ce[p]) === 'undefined') ce[p] = ce2[p]; ce.$baseCtor = ce2; } }
**************************************************************************** * Author : Timo * Version : 6.4.2.2 (FPoint) * Date : 8 September 2017 * * This is a translation of the C# Clipper library to Javascript. * * *****************************************************************************
Inherit
javascript
yszhao91/cga.js
src/clipper/clipper_float_unminified.js
https://github.com/yszhao91/cga.js/blob/master/src/clipper/clipper_float_unminified.js
MIT
function createWechat ($container, $data) { var $wechat = $container.find('a.icon-wechat'); if (!$wechat.length) {return;} $wechat.append('<div class="wechat-qrcode"><h4>'+$data.wechatQrcodeTitle+'</h4><div class="qrcode"></div><div class="help">'+$data.wechatQrcodeHelper+'</div></div>'); $wechat.find('.qrcode').qrcode({render: 'image', size: $data.wechatQrcodeSize, text: $data.url}); if ($wechat.offset().top < 100) { $wechat.find('.wechat-qrcode').addClass('bottom'); } }
Create the wechat icon and QRCode. @param {Object|String} $container @param {Object} $data
createWechat
javascript
overtrue/share.js
src/js/jquery.share.js
https://github.com/overtrue/share.js/blob/master/src/js/jquery.share.js
MIT