path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
resource/js/app.js | crow-misia/crowi | import React from 'react';
import ReactDOM from 'react-dom';
import Crowi from './util/Crowi';
import CrowiRenderer from './util/CrowiRenderer';
import HeaderSearchBox from './components/HeaderSearchBox';
import SearchPage from './components/SearchPage';
import PageListSearch from './components/PageListSearch';
import PageHistory from './components/PageHistory';
import SeenUserList from './components/SeenUserList';
//import PageComment from './components/PageComment';
if (!window) {
window = {};
}
const mainContent = document.querySelector('#content-main');
let pageId = null;
if (mainContent !== null) {
pageId = mainContent.attributes['data-page-id'].value;
}
// FIXME
const crowi = new Crowi({me: $('#content-main').data('current-username')}, window);
window.crowi = crowi;
crowi.fetchUsers();
const crowiRenderer = new CrowiRenderer();
window.crowiRenderer = crowiRenderer;
const componentMappings = {
'search-top': <HeaderSearchBox />,
'search-page': <SearchPage />,
'page-list-search': <PageListSearch />,
//'revision-history': <PageHistory pageId={pageId} />,
//'page-comment': <PageComment />,
'seen-user-list': <SeenUserList />,
};
Object.keys(componentMappings).forEach((key) => {
const elem = document.getElementById(key);
if (elem) {
ReactDOM.render(componentMappings[key], elem);
}
});
// うわーもうー
$('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
ReactDOM.render(<PageHistory pageId={pageId} crowi={crowi} />, document.getElementById('revision-history'));
});
|
fields/types/cloudinaryimages/CloudinaryImagesField.js | geminiyellow/keystone | import _ from 'underscore';
import React from 'react';
import Field from '../Field';
import { Button, FormField, FormInput, FormNote } from 'elemental';
import Lightbox from '../../../admin/src/components/Lightbox';
const SUPPORTED_TYPES = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/x-icon', 'application/pdf', 'image/x-tiff', 'image/x-tiff', 'application/postscript', 'image/vnd.adobe.photoshop', 'image/svg+xml'];
var Thumbnail = React.createClass({
displayName: 'CloudinaryImagesFieldThumbnail',
propTypes: {
deleted: React.PropTypes.bool,
height: React.PropTypes.number,
isQueued: React.PropTypes.bool,
openLightbox: React.PropTypes.func,
shouldRenderActionButton: React.PropTypes.bool,
toggleDelete: React.PropTypes.func,
url: React.PropTypes.string,
width: React.PropTypes.number,
},
renderActionButton () {
if (!this.props.shouldRenderActionButton || this.props.isQueued) return null;
return <Button type={this.props.deleted ? 'link-text' : 'link-cancel'} block onClick={this.props.toggleDelete}>{this.props.deleted ? 'Undo' : 'Remove'}</Button>;
},
render () {
let iconClassName;
let { deleted, height, isQueued, url, width } = this.props;
if (deleted) {
iconClassName = 'delete-pending mega-octicon octicon-x';
} else if (isQueued) {
iconClassName = 'img-uploading mega-octicon octicon-cloud-upload';
}
let previewClassName = 'image-preview';
if (deleted || isQueued) previewClassName += ' action';
let title = (width && height) ? (width + ' × ' + height) : '';
return (
<div className="image-field image-sortable" title={title}>
<div className={previewClassName}>
<a href={url} onClick={this.props.openLightbox} className="img-thumbnail">
<img style={{ height: '90' }} className="img-load" src={url} />
<span className={iconClassName} />
</a>
</div>
{this.renderActionButton()}
</div>
);
}
});
module.exports = Field.create({
getInitialState () {
var thumbnails = [];
var self = this;
_.each(this.props.value, function (item) {
self.pushThumbnail(item, thumbnails);
});
return { thumbnails: thumbnails };
},
openLightbox (index) {
event.preventDefault();
this.setState({
lightboxIsVisible: true,
lightboxImageIndex: index,
});
},
closeLightbox () {
this.setState({
lightboxIsVisible: false,
lightboxImageIndex: null,
});
},
renderLightbox () {
if (!this.props.value || !this.props.value.length) return;
let images = this.props.value.map(image => image.url);
return (
<Lightbox
images={images}
initialImage={this.state.lightboxImageIndex}
isOpen={this.state.lightboxIsVisible}
onCancel={this.closeLightbox}
/>
);
},
removeThumbnail (i) {
var thumbs = this.state.thumbnails;
var thumb = thumbs[i];
if (thumb.props.isQueued) {
thumbs[i] = null;
} else {
thumb.props.deleted = !thumb.props.deleted;
}
this.setState({ thumbnails: thumbs });
},
pushThumbnail (args, thumbs) {
thumbs = thumbs || this.state.thumbnails;
var i = thumbs.length;
args.toggleDelete = this.removeThumbnail.bind(this, i);
args.shouldRenderActionButton = this.shouldRenderField();
args.openLightbox = this.openLightbox.bind(this, i);
thumbs.push(<Thumbnail key={i} {...args} />);
},
fileFieldNode () {
return this.refs.fileField.getDOMNode();
},
getCount (key) {
var count = 0;
_.each(this.state.thumbnails, function (thumb) {
if (thumb && thumb.props[key]) count++;
});
return count;
},
renderFileField () {
if (!this.shouldRenderField()) return null;
return <input ref="fileField" type="file" name={this.props.paths.upload} multiple className="field-upload" onChange={this.uploadFile} tabIndex="-1" />;
},
clearFiles () {
this.fileFieldNode().value = '';
this.setState({
thumbnails: this.state.thumbnails.filter(function (thumb) {
return !thumb.props.isQueued;
})
});
},
uploadFile (event) {
var self = this;
var files = event.target.files;
_.each(files, function (f) {
if (!_.contains(SUPPORTED_TYPES, f.type)) {
alert('Unsupported file type. Supported formats are: GIF, PNG, JPG, BMP, ICO, PDF, TIFF, EPS, PSD, SVG');
return;
}
if (window.FileReader) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
self.pushThumbnail({ isQueued: true, url: e.target.result });
self.forceUpdate();
};
fileReader.readAsDataURL(f);
} else {
self.pushThumbnail({ isQueued: true, url: '#' });
self.forceUpdate();
}
});
},
changeImage () {
this.fileFieldNode().click();
},
hasFiles () {
return this.refs.fileField && this.fileFieldNode().value;
},
renderToolbar () {
if (!this.shouldRenderField()) return null;
var body = [];
var push = function (queueType, alertType, count, action) {
if (count <= 0) return;
var imageText = count === 1 ? 'image' : 'images';
body.push(<div key={queueType + '-toolbar'} className={queueType + '-queued' + ' u-float-left'}>
<FormInput noedit>{count} {imageText} {action} - save to confirm</FormInput>
</div>);
};
push('upload', 'success', this.getCount('isQueued'), 'queued for upload');
push('delete', 'danger', this.getCount('deleted'), 'removed');
var clearFilesButton;
if (this.hasFiles()) {
clearFilesButton = <Button type="link-cancel" onClick={this.clearFiles} className="ml-5">Clear selection</Button>;
}
return (
<div className="images-toolbar">
<div className="u-float-left">
<Button onClick={this.changeImage}>Select files</Button>
{clearFilesButton}
</div>
{body}
</div>
);
},
renderPlaceholder () {
return (
<div className="image-field image-field--upload" onClick={this.changeImage}>
<div className="image-preview">
<span className="img-thumbnail">
<span className="img-dropzone" />
<div className="img-uploading mega-octicon octicon-file-media" />
</span>
</div>
<div className="image-details">
<span className="image-message">Click to upload</span>
</div>
</div>
);
},
renderContainer () {
return (
<div className="images-container">
{this.state.thumbnails}
</div>
);
},
renderFieldAction () {
if (!this.shouldRenderField()) return null;
var value = '';
var remove = [];
_.each(this.state.thumbnails, function (thumb) {
if (thumb && thumb.props.deleted) remove.push(thumb.props.public_id);
});
if (remove.length) value = 'remove:' + remove.join(',');
return <input ref="action" className="field-action" type="hidden" value={value} name={this.props.paths.action} />;
},
renderUploadsField () {
if (!this.shouldRenderField()) return null;
return <input ref="uploads" className="field-uploads" type="hidden" name={this.props.paths.uploads} />;
},
renderNote () {
if (!this.props.note) return null;
return <FormNote note={this.props.note} />;
},
renderUI () {
return (
<FormField label={this.props.label} className="field-type-cloudinaryimages">
{this.renderFieldAction()}
{this.renderUploadsField()}
{this.renderFileField()}
{this.renderContainer()}
{this.renderToolbar()}
{this.renderNote()}
{this.renderLightbox()}
</FormField>
);
}
});
|
example/index.ios.js | netbeast/react-native-dial | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import Example from './example'
export default class example extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
<Example/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ddd',
paddingTop: 100,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('example', () => example);
|
src/App.js | gilbox/elegant-react-hot-demo | import React, { Component } from 'react';
import {sub} from 'elegant-react';
import Counters from './Counters';
import {on, stream} from 'flyd';
import counterPlugin from './counter-plugin';
export default class App extends Component {
constructor(props) {
super(props);
const {atom} = this.props;
this.edit = ::atom.updateState;
this.state = {state: atom.getState()};
}
componentWillMount() {
const {atom} = this.props;
const state = atom.getState();
this.incrementActionStreams =
state.get('counts').map((_,i) =>
counterPlugin(sub(this.edit, 'counts', i)).incrementAction$
).toArray();
// connect atom updates to component's state
on(state => this.setState({state}), atom.didSetState$);
}
render() {
const {state} = this.state;
const {edit} = this;
const sort = state.get('sort');
const sortOrder = state.get('sortOrder');
const compact = state.get('compact');
const toggleSort = sub(edit, 'sort');
const toggleSortOrder = sub(edit, 'sortOrder');
const toggleCompact = sub(edit, 'compact');
return <div>
<label style={{ position: 'absolute', top: 5, right: 50}}>
<input type="checkbox" checked={sort}
onChange={event => toggleSort(v => !v)}/>
sort
</label>
<label style={{ position: 'absolute', top: 5, right: 100}}>
<input type="checkbox" checked={sortOrder===1}
onChange={event => {
toggleSort(v => true);
toggleSortOrder(v => -v)}}/>
sort asc
</label>
<label style={{ position: 'absolute', top: 5, right: 180}}>
<input type="checkbox" checked={compact}
onChange={event => toggleCompact(c => !c)}/>
compact
</label>
<Counters
lineHeight={compact ? 30 : 40}
sortOrder={sortOrder * ~~sort}
counts={state.get('counts')}
incrementActionStreams={this.incrementActionStreams} />
</div>
}
}
|
app/javascript/mastodon/features/compose/components/upload_button.js | 5thfloor/ichiji-social | import React from 'react';
import IconButton from '../../../components/icon_button';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';
const messages = defineMessages({
upload: { id: 'upload_button.label', defaultMessage: 'Add media ({formats})' },
});
const SUPPORTED_FORMATS = 'JPEG, PNG, GIF, WebM, MP4, MOV, OGG, WAV, MP3, FLAC';
const makeMapStateToProps = () => {
const mapStateToProps = state => ({
acceptContentTypes: state.getIn(['media_attachments', 'accept_content_types']),
});
return mapStateToProps;
};
const iconStyle = {
height: null,
lineHeight: '27px',
};
export default @connect(makeMapStateToProps)
@injectIntl
class UploadButton extends ImmutablePureComponent {
static propTypes = {
disabled: PropTypes.bool,
unavailable: PropTypes.bool,
onSelectFile: PropTypes.func.isRequired,
style: PropTypes.object,
resetFileKey: PropTypes.number,
acceptContentTypes: ImmutablePropTypes.listOf(PropTypes.string).isRequired,
intl: PropTypes.object.isRequired,
};
handleChange = (e) => {
if (e.target.files.length > 0) {
this.props.onSelectFile(e.target.files);
}
}
handleClick = () => {
this.fileElement.click();
}
setRef = (c) => {
this.fileElement = c;
}
render () {
const { intl, resetFileKey, unavailable, disabled, acceptContentTypes } = this.props;
if (unavailable) {
return null;
}
return (
<div className='compose-form__upload-button'>
<IconButton icon='paperclip' title={intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} />
<label>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })}</span>
<input
key={resetFileKey}
ref={this.setRef}
type='file'
multiple
accept={acceptContentTypes.toArray().join(',')}
onChange={this.handleChange}
disabled={disabled}
style={{ display: 'none' }}
/>
</label>
</div>
);
}
}
|
pootle/static/js/shared/components/CodeMirror.js | dwaynebailey/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import * as CM from 'codemirror';
import 'codemirror/addon/display/placeholder';
import 'codemirror/lib/codemirror.css';
import { getMode } from 'utils/markup';
import './CodeMirror.css';
const CodeMirror = React.createClass({
propTypes: {
markup: React.PropTypes.string,
// Temporarily needed to support submitting forms not controlled by JS
name: React.PropTypes.string,
onChange: React.PropTypes.func,
placeholder: React.PropTypes.string,
value: React.PropTypes.string,
},
getDefaultProps() {
return {
markup: 'html',
};
},
componentDidMount() {
const mode = getMode(this.props.markup);
// Using webpack's `bundle` loader so each mode goes into a separate chunk
const bundledResult = require(`bundle!codemirror/mode/${mode}/${mode}.js`);
bundledResult(() => {
this.codemirror = CM.fromTextArea(this.refs.editor, {
mode,
lineWrapping: true,
});
this.codemirror.on('change', this.handleChange);
});
},
handleChange() {
if (this.props.onChange) {
this.props.onChange(this.codemirror.getValue());
}
},
render() {
const extraProps = {};
if (this.props.name) {
extraProps.name = this.props.name;
}
return (
<textarea
defaultValue={this.props.value}
placeholder={this.props.placeholder}
ref="editor"
{...extraProps}
/>
);
},
});
export default CodeMirror;
|
src/pages/list/ListPage.js | yang-zhang-syd/React-Wechat-E2E-Test-With-Fake-Api | import React from 'react';
import {
Panel,
PanelHeader,
PanelBody,
PanelFooter,
MediaBox,
MediaBoxHeader,
MediaBoxBody,
MediaBoxTitle,
MediaBoxDescription,
MediaBoxInfo,
MediaBoxInfoMeta,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} from 'react-weui';
import Page from '../../components/page/page';
export default class ListPage extends React.Component {
render() {
return (
<Page className="panel" title="List"></Page>
);
}
}
|
src/features/rekit-cmds/DialogPlace.js | supnate/rekit-portal | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { autobind } from 'core-decorators';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Modal } from 'antd';
import * as actions from './redux/actions';
import { CmdForm, cmdSuccessNotification, LogViewerDialog } from './';
const displayName = _.flow(_.lowerCase, _.upperFirst);
export class DialogPlace extends Component {
static propTypes = {
rekitCmds: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired,
};
@autobind
handleCmdDialogDone(dialogType) {
this.props.actions.hideDialog(dialogType);
}
@autobind
handleCmdSuccess(dialogType) {
this.props.actions.hideCmdDialog(dialogType);
const { args } = this.props.rekitCmds.execCmdResult;
cmdSuccessNotification(args, this.props.actions.showCmdDialog);
}
render() {
const { rekitCmds } = this.props;
const { hideCmdDialog } = this.props.actions;
return (
<div className="rekit-cmds-dialog-place">
{rekitCmds.cmdDialogVisible &&
<Modal
visible
maskClosable={false}
footer=""
wrapClassName="rekit-cmds-cmd-dialog"
title={displayName(rekitCmds.cmdArgs.type)}
onClose={() => hideCmdDialog('cmd')}
{...this.props}
>
<CmdForm
onCancel={() => hideCmdDialog('cmd')}
onDone={() => this.handleCmdSuccess('cmd')}
/>
</Modal>
}
{rekitCmds.logViewerDialogVisible &&
<LogViewerDialog onClose={() => hideCmdDialog('logViewer')} />
}
</div>
);
}
}
/* istanbul ignore next */
function mapStateToProps(state) {
return {
rekitCmds: state.rekitCmds,
};
}
/* istanbul ignore next */
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({ ...actions }, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(DialogPlace);
|
SSBW/Tareas/Tarea9/restaurantes2/node_modules/react-bootstrap/es/InputGroupAddon.js | jmanday/Master | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var InputGroupAddon = function (_React$Component) {
_inherits(InputGroupAddon, _React$Component);
function InputGroupAddon() {
_classCallCheck(this, InputGroupAddon);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
InputGroupAddon.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('span', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return InputGroupAddon;
}(React.Component);
export default bsClass('input-group-addon', InputGroupAddon); |
src/containers/pages/create-deck/after-class-selection/left-container.js | vFujin/HearthLounge | import React from 'react';
import SidebarHeader from './left-container/sidebar/sidebar-header';
import DeckSidebar from './left-container/deck-sidebar';
const LeftContainer = ({playerClass}) => (
<div className="container__page--inner container__page--left">
<SidebarHeader />
<DeckSidebar playerClass={playerClass}/>
</div>
);
export default LeftContainer; |
node_modules/react-router/es6/RouterContext.js | ajames72/MovieDBReact | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import invariant from 'invariant';
import React from 'react';
import deprecateObjectProperties from './deprecateObjectProperties';
import getRouteParams from './getRouteParams';
import { isReactChildren } from './RouteUtils';
import warning from './routerWarning';
var _React$PropTypes = React.PropTypes;
var array = _React$PropTypes.array;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <RouterContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
var RouterContext = React.createClass({
displayName: 'RouterContext',
propTypes: {
history: object,
router: object.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired,
createElement: func.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
createElement: React.createElement
};
},
childContextTypes: {
history: object,
location: object.isRequired,
router: object.isRequired
},
getChildContext: function getChildContext() {
var _props = this.props;
var router = _props.router;
var history = _props.history;
var location = _props.location;
if (!router) {
process.env.NODE_ENV !== 'production' ? warning(false, '`<RouterContext>` expects a `router` rather than a `history`') : void 0;
router = _extends({}, history, {
setRouteLeaveHook: history.listenBeforeLeavingRoute
});
delete router.listenBeforeLeavingRoute;
}
if (process.env.NODE_ENV !== 'production') {
location = deprecateObjectProperties(location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. http://tiny.cc/router-accessinglocation');
}
return { history: history, location: location, router: router };
},
createElement: function createElement(component, props) {
return component == null ? null : this.props.createElement(component, props);
},
render: function render() {
var _this = this;
var _props2 = this.props;
var history = _props2.history;
var location = _props2.location;
var routes = _props2.routes;
var params = _props2.params;
var components = _props2.components;
var element = null;
if (components) {
element = components.reduceRight(function (element, components, index) {
if (components == null) return element; // Don't create new children; use the grandchildren.
var route = routes[index];
var routeParams = getRouteParams(route, params);
var props = {
history: history,
location: location,
params: params,
route: route,
routeParams: routeParams,
routes: routes
};
if (isReactChildren(element)) {
props.children = element;
} else if (element) {
for (var prop in element) {
if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop];
}
}
if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') {
var elements = {};
for (var key in components) {
if (Object.prototype.hasOwnProperty.call(components, key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = _this.createElement(components[key], _extends({
key: key }, props));
}
}
return elements;
}
return _this.createElement(components, props);
}, element);
}
!(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0;
return element;
}
});
export default RouterContext; |
packages/bonde-admin/src/components/notify/warning.js | ourcities/rebu-client | import PropTypes from 'prop-types'
import React from 'react'
import Box from './box'
var styles = require('exenv').canUseDOM ? require('./warning.scss') : {}
const Warning = ({ title, children }) => (
<Box
title={title}
styles={styles}
icon='exclamation-triangle'
>
{children}
</Box>
)
Warning.propTypes = {
title: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
]).isRequired,
children: PropTypes.any.isRequired
}
export default Warning
|
app/assets/javascripts/application.js | tka/ideapool | require("../stylesheets/application.scss")
import React from 'react';
import ReactDom from 'react-dom'
import UserNav from "./components/UserNav.js"
ReactDom.render(
<UserNav/>,
document.getElementById('user-nav')
);
|
packages/material-ui-icons/src/LocalHotel.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LocalHotel = props =>
<SvgIcon {...props}>
<path d="M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3zm12-6h-8v7H3V5H1v15h2v-3h18v3h2v-9c0-2.21-1.79-4-4-4z" />
</SvgIcon>;
LocalHotel = pure(LocalHotel);
LocalHotel.muiName = 'SvgIcon';
export default LocalHotel;
|
packages/icons/src/script.js | geek/joyent-portal | import React from 'react';
import Rotate from './rotate';
import calcFill from './fill';
export default ({
fill = null,
light = false,
disabled = false,
direction = 'down',
colors = {},
style = {},
...rest
}) => (
<Rotate direction={direction}>
{({ style: rotateStyle }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="15.43"
height="18"
viewBox="0 0 15.43 18"
style={{ ...style, ...rotateStyle }}
{...rest}
>
<path
fill={calcFill({ fill, disabled, light, colors })}
d="M15.09,13.64,12.29,6h.14a3,3,0,0,0,0-6H3A3,3,0,0,0,0,3a3.37,3.37,0,0,0,.09.71,6.85,6.85,0,0,0,.25.64l3,7.68L3,12a3,3,0,0,0,0,6h9.43a2.94,2.94,0,0,0,3-3.43A7.54,7.54,0,0,0,15.09,13.64ZM12.43,1.46a1.54,1.54,0,1,1,0,3.08,1.52,1.52,0,0,1-1.27-.67l-.24-.6a1.24,1.24,0,0,1,0-.27A1.54,1.54,0,0,1,12.43,1.46ZM2,3.74l-.21-.52a.78.78,0,0,1,0-.22A1.29,1.29,0,0,1,3,1.71H9.73A3,3,0,0,0,9.43,3a2.76,2.76,0,0,0,.09.71L9.63,4c0,.09.77,2,.77,2l2.33,6-.3,0H5.36L2.88,6ZM9.73,16.29H3a1.29,1.29,0,0,1,0-2.58H9.73a2.92,2.92,0,0,0,0,2.58Zm2.7.25A1.54,1.54,0,1,1,14,15,1.54,1.54,0,0,1,12.43,16.54Z"
/>
</svg>
)}
</Rotate>
);
|
public/app/components/vpanel-project-tab/canvas-component-attribute.js | vincent-tr/mylife-home-studio | 'use strict';
import React from 'react';
import * as dnd from 'react-dnd';
import icons from '../icons';
import { dragTypes } from '../../constants/index';
import styles from './canvas-component-styles';
const CanvasComponentAttribute = ({ attribute, connectDragPreview, connectDragSource }) => connectDragSource(
<div style={styles.detailsContainer}>
{connectDragPreview(<div style={styles.detailsIconContainer}><icons.NetAttribute style={styles.detailsIcon} /></div>)}
<div style={styles.detailsText}>{`${attribute.name} (${attribute.type})`}</div>
</div>
);
CanvasComponentAttribute.propTypes = {
component : React.PropTypes.object.isRequired,
attribute : React.PropTypes.object.isRequired,
onCreateBinding : React.PropTypes.func.isRequired,
connectDragSource : React.PropTypes.func.isRequired,
connectDragPreview : React.PropTypes.func.isRequired,
isDragging : React.PropTypes.bool.isRequired
};
const attributeSource = {
beginDrag(props/*, monitor*/) {
const { component, attribute } = props;
return {
remoteComponent : component.uid,
remoteAttribute : attribute.name
};
},
endDrag(props, monitor) {
if(!monitor.didDrop()) { return; }
const { component, attribute, onCreateBinding } = props;
const { localComponent, localAction } = monitor.getDropResult();
onCreateBinding(component.uid, attribute.name, localComponent, localAction);
}
};
function collect(connect, monitor) {
return {
connectDragSource : connect.dragSource(),
connectDragPreview : connect.dragPreview(),
isDragging : monitor.isDragging()
};
}
export default dnd.DragSource(dragTypes.VPANEL_COMPONENT_ATTRIBUTE, attributeSource, collect)(CanvasComponentAttribute);
|
app/javascript/mastodon/features/account_gallery/components/media_item.js | yukimochi/mastodon | import Blurhash from 'mastodon/components/blurhash';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
import { autoPlayGif, displayMedia, useBlurhash } from 'mastodon/initial_state';
import { isIOS } from 'mastodon/is_mobile';
import PropTypes from 'prop-types';
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class MediaItem extends ImmutablePureComponent {
static propTypes = {
attachment: ImmutablePropTypes.map.isRequired,
displayWidth: PropTypes.number.isRequired,
onOpenMedia: PropTypes.func.isRequired,
};
state = {
visible: displayMedia !== 'hide_all' && !this.props.attachment.getIn(['status', 'sensitive']) || displayMedia === 'show_all',
loaded: false,
};
handleImageLoad = () => {
this.setState({ loaded: true });
}
handleMouseEnter = e => {
if (this.hoverToPlay()) {
e.target.play();
}
}
handleMouseLeave = e => {
if (this.hoverToPlay()) {
e.target.pause();
e.target.currentTime = 0;
}
}
hoverToPlay () {
return !autoPlayGif && ['gifv', 'video'].indexOf(this.props.attachment.get('type')) !== -1;
}
handleClick = e => {
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
if (this.state.visible) {
this.props.onOpenMedia(this.props.attachment);
} else {
this.setState({ visible: true });
}
}
}
render () {
const { attachment, displayWidth } = this.props;
const { visible, loaded } = this.state;
const width = `${Math.floor((displayWidth - 4) / 3) - 4}px`;
const height = width;
const status = attachment.get('status');
const title = status.get('spoiler_text') || attachment.get('description');
let thumbnail, label, icon, content;
if (!visible) {
icon = (
<span className='account-gallery__item__icons'>
<Icon id='eye-slash' />
</span>
);
} else {
if (['audio', 'video'].includes(attachment.get('type'))) {
content = (
<img
src={attachment.get('preview_url') || attachment.getIn(['account', 'avatar_static'])}
alt={attachment.get('description')}
onLoad={this.handleImageLoad}
/>
);
if (attachment.get('type') === 'audio') {
label = <Icon id='music' />;
} else {
label = <Icon id='play' />;
}
} else if (attachment.get('type') === 'image') {
const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0;
const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0;
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
content = (
<img
src={attachment.get('preview_url')}
alt={attachment.get('description')}
style={{ objectPosition: `${x}% ${y}%` }}
onLoad={this.handleImageLoad}
/>
);
} else if (attachment.get('type') === 'gifv') {
content = (
<video
className='media-gallery__item-gifv-thumbnail'
aria-label={attachment.get('description')}
role='application'
src={attachment.get('url')}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
autoPlay={!isIOS() && autoPlayGif}
loop
muted
/>
);
label = 'GIF';
}
thumbnail = (
<div className='media-gallery__gifv'>
{content}
{label && <span className='media-gallery__gifv__label'>{label}</span>}
</div>
);
}
return (
<div className='account-gallery__item' style={{ width, height }}>
<a className='media-gallery__item-thumbnail' href={status.get('url')} onClick={this.handleClick} title={title} target='_blank' rel='noopener noreferrer'>
<Blurhash
hash={attachment.get('blurhash')}
className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && loaded })}
dummy={!useBlurhash}
/>
{visible ? thumbnail : icon}
</a>
</div>
);
}
}
|
front/app/js/components/__dev__/ExpandButtonGroup.js | nudoru/React-Starter-3 | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles, createClassNameFromProps } from '../controls/common/StyleManager';
/**
<ExpandButtonGroup>
<ToggleButton>Click Me</ToggleButton> // If first, buttons on right, last on left
<ButtonGroup> // hide / show, open / closed?
<Button primary>Option 1</Button>
<Button>Option 2</Button>
</ButtonGroup>
</ExpandButtonGroup>
*/
class BExpandButtonGroup extends React.PureComponent {
render() {
return (
<div className={getBsClassName(this.props)}>Template component</div>
);
}
}
export const ExpandButtonGroup = withStyles('')(BExpandButtonGroup);
class BToggleButton extends React.PureComponent {
render() {
return (
<div className={getBsClassName(this.props)}>Template component</div>
);
}
}
export const ToggleButton = withStyles('')(BToggleButton); |
docs/app/Examples/collections/Table/Variations/TableExampleAttached.js | koenvg/Semantic-UI-React | import React from 'react'
import { Table } from 'semantic-ui-react'
const header = (
<Table.Header>
<Table.Row>
<Table.HeaderCell>Header</Table.HeaderCell>
<Table.HeaderCell>Header</Table.HeaderCell>
<Table.HeaderCell>Header</Table.HeaderCell>
</Table.Row>
</Table.Header>
)
const body = (
<Table.Body>
<Table.Row>
<Table.Cell>Cell</Table.Cell>
<Table.Cell>Cell</Table.Cell>
<Table.Cell>Cell</Table.Cell>
</Table.Row>
</Table.Body>
)
const TableExampleAttached = () => (
<div>
<Table attached='top' basic>{header}{body}</Table>
<Table attached>
{body}
</Table>
<Table attached celled selectable>
{body}
</Table>
<Table attached='bottom' celled>
{header}
{body}
</Table>
</div>
)
export default TableExampleAttached
|
client/src/templates/Introduction/Intro.js | jonathanihm/freeCodeCamp | import React from 'react';
import PropTypes from 'prop-types';
import { Link, graphql } from 'gatsby';
import Helmet from 'react-helmet';
import { Grid, ListGroup, ListGroupItem } from '@freecodecamp/react-bootstrap';
import LearnLayout from '../../components/layouts/Learn';
import FullWidthRow from '../../components/helpers/FullWidthRow';
import ButtonSpacer from '../../components/helpers/ButtonSpacer';
import { MarkdownRemark, AllChallengeNode } from '../../redux/propTypes';
import './intro.css';
const propTypes = {
data: PropTypes.shape({
markdownRemark: MarkdownRemark,
allChallengeNode: AllChallengeNode
})
};
function renderMenuItems({ edges = [] }) {
return edges
.map(({ node }) => node)
.map(({ title, fields: { slug } }) => (
<Link key={'intro-' + slug} to={slug}>
<ListGroupItem>{title}</ListGroupItem>
</Link>
));
}
function IntroductionPage({ data: { markdownRemark, allChallengeNode } }) {
const {
html,
frontmatter: { block }
} = markdownRemark;
const firstLesson = allChallengeNode && allChallengeNode.edges[0].node;
const firstLessonPath = firstLesson
? firstLesson.fields.slug
: '/strange-place';
return (
<LearnLayout>
<Helmet>
<title>{block} | freeCodeCamp.org</title>
</Helmet>
<Grid className='intro-layout-container'>
<FullWidthRow>
<div
className='intro-layout'
dangerouslySetInnerHTML={{ __html: html }}
/>
</FullWidthRow>
<FullWidthRow>
<Link
className='btn btn-lg btn-primary btn-block'
to={firstLessonPath}
>
Go to the first lesson
</Link>
<ButtonSpacer />
<Link className='btn btn-lg btn-primary btn-block' to='/learn'>
View the curriculum
</Link>
<ButtonSpacer />
<hr />
</FullWidthRow>
<FullWidthRow>
<h2 className='intro-toc-title'>Upcoming Lessons</h2>
<ListGroup className='intro-toc'>
{allChallengeNode ? renderMenuItems(allChallengeNode) : null}
</ListGroup>
</FullWidthRow>
</Grid>
</LearnLayout>
);
}
IntroductionPage.displayName = 'IntroductionPage';
IntroductionPage.propTypes = propTypes;
export default IntroductionPage;
export const query = graphql`
query IntroPageBySlug($slug: String!, $block: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
frontmatter {
block
}
html
}
allChallengeNode(
filter: { block: { eq: $block } }
sort: { fields: [superOrder, order, challengeOrder] }
) {
edges {
node {
fields {
slug
}
title
}
}
}
}
`;
|
src/pages/about.js | H3yfinn/finbarmaunsell.com | import React from 'react';
import Link from 'gatsby-link';
import Footer from './components/footer.js'
import me from './images/me_tonga.png';
const SecondPage = () => (
<div>
<div>
<h1>About</h1>
<p>This page is my elevator pitch, web style!</p>
<p>I'm one of those people that likes to try do things differently. I find that I'm always trying to improve my situation but my methods don't always run in the norm. </p>
<p>For example, this year I left university to try out studying online. I thought it would be cheaper, more benefical and maybe even exciting! That's going well. </p>
<div>
<img src={me} alt='picture of finn' />
</div>
<p>My goals for life seem to revolve around enjoyment and fullfilment. I'm not one to sacrifice either of those recklessly but I am definitely up for taking opportunities to gain experience and improvements in life. </p>
<p>To note, as hard as I try to keep things simple, the above is, like this website, continually changing. If you have feedback or even want to get in touch please <a href='mailto:[email protected]'>email me</a>.</p>
</div>
<Footer />
</div>
)
export default SecondPage
|
frontend/app_v2/src/common/icons/Lessons.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
/**
* @summary Lessons
* @component
*
* @param {object} props
*
* @returns {node} jsx markup
*/
function Lessons({ styling }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" className={styling}>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z" />
</svg>
)
}
// PROPTYPES
const { string } = PropTypes
Lessons.propTypes = {
styling: string,
}
export default Lessons
|
src/svg-icons/device/bluetooth-disabled.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBluetoothDisabled = (props) => (
<SvgIcon {...props}>
<path d="M13 5.83l1.88 1.88-1.6 1.6 1.41 1.41 3.02-3.02L12 2h-1v5.03l2 2v-3.2zM5.41 4L4 5.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l4.29-4.29 2.3 2.29L20 18.59 5.41 4zM13 18.17v-3.76l1.88 1.88L13 18.17z"/>
</SvgIcon>
);
DeviceBluetoothDisabled = pure(DeviceBluetoothDisabled);
DeviceBluetoothDisabled.displayName = 'DeviceBluetoothDisabled';
DeviceBluetoothDisabled.muiName = 'SvgIcon';
export default DeviceBluetoothDisabled;
|
src/components/TeamForm/TeamForm.js | labzero/lunch | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Button from 'react-bootstrap/lib/Button';
import Col from 'react-bootstrap/lib/Col';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import InputGroup from 'react-bootstrap/lib/InputGroup';
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
import Popover from 'react-bootstrap/lib/Popover';
import Row from 'react-bootstrap/lib/Row';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import TeamGeosuggestContainer from '../TeamGeosuggest/TeamGeosuggestContainer';
import TeamMapContainer from '../TeamMap/TeamMapContainer';
import s from './TeamForm.scss';
class TeamForm extends Component {
static propTypes = {
center: PropTypes.object,
team: PropTypes.object.isRequired,
updateTeam: PropTypes.func.isRequired
};
static defaultProps = {
center: undefined
};
constructor(props) {
super(props);
this.defaultCenter = {
lat: props.team.lat,
lng: props.team.lng
};
this.state = {
address: props.team.address,
name: props.team.name,
sortDuration: props.team.sort_duration
};
}
handleChange = field => event => this.setState({ [field]: event.target.value });
handleSubmit = (event) => {
event.preventDefault();
const typedsortDuration = typeof this.state.sortDuration === 'number'
? this.state.sortDuration
: parseInt(this.state.sortDuration.slice(), 10);
if (typedsortDuration > 0) {
this.props.updateTeam(
Object.assign({}, this.state, this.props.center, { sort_duration: typedsortDuration })
);
} else {
event.stopPropagation();
}
};
render() {
const { name, address, sortDuration } = this.state;
const sortDurationAddonLabel = parseInt(sortDuration, 10) === 1 ? 'day' : 'days';
const popoverRight = (
<Popover title="Sort Duration" id="sortDuration">
<p>
Sort duration refers to the amount of time votes and decisions factor in to how
restaurants are sorted. For example, if you choose Burger Shack for today’s lunch
and your sort duration is set to 7 days, Burger Shack will appear towards the bottom
of your restaurant list for the next week.
</p>
<p>
Conversely, if you were to upvote Burger Shack but not choose it for today’s lunch,
Burger Shack would be prioritized and appear higher in your restaurant list for the
next week.
</p>
</Popover>
);
return (
<form onSubmit={this.handleSubmit}>
<FormGroup controlId="teamForm-name">
<ControlLabel>
Name
</ControlLabel>
<Row>
<Col sm={6}>
<FormControl
onChange={this.handleChange('name')}
required
value={name}
/>
</Col>
</Row>
</FormGroup>
<FormGroup controlId="teamForm-address">
<ControlLabel>Address</ControlLabel>
<TeamMapContainer defaultCenter={this.defaultCenter} />
<TeamGeosuggestContainer
id="teamForm-address"
initialValue={address}
onChange={this.handleChange('address')}
/>
</FormGroup>
<FormGroup controlId="teamForm-vote-duration">
<ControlLabel>Sort duration</ControlLabel>
<OverlayTrigger trigger="focus" placement="right" overlay={popoverRight}>
<Button
bsSize="xsmall"
className={['glyphicon glyphicon-question-sign', s.overlayTrigger].join(' ')}
/>
</OverlayTrigger>
<Row>
<Col sm={2}>
<InputGroup>
<FormControl
type="number"
onChange={this.handleChange('sortDuration')}
required
value={sortDuration}
min="1"
/>
<InputGroup.Addon>{sortDurationAddonLabel}</InputGroup.Addon>
</InputGroup>
</Col>
</Row>
</FormGroup>
<Button type="submit">Save Changes</Button>
</form>
);
}
}
export default withStyles(s)(TeamForm);
|
app/components/Root/Root.js | LabMDE/bungee-books-web | import React from 'react';
import style from './Root.scss';
import classNames from 'classNames/bind';
const css = classNames.bind(style);
import Nav from '../Nav/Nav';
import Footer from '../Footer/Footer';
const Root = ({ children }) => {
return (
<div className="main-container">
<Nav />
<div className={ css('container') }>
{ children }
</div>
<Footer />
</div>
);
};
export default Root;
|
src/components/Home.js | benawad/nukool | import React, { Component } from 'react';
import { Container, Button, Form, Message } from 'semantic-ui-react'
import Title from './Title';
class Home extends Component {
getParameterByName(name) {
const url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
constructor(props) {
super(props);
const redditStateKey = 'redditState';
if (window.location.search) {
const state = this.getParameterByName('state');
const code = this.getParameterByName('code');
if (state && code) {
if (state === localStorage.getItem(redditStateKey, "")) {
const { subject, message, users } = localStorage;
if (subject !== undefined && message !== undefined && users !== undefined) {
this.props.sendMessages(subject, message, JSON.parse(users), 'yummy ramen', code);
}
}
}
}
this.subjectKey = "subject";
this.messageKey = "message";
this.usersKey = "users";
const redditState = this.createState();
localStorage.setItem(redditStateKey, redditState);
const redirectUri = "http://benawad.com/nukool/%23";
this.url = `https://www.reddit.com/api/v1/authorize?scope=identity,privatemessages&response_type=code&redirect_uri=${redirectUri}&client_id=-Q-lrceF3GNtHw&state=${redditState}&duration=permanent`
this.handleSubmit = this.handleSubmit.bind(this);
this.errorContent = this.errorContent.bind(this);
this.subjectChange = this.subjectChange.bind(this);
this.messageChange = this.messageChange.bind(this);
this.usersChange = this.usersChange.bind(this);
this.messageSuccess = this.messageSuccess.bind(this);
}
createState() {
let state = "";
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 5; i++) {
state += possible.charAt(Math.floor(Math.random() * possible.length));
}
return state;
}
handleSubmit(e) {
// validate input
const subject = this.props.homeState.subject.trim();
const message = this.props.homeState.message.trim();
let users = this.props.homeState.users.split('\n');
let cleanUsers = [];
let cleanUser = '';
for (let i = 0; i < users.length; i++) {
cleanUser = users[i].trim();
if (cleanUser !== '') {
cleanUsers.push(cleanUser) ;
}
}
let uniqueUsers = new Set(cleanUsers);
cleanUsers = [...uniqueUsers];
const subjectEmpty = subject === '';
const messageEmpty = message === '';
const usersOver10 = cleanUsers.length > 10;
const noUsers = cleanUsers.length <= 0;
if (subjectEmpty || messageEmpty || usersOver10 || noUsers) {
this.props.homeUpdate({
subjectEmpty,
messageEmpty,
usersOver10,
noUsers,
messageSuccess: 2
});
} else {
localStorage.setItem(this.subjectKey, this.props.homeState.subject);
localStorage.setItem(this.messageKey, this.props.homeState.message);
localStorage.setItem(this.usersKey, JSON.stringify(cleanUsers));
window.location = this.url;
}
e.preventDefault();
}
errorContent() {
let errorMessages = [];
if (this.props.homeState.subjectEmpty) {
errorMessages.push('Subject cannot be empty');
}
if (this.props.homeState.messageEmpty) {
errorMessages.push('Message cannot be empty');
}
if (this.props.homeState.usersOver10) {
errorMessages.push('Can only message up to 10 users');
}
if (this.props.homeState.noUsers) {
errorMessages.push('Users cannot be empty');
}
return errorMessages.join(' | ');
}
subjectChange(e) {
const subjectEmpty = e.target.value.trim() === '';
const messageSuccess = subjectEmpty ? 2 : this.props.homeState.messageSuccess;
this.props.updateHome({
subject: e.target.value,
subjectEmpty,
messageSuccess
})
}
messageChange(e) {
const messageEmpty = e.target.value.trim() === '';
const messageSuccess = messageEmpty ? 2 : this.props.homeState.messageSuccess;
this.props.updateHome({
message: e.target.value,
messageEmpty,
messageSuccess
});
}
usersChange(e) {
const noUsers = e.target.value.trim() === '';
const messageSuccess = noUsers ? 2 : this.props.homeState.messageSuccess;
this.props.updateHome({
users: e.target.value,
noUsers,
messageSuccess
});
}
messageForm() {
return (
<Form onSubmit={this.handleSubmit} error={this.props.homeState.subjectEmpty || this.props.homeState.messageEmpty || this.props.homeState.usersOver10 || this.props.homeState.noUsers}>
<Message
error
header='Error'
content={this.errorContent()}
/>
<Form.Field error={this.props.homeState.subjectEmpty} >
<label>Subject</label>
<input
maxLength="99"
name='subject'
onChange={this.subjectChange}
value={this.props.homeState.subject}/>
</Form.Field>
<Form.TextArea error={this.props.homeState.messageEmpty} name='message' label='Message' onChange={this.messageChange} value={this.props.homeState.message} />
<Form.TextArea error={this.props.homeState.usersOver10 || this.props.homeState.noUsers} name='users' placeholder='Add one user per line' label='Users (up to 10)' onChange={this.usersChange} value={this.props.homeState.users} />
<Button primary fluid type='submit'>Send</Button>
</Form>
)
}
messageSuccess() {
const { messageSuccess } = this.props.homeState;
if (messageSuccess === 1) {
return (
<Message
success
header='Authentication successful!'
content='Your message will be sent shortly'
/>
);
} else if (messageSuccess === 0) {
return (
<Message
negative
header='Authentication failed!'
content='Something went wrong :( try again.'
/>
);
} else {
return false;
}
}
render() {
return (
<div>
<div className="outer">
<div className="middle">
<div className="inner">
<Container text>
<Title />
{this.messageSuccess()}
{this.messageForm()}
</Container>
</div>
</div>
</div>
</div>
);
}
}
export default Home;
|
src/routes.js | wunderg/react-nos-kit | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import HomePage from './components/HomePage';
import AboutPage from './components/AboutPage.js';
import NotFoundPage from './components/NotFoundPage.js';
import Signin from './containers/Auth/signin.js';
import Signup from './containers/Auth/signup.js';
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage}/>
<Route path="about" component={AboutPage}/>
<Route path="signin" component={Signin}/>
<Route path="signup" component={Signup}/>
<Route path="*" component={NotFoundPage}/>
</Route>
);
|
definitions/npm/fixed-data-table-2_v0.7.x/flow_v0.47.x-v0.52.x/test_fixed-data-table-2_v0.7.x.js | flowtype/flow-typed | /* @flow */
import React from 'react';
import {Cell, Column, ColumnGroup, Table} from 'fixed-data-table-2';
let cell = <Cell/>;
cell = <Cell onColumnResize={(left, width, minWidth, maxWidth, columnKey, event) => {event.target;}}/>;
// $FlowExpectedError
cell = <Cell onColumnResize={(left, width, minWidth, maxWidth, columnKey, event) => minWidth + maxWidth}/>;
// $FlowExpectedError
let column = <Column/>;
column = <Column width={300} minWidth={null}/>;
let columnGroup = <ColumnGroup/>;
// $FlowExpectedError
columnGroup = <ColumnGroup align='top'/>;
// $FlowExpectedError
let table = <Table/>;
table = <Table
width={900}
rowsCount={10}
rowHeight={50}
headerHeight={60}
/>;
|
src/content/work/assets/SubscriptionsForSaas/modules/List/Icons/Pause/index.js | jmikrut/keen-2017 | import React from 'react';
import './Pause.css';
export default (props) => {
let color = props.color ? props.color : '';
return (
<svg className="plus" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12">
<line stroke={color} x1="4.76" y1="3.76" x2="4.76" y2="8.24"/>
<line stroke={color} x1="7.24" y1="8.24" x2="7.24" y2="3.76"/>
</svg>
);
} |
demo/back-end-antd-app/src/components/Todo.js | JianmingXia/StudyTest | import React from 'react'
const Todo = ({ completed, text, onClick, onDelete }) => (
<li style={{
width: "400px"
}}>
<span
onClick={onClick}
style={{
textDecoration: completed ? 'line-through' : 'none',
width: "350px"
}}>
{text}
</span>
<button onClick={onDelete}
style={{
width: "50px",
float: "right"
}}
>
x
</button>
</li>
);
export default Todo
|
client/src/components/FileManager.js | nickbreaton/spare-page | import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { download, remove } from '../state/files'
import File from './File'
import React from 'react'
const FileManager = (props) => (
<div>
{mapFilesToComponents(props)}
</div>
)
const mapFilesToComponents = (props) => (
props.files.map((file) => (
<File
{...file}
key={file.uuid}
download={() => props.download(file.uuid)}
remove={() => props.remove(file.uuid)}
/>
))
)
const mapStateToProps = (state) => (
{ files: state.files }
)
const mapDispatchToProps = (dispatch) => (
bindActionCreators({ download, remove }, dispatch)
)
export default connect(mapStateToProps, mapDispatchToProps)(FileManager)
|
src/components/QuestionItem/index.js | da07ng/danqing | import React, { Component } from 'react';
class QuestionItem extends Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>danqing</h1>
);
}
}
export default QuestionItem;
|
examples/cra-kitchen-sink/src/stories/welcome.stories.js | storybooks/react-storybook | import React from 'react';
import { Welcome } from '@storybook/react/demo';
import { linkTo } from '@storybook/addon-links';
export default {
title: 'Welcome',
component: Welcome,
};
export const Story1 = () => <Welcome showApp={linkTo('Button')} />;
Story1.title = 'to Storybook';
|
lib/js/apps/genetic-algorithms/index.js | jneander/learning | import React from 'react';
import AppHarness from 'js/shared/components/AppHarness';
import ExampleHarness from 'js/shared/components/ExampleHarness';
import CardSplitting from './CardSplitting';
import KnightCovering from './KnightCovering';
import OneMax from './OneMax';
import Queens from './Queens';
import SortingNumbers from './SortingNumbers';
import TextMatching from './TextMatching';
const examples = [
{ label: 'Text Matching', component: TextMatching },
{ label: 'One Max', component: OneMax },
{ label: 'Sorting Numbers', component: SortingNumbers },
{ label: 'Queens', component: Queens },
{ label: 'Card Splitting', component: CardSplitting },
{ label: 'Knight Covering', component: KnightCovering }
];
export default function GeneticAlgorithms (props) {
return (
<AppHarness page="geneticAlgorithms">
<ExampleHarness
defaultExample={examples[5]}
examples={examples}
heading="Genetic Algorithms"
>
<div>
I recommend not trying the Genetic Algorithms on your mobile device. They consume a lot of power.
</div>
</ExampleHarness>
</AppHarness>
);
}
|
react-flux-mui/js/material-ui/src/svg-icons/image/filter-6.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilter6 = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-8-2h2c1.1 0 2-.89 2-2v-2c0-1.11-.9-2-2-2h-2V7h4V5h-4c-1.1 0-2 .89-2 2v6c0 1.11.9 2 2 2zm0-4h2v2h-2v-2z"/>
</SvgIcon>
);
ImageFilter6 = pure(ImageFilter6);
ImageFilter6.displayName = 'ImageFilter6';
ImageFilter6.muiName = 'SvgIcon';
export default ImageFilter6;
|
src/components/tablePrices/presentation/TPTableModal.js | edu-affiliates/promo_calculators | 'use strict';
import React from 'react';
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import generalOptions from '../../../config/generalOptions';
import {plusPage, minusPage, handleInputPageNumber} from '../../../store/actions'
//presentation of the counter in calc small
class TPTableModal extends React.Component {
constructor(props) {
super(props);
this.state = {
emptyInput: false,
alert: false
};
this.handleChange = this.handleChange.bind(this);
};
handleChange(e) {
if (e.target.value === '') {
this.setState({emptyInput: true})
} else {
if (this.state.emptyInput)
this.setState({emptyInput: false})
}
const number = parseInt(e.target.value);
if (number > this.props.maxPageNumber) {
this.setState({alert: true})
}
this.props.handleInputPageNumber(number);
}
handleBlur() {
this.setState({emptyInput: false});
}
redirectTo(type) {
const {service, level, deadline, pageNumber} = this.props;
let redirectTo = generalOptions.siteMyUrl
+ `/${type}.html?csi=` + service.id
+ '&cli=' + level.id
+ '&cdi=' + deadline.id
+ '&ccu=' + pageNumber;
if (generalOptions.rid) {
redirectTo += `&rid=${generalOptions.rid}`
}
if (generalOptions.dsc) {
redirectTo += `&dsc=${generalOptions.dsc}`
}
location.href = redirectTo;
}
estimateDay() {
const {deadline} = this.props;
const nowMs = new Date().getTime();
const deadlineMs = deadline.hours * 60 * 60 * 1000;
const date = new Date((nowMs + deadlineMs));
return date.getDate() +
"/" + (date.getMonth() + 1) +
"/" + date.getFullYear();
}
render() {
const {onClickPlus, onClickMinus, fullPrice, discount, pageNumber, service, level, currency} = this.props;
const fullPriceDiv = (discount === 0) ? <div/> : <div className="tp-modal__price-full-container">
<div className="tp-modal__price-full">
<span className="tp-modal__price-line-throw"/>
{currency}{(fullPrice * pageNumber).toFixed(2)}
</div>
</div>;
return (
<div className="tp-modal-wrap">
<div onClick={(e) => {
e.stopPropagation();
this.props.closeModal();
}} className="tp-modal__cross">×</div>
<div className="tp-modal">
<div className="tp-modal__date">
<span className="tp-modal__date--title">Estimate date:</span>
<span className="tp-modal__date--value">{this.estimateDay()}</span>
</div>
<div className="tp-modal__counter">
<div onClick={onClickMinus} className="tp-modal__counter-btn tp-modal__counter-btn--minus">
<span>-</span>
</div>
<div className="tp-modal__page-value">
<input type="text"
className="tp-modal__page-input"
onBlur={() => this.handleBlur()}
value={(this.state.emptyInput) ? '' : pageNumber}
onChange={(e) => this.handleChange(e)}
/>
<span>{(pageNumber === 1) ? 'page' : 'pages'}</span>
</div>
<div onClick={onClickPlus} className="tp-modal__counter-btn tp-modal__counter-btn--plus">
<span>+</span>
</div>
</div>
<div className="tp-modal__price">
<span className="tp-modal__price-title">Estimated price:</span>
<div className="tp-modal__price-container">
{fullPriceDiv}
<div className="tp-modal__price-dsc">
{currency}{(fullPrice * (1 - discount) * pageNumber).toFixed(2)}
</div>
</div>
</div>
<div className="tp-modal__btn-group">
<div onClick={() => this.redirectTo('inquiry')} className="tp-modal__btn tp-modal__btn--qoute">
free quote
</div>
<div onClick={() => this.redirectTo('order')} className="tp-modal__btn tp-modal__btn--order">
order now
</div>
</div>
</div>
</div>
)
}
}
TPTableModal.propTypes = {
onClickPlus: PropTypes.func.isRequired,
onClickMinus: PropTypes.func.isRequired,
pageNumber: PropTypes.number.isRequired,
fullPrice: PropTypes.number.isRequired,
discount: PropTypes.number.isRequired,
service: PropTypes.object.isRequired,
level: PropTypes.object.isRequired,
deadline: PropTypes.object.isRequired,
};
//container to match redux state to component props and dispatch redux actions to callback props
const mapStateToProps = (reduxState, ownProps) => {
const state = reduxState.calculatorSmall[ownProps.calcId];
return {
discount: reduxState.discount,
fullPrice: state.deadline.price,
pageNumber: state.pageNumber,
currentDeadline: state.deadline,
service: state.service,
level: state.level,
deadline: state.deadline,
currency: state.currency
}
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClickMinus: () => {
dispatch(minusPage(ownProps.calcId))
},
onClickPlus: () => {
dispatch(plusPage(ownProps.calcId))
},
handleInputPageNumber: (number) => {
dispatch(handleInputPageNumber(number, ownProps.calcId));
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(TPTableModal);
|
node_modules/react-router-dom/node_modules/react-router/es/MemoryRouter.js | millerman86/CouponProject | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import warning from 'warning';
import React from 'react';
import PropTypes from 'prop-types';
import createHistory from 'history/createMemoryHistory';
import Router from './Router';
/**
* The public API for a <Router> that stores location in memory.
*/
var MemoryRouter = function (_React$Component) {
_inherits(MemoryRouter, _React$Component);
function MemoryRouter() {
var _temp, _this, _ret;
_classCallCheck(this, MemoryRouter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret);
}
MemoryRouter.prototype.componentWillMount = function componentWillMount() {
warning(!this.props.history, '<MemoryRouter> ignores the history prop. To use a custom history, ' + 'use `import { Router }` instead of `import { MemoryRouter as Router }`.');
};
MemoryRouter.prototype.render = function render() {
return React.createElement(Router, { history: this.history, children: this.props.children });
};
return MemoryRouter;
}(React.Component);
MemoryRouter.propTypes = {
initialEntries: PropTypes.array,
initialIndex: PropTypes.number,
getUserConfirmation: PropTypes.func,
keyLength: PropTypes.number,
children: PropTypes.node
};
export default MemoryRouter; |
internals/templates/notFoundPage/notFoundPage.js | kenzanboo/tumbler-blog-api | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/common/components/Router/RouterBase.js | minmaster/gig-native-web | 'use strict';
import { Component } from 'react';
import Home from '../Home/Home';
import Video from '../Video/Video';
import Article from '../Article/Article';
import Gallery from '../Gallery/Gallery';
import React from 'react';
class Router extends Component {
constructor(props) {
super(props);
this.state = {
nav: null,
isOpen: false
}
this.updateMenuState = this.updateMenuState.bind(this);
this.toggle = this.toggle.bind(this);
}
updateMenuState(isOpen) {
this.setState({ isOpen, });
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
close() {
this.setState({
isOpen: false
})
}
open() {
this.setState({
isOpen: true
})
}
getChildContext() {
return {
menuActions: this.getMenuActions()
};
}
getMenuActions() {
return {
toggle: this.toggle.bind(this),
open: this.open.bind(this),
close: this.close.bind(this)
}
}
renderScene(route, nav) {
var Component;
if (route.component) {
Component = route.component;
}
switch(route.id) {
case 'videos':
return(<Video navigator={nav} item={route.passProps.item} />)
break;
case 'gallery':
return(<Gallery navigator={nav} />)
break;
case 'articles':
return(<Article navigator={nav} item={route.passProps.item} />)
break;
case 'home':
return(<Home navigator={nav} />)
break;
default:
return(<Home navigator={nav} />)
break;
}
}
componentDidMount() {
this.setState({
nav: this.refs.nav
});
}
}
module.exports = Router;
|
src/svg-icons/action/alarm.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAlarm = (props) => (
<SvgIcon {...props}>
<path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
</SvgIcon>
);
ActionAlarm = pure(ActionAlarm);
ActionAlarm.displayName = 'ActionAlarm';
ActionAlarm.muiName = 'SvgIcon';
export default ActionAlarm;
|
src/views/TheirTeamView.js | andrewSRahn/pickban | import React from 'react'
import OpponentComponent from '../components/OpponentComponent.js'
export default function TheirTeamView(props){
if(props.client === '')
return <div id='their-team'></div>
else {
return (
<div id='their-team'>
<OpponentComponent {...props.client.theirTeam[0]}/>
<OpponentComponent {...props.client.theirTeam[1]}/>
<OpponentComponent {...props.client.theirTeam[2]}/>
<OpponentComponent {...props.client.theirTeam[3]}/>
<OpponentComponent {...props.client.theirTeam[4]}/>
</div>
)
}
} |
examples/query-params/app.js | natorojr/react-router | import React from 'react';
import { Router, Route, Link } from 'react-router';
var User = React.createClass({
render() {
var { query } = this.props.location;
var age = query && query.showAge ? '33' : '';
var { userID } = this.props.params;
return (
<div className="User">
<h1>User id: {userID}</h1>
{age}
</div>
);
}
});
var App = React.createClass({
render() {
return (
<div>
<ul>
<li><Link to="/user/bob">Bob</Link></li>
<li><Link to="/user/bob" query={{showAge: true}}>Bob With Query Params</Link></li>
<li><Link to="/user/sally">Sally</Link></li>
</ul>
{this.props.children}
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="user/:userID" component={User} />
</Route>
</Router>
), document.getElementById('example'));
|
examples/redux-loop/redux-loop-example/src/counter.js | mpeyper/redux-subspace | import React from 'react';
import { fromJS } from 'immutable';
import { connect } from 'react-redux';
import { createAction, createReducer } from 'redux-act';
import { Cmd, loop } from 'redux-loop';
import delay from './delay';
/**
* Set up an initial state with two counters that we will update after some
* variable amount of time after we start the incrementing process. Immutable
* objects work rather well with redux-loop, and there is not additional setup
* to be able to use an Immutable.Map as your top level state. Internally,
* redux-loop makes sure the redux store is satisfied with the shape of your
* state.
*/
const initialState = fromJS({
short: {
loading: false,
count: 0,
failed: false,
},
long: {
loading: false,
count: 0,
failed: false,
},
});
/**
* We're using redux-act (https://github.com/pauldijou/redux-act) to set up
* some actions here, but this is just because we like it and it lets you add
* real documentation strings instead of using constants. No special
* action-creator factories or reducer factories are necessary to use
* redux-loop. Switch statements are totally fine!
*/
const Actions = {
incrementBothStart: createAction('Start both increments'),
shortIncrementStart: createAction('Start short incrememt'),
shortIncrementSucceed: createAction('Finish short increment'),
shortIncrementFail: createAction('Fail to complete short increment'),
longIncrementStart: createAction('Start long increment'),
longIncrementSucceed: createAction('Finish long increment'),
longIncrementFail: createAction('Fail to complete long increment'),
};
/**
* In order to do actual real-world things in your application you'll probably
* have an API that makes network requests or manages animations or something
* of that nature. Here we'll just use timeouts to mock up some asynchronous
* behavior. redux-loop expects that your Promises will always resolve, even if
* the original API call fails. You'll always want to fill in both the `then`
* and the `catch` cases with an action creator. In this example, the `delay`
* function has a roughly 50% chance of rejecting the promise, so we'll handle
* both cases. If you forget to handle an error case and a Promise passed to
* redux-loop does get rejected, you'll see an error logged to the console and
* redux-loop's dispatching will halt.
*/
const Api = {
shortIncrement: (amount) => (
delay(10)
.then(() => amount)
),
longIncrement: (amount) => (
delay(3000)
.then(() => amount)
)
};
/**
* In your reducer you can choose to return a loop or not. The typical pattern
* you'll end up using is to have some sort of `__Start` action that feeds into
* one or more pairs of `__Succeed` and `__Fail` actions. You must always handle
* the failure case, even if the handler is a no-op!
*/
export const reducer = createReducer({
/**
* The following three reducers start through the process of updating the
* counter on the short timer. The process starts here and can either fail
* or succeed randomly, and we've covered both cases.
*/
[Actions.shortIncrementStart]: (state, amount) => {
console.log('short start');
return loop(state
.setIn(['short', 'loading'], true)
.setIn(['short', 'failed'], false),
Cmd.run(Api.shortIncrement, {
successActionCreator: Actions.shortIncrementSucceed,
failActionCreator: Actions.shortIncrementFail,
args: [amount]
})
)
},
[Actions.shortIncrementSucceed]: (state, amount) => {
console.log('short success');
return state
.setIn(['short', 'loading'], false)
.updateIn(['short', 'count'], (current) => current + amount)
},
[Actions.shortIncrementFail]: (state) => {
console.log('short fail');
return state
.setIn(['short', 'loading'], false)
.setIn(['short', 'failed'], true)
},
/**
* The following three reducers perform the same such behavior for the counter
* on the long timer.
*/
[Actions.longIncrementStart]: (state, amount) => {
console.log('long start');
return loop(state
.setIn(['long', 'loading'], true)
.setIn(['long', 'failed'], false),
Cmd.run(Api.longIncrement, {
successActionCreator: Actions.longIncrementSucceed,
failActionCreator: Actions.longIncrementFail,
args: [amount]
}))
},
[Actions.longIncrementSucceed]: (state, amount) => {
console.log('long success');
return state
.setIn(['long', 'loading'], false)
.updateIn(['long', 'count'], (current) => current + amount)
},
[Actions.longIncrementFail]: (state) => {
console.log('log failed');
return state
.setIn(['long', 'loading'], false)
.setIn(['long', 'failed'], true)
},
/**
* This final action groups the two increment start actions with a batch.
* `Effects.batch()` will wait for all actions in the batch to become available
* before proceeding, so only use it if you want to wait for the longest-
* running effect to complete before dispatching everything. In our case we
* want both increment paths to procede independently so we use
* `Effects.constant()` to forward into the starting actions for both paths.
*/
[Actions.incrementBothStart]: (state, amount) => {
console.log('both start');
return loop(state,
Cmd.list([
Cmd.action(Actions.shortIncrementStart(amount)),
Cmd.action(Actions.longIncrementStart(amount)),
])
)},
}, initialState);
/**
* Here we set up a simple, reusable "dumb" component in the redux nomenclature
* which we can reuse to render each counter since they have a repeatable
* structure.
*/
const Counter = ({ loading, count, failed, onClick, name }) => {
const failureMessage = failed ?
<div>Failed to complete increment for {name}</div> :
null;
return (
<div style={{
opacity: loading ? 0.5 : 1,
padding: 10
}}>
<div>
<button
disabled={loading}
onClick={onClick}>
{loading ? 'Loading...' : `Add 1 to ${name} counter`}
</button>
</div>
<div>
{name} counter: {count}
</div>
{failureMessage}
</div>
);
}
/**
* Careful here! Our top level state is a an Immutable Map, and `connect()` in
* react-redux attempts to spread our state object over our components, so we
* need to make sure the state is contained in a single property within our
* component's `props`. We'll call it `model` here, to be a little more like
* Elm 😄, and we'll also deserialize it to a plain object for convenience.
*/
const connector = connect((state) => ({ model: state.toJS() }));
/**
* This component is our top-level app structure which recieves the state from
* our store. Some of the rendering will be delegated to the Counter component
* we set up earlier. It includes one Counter for each in the store as well
* as a button to initiate the `incrementBothStart` action.
*/
export const CounterApp = connector(({ model, dispatch }) => {
const anyLoading = model.short.loading || model.long.loading;
return (
<div>
<Counter
{...model.short}
name="Short timeout"
onClick={() => {
dispatch(Actions.shortIncrementStart(1)).then(() => {
console.log('short');
})
}}/>
<Counter
{...model.long}
name="Long timeout"
onClick={() => {
dispatch(Actions.longIncrementStart(1)).then(() => {
console.log('long');
})
}} />
<div>
<button
disabled={anyLoading}
onClick={() => {
dispatch(Actions.incrementBothStart(1)).then(() => {
console.log('both');
})
}}>
{anyLoading ? 'Loading...' : 'Add 1 to both and wait'}
</button>
</div>
</div>
);
});
|
ajax/libs/react-instantsearch/4.1.0/Connectors.js | joeyparrish/cdnjs | /*! ReactInstantSearch 4.1.0 | © Algolia, inc. | https://community.algolia.com/react-instantsearch/ */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["Connectors"] = factory(require("react"));
else
root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Connectors"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_4__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 436);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
if (false) {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(159)();
}
/***/ }),
/* 1 */
/***/ (function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEqual2 = __webpack_require__(81);
var _isEqual3 = _interopRequireDefault(_isEqual2);
var _has2 = __webpack_require__(58);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.default = createConnector;
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = __webpack_require__(4);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(44);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* @typedef {object} ConnectorDescription
* @property {string} displayName - the displayName used by the wrapper
* @property {function} refine - a function to filter the local state
* @property {function} getSearchParameters - function transforming the local state to a SearchParameters
* @property {function} getMetadata - metadata of the widget
* @property {function} transitionState - hook after the state has changed
* @property {function} getProvidedProps - transform the state into props passed to the wrapped component.
* Receives (props, widgetStates, searchState, metadata) and returns the local state.
* @property {function} getId - Receives props and return the id that will be used to identify the widget
* @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state.
* @property {object} propTypes - PropTypes forwarded to the wrapped component.
* @property {object} defaultProps - default values for the props
*/
/**
* Connectors are the HOC used to transform React components
* into InstantSearch widgets.
* In order to simplify the construction of such connectors
* `createConnector` takes a description and transform it into
* a connector.
* @param {ConnectorDescription} connectorDesc the description of the connector
* @return {Connector} a function that wraps a component into
* an instantsearch connected one.
*/
function createConnector(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var hasRefine = (0, _has3.default)(connectorDesc, 'refine');
var hasSearchForFacetValues = (0, _has3.default)(connectorDesc, 'searchForFacetValues');
var hasSearchParameters = (0, _has3.default)(connectorDesc, 'getSearchParameters');
var hasMetadata = (0, _has3.default)(connectorDesc, 'getMetadata');
var hasTransitionState = (0, _has3.default)(connectorDesc, 'transitionState');
var hasCleanUp = (0, _has3.default)(connectorDesc, 'cleanUp');
var isWidget = hasSearchParameters || hasMetadata || hasTransitionState;
return function (Composed) {
var _class, _temp, _initialiseProps;
return _temp = _class = function (_Component) {
_inherits(Connector, _Component);
function Connector(props, context) {
_classCallCheck(this, Connector);
var _this = _possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context));
_initialiseProps.call(_this);
var _context$ais = context.ais,
store = _context$ais.store,
widgetsManager = _context$ais.widgetsManager,
multiIndexContext = context.multiIndexContext;
var canRender = false;
_this.state = {
props: _this.getProvidedProps(_extends({}, props, { canRender: canRender })),
canRender: canRender // use to know if a component is rendered (browser), or not (server).
};
_this.unsubscribe = store.subscribe(function () {
if (_this.state.canRender) {
_this.setState({
props: _this.getProvidedProps(_extends({}, _this.props, {
canRender: _this.state.canRender
}))
});
}
});
var getSearchParameters = hasSearchParameters ? function (searchParameters) {
return connectorDesc.getSearchParameters.call(_this, searchParameters, _this.props, store.getState().widgets);
} : null;
var getMetadata = hasMetadata ? function (nextWidgetsState) {
return connectorDesc.getMetadata.call(_this, _this.props, nextWidgetsState);
} : null;
var transitionState = hasTransitionState ? function (prevWidgetsState, nextWidgetsState) {
return connectorDesc.transitionState.call(_this, _this.props, prevWidgetsState, nextWidgetsState);
} : null;
if (isWidget) {
_this.unregisterWidget = widgetsManager.registerWidget({
getSearchParameters: getSearchParameters,
getMetadata: getMetadata,
transitionState: transitionState,
multiIndexContext: multiIndexContext
});
}
return _this;
}
_createClass(Connector, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.setState({
canRender: true
});
}
}, {
key: 'componentWillMount',
value: function componentWillMount() {
if (connectorDesc.getSearchParameters) {
this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props);
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (!(0, _isEqual3.default)(this.props, nextProps)) {
this.setState({
props: this.getProvidedProps(nextProps)
});
if (isWidget) {
// Since props might have changed, we need to re-run getSearchParameters
// and getMetadata with the new props.
this.context.ais.widgetsManager.update();
if (connectorDesc.transitionState) {
this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets));
}
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.unsubscribe();
if (isWidget) {
this.unregisterWidget(); // will schedule an update
if (hasCleanUp) {
var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets);
this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), {
widgets: newState
}));
this.context.ais.onSearchStateChange((0, _utils.removeEmptyKey)(newState));
}
}
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var propsEqual = (0, _utils.shallowEqual)(this.props, nextProps);
if (this.state.props === null || nextState.props === null) {
if (this.state.props === nextState.props) {
return !propsEqual;
}
return true;
}
return !propsEqual || !(0, _utils.shallowEqual)(this.state.props, nextState.props);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
if (this.state.props === null) {
return null;
}
var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {};
var searchForFacetValuesProps = hasSearchForFacetValues ? {
searchForItems: this.searchForFacetValues,
searchForFacetValues: function searchForFacetValues(facetName, query) {
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`searchForItems`, this will break in the next major version.');
}
_this2.searchForFacetValues(facetName, query);
}
} : {};
return _react2.default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(_react.Component), _class.displayName = connectorDesc.displayName + '(' + (0, _utils.getDisplayName)(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = {
// @TODO: more precise state manager propType
ais: _propTypes2.default.object.isRequired,
multiIndexContext: _propTypes2.default.object
}, _initialiseProps = function _initialiseProps() {
var _this3 = this;
this.getProvidedProps = function (props) {
var store = _this3.context.ais.store;
var _store$getState = store.getState(),
results = _store$getState.results,
searching = _store$getState.searching,
error = _store$getState.error,
widgets = _store$getState.widgets,
metadata = _store$getState.metadata,
resultsFacetValues = _store$getState.resultsFacetValues,
searchingForFacetValues = _store$getState.searchingForFacetValues;
var searchState = {
results: results,
searching: searching,
error: error,
searchingForFacetValues: searchingForFacetValues
};
return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues);
};
this.refine = function () {
var _connectorDesc$refine;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this3.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.searchForFacetValues = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.createURL = function () {
var _connectorDesc$refine2;
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return _this3.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.cleanUp = function () {
var _connectorDesc$cleanU;
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this3].concat(args));
};
}, _temp;
};
}
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(76);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_4__;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get2 = __webpack_require__(72);
var _get3 = _interopRequireDefault(_get2);
var _omit2 = __webpack_require__(35);
var _omit3 = _interopRequireDefault(_omit2);
var _has2 = __webpack_require__(58);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.getIndex = getIndex;
exports.getResults = getResults;
exports.hasMultipleIndex = hasMultipleIndex;
exports.refineValue = refineValue;
exports.getCurrentRefinementValue = getCurrentRefinementValue;
exports.cleanUpValue = cleanUpValue;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getIndex(context) {
return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex;
}
function getResults(searchResults, context) {
if (searchResults.results && !searchResults.results.hits) {
return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null;
} else {
return searchResults.results ? searchResults.results : null;
}
}
function hasMultipleIndex(context) {
return context && context.multiIndexContext;
}
// eslint-disable-next-line max-params
function refineValue(searchState, nextRefinement, context, resetPage, namespace) {
if (hasMultipleIndex(context)) {
return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage);
} else {
return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage);
}
}
function refineMultiIndex(searchState, nextRefinement, context, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
var index = getIndex(context);
var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, nextRefinement, page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndex(searchState, nextRefinement, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, nextRefinement, page);
}
// eslint-disable-next-line max-params
function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) {
var _extends4;
var index = getIndex(context);
var page = resetPage ? { page: 1 } : undefined;
var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], (_extends4 = {}, _defineProperty(_extends4, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), _defineProperty(_extends4, 'page', 1), _extends4)))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends(_defineProperty({}, namespace, nextRefinement), page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page);
}
function getNamespaceAndAttributeName(id) {
var parts = id.match(/^([^.]*)\.(.*)/);
var namespace = parts && parts[1];
var attributeName = parts && parts[2];
return { namespace: namespace, attributeName: attributeName };
}
// eslint-disable-next-line max-params
function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) {
var index = getIndex(context);
var _getNamespaceAndAttri = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri.namespace,
attributeName = _getNamespaceAndAttri.attributeName;
var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && (0, _has3.default)(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && (0, _has3.default)(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && (0, _has3.default)(searchState[namespace], attributeName) || !hasMultipleIndex(context) && (0, _has3.default)(searchState, id);
if (refinements) {
var currentRefinement = void 0;
if (hasMultipleIndex(context)) {
currentRefinement = namespace ? (0, _get3.default)(searchState.indices['' + index][namespace], attributeName) : (0, _get3.default)(searchState.indices[index], id);
} else {
currentRefinement = namespace ? (0, _get3.default)(searchState[namespace], attributeName) : (0, _get3.default)(searchState, id);
}
return refinementsCallback(currentRefinement);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return defaultValue;
}
function cleanUpValue(searchState, context, id) {
var index = getIndex(context);
var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri2.namespace,
attributeName = _getNamespaceAndAttri2.attributeName;
if (hasMultipleIndex(context)) {
return namespace ? _extends({}, searchState, {
indices: _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], _defineProperty({}, namespace, (0, _omit3.default)(searchState.indices[index][namespace], '' + attributeName)))))
}) : (0, _omit3.default)(searchState, 'indices.' + index + '.' + id);
} else {
return namespace ? _extends({}, searchState, _defineProperty({}, namespace, (0, _omit3.default)(searchState[namespace], '' + attributeName))) : (0, _omit3.default)(searchState, '' + id);
}
}
/***/ }),
/* 6 */
/***/ (function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ }),
/* 7 */
/***/ (function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16),
getRawTag = __webpack_require__(124),
objectToString = __webpack_require__(125);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(89),
baseKeys = __webpack_require__(79),
isArrayLike = __webpack_require__(11);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(123),
getValue = __webpack_require__(128);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(19),
isLength = __webpack_require__(42);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ }),
/* 12 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
var baseMatches = __webpack_require__(257),
baseMatchesProperty = __webpack_require__(260),
identity = __webpack_require__(26),
isArray = __webpack_require__(1),
property = __webpack_require__(262);
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
module.exports = baseIteratee;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
var baseKeys = __webpack_require__(79),
getTag = __webpack_require__(57),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1),
isArrayLike = __webpack_require__(11),
isBuffer = __webpack_require__(21),
isPrototype = __webpack_require__(38),
isTypedArray = __webpack_require__(34);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
/***/ }),
/* 15 */,
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseIteratee = __webpack_require__(13),
baseMap = __webpack_require__(183),
isArray = __webpack_require__(1);
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, baseIteratee(iteratee, 3));
}
module.exports = map;
/***/ }),
/* 18 */
/***/ (function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObject = __webpack_require__(6);
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(147),
isObjectLike = __webpack_require__(7);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3),
stubFalse = __webpack_require__(148);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(56)(module)))
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(1),
isKey = __webpack_require__(64),
stringToPath = __webpack_require__(156),
toString = __webpack_require__(65);
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
module.exports = castPath;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
module.exports = isSymbol;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(23);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = toKey;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(26),
overRest = __webpack_require__(166),
setToString = __webpack_require__(93);
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
module.exports = baseRest;
/***/ }),
/* 26 */
/***/ (function(module, exports) {
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(96),
baseAssignValue = __webpack_require__(47);
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
module.exports = copyObject;
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(113),
listCacheDelete = __webpack_require__(114),
listCacheGet = __webpack_require__(115),
listCacheHas = __webpack_require__(116),
listCacheSet = __webpack_require__(117);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(18);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(137);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ }),
/* 32 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ }),
/* 33 */,
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(149),
baseUnary = __webpack_require__(43),
nodeUtil = __webpack_require__(150);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseClone = __webpack_require__(229),
baseUnset = __webpack_require__(245),
castPath = __webpack_require__(22),
copyObject = __webpack_require__(27),
customOmitClone = __webpack_require__(247),
flatRest = __webpack_require__(176),
getAllKeysIn = __webpack_require__(97);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
module.exports = omit;
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(95),
baseEach = __webpack_require__(73),
castFunction = __webpack_require__(179),
isArray = __webpack_require__(1);
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, castFunction(iteratee));
}
module.exports = forEach;
/***/ }),
/* 37 */
/***/ (function(module, exports) {
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
module.exports = replaceHolders;
/***/ }),
/* 38 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(28),
stackClear = __webpack_require__(118),
stackDelete = __webpack_require__(119),
stackGet = __webpack_require__(120),
stackHas = __webpack_require__(121),
stackSet = __webpack_require__(122);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(129),
mapCacheDelete = __webpack_require__(136),
mapCacheGet = __webpack_require__(138),
mapCacheHas = __webpack_require__(139),
mapCacheSet = __webpack_require__(140);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ }),
/* 42 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ }),
/* 43 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.defer = undefined;
var _isPlainObject2 = __webpack_require__(45);
var _isPlainObject3 = _interopRequireDefault(_isPlainObject2);
var _isEmpty2 = __webpack_require__(14);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
exports.shallowEqual = shallowEqual;
exports.isSpecialClick = isSpecialClick;
exports.capitalize = capitalize;
exports.assertFacetDefined = assertFacetDefined;
exports.getDisplayName = getDisplayName;
exports.removeEmptyKey = removeEmptyKey;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
function isSpecialClick(event) {
var isMiddleClick = event.button === 1;
return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
}
function capitalize(key) {
return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1);
}
function assertFacetDefined(searchParameters, searchResults, facet) {
var wasRequested = searchParameters.isConjunctiveFacet(facet) || searchParameters.isDisjunctiveFacet(facet);
var wasReceived = Boolean(searchResults.getFacetByName(facet));
if (searchResults.nbHits > 0 && wasRequested && !wasReceived) {
// eslint-disable-next-line no-console
console.warn('A component requested values for facet "' + facet + '", but no facet ' + 'values were retrieved from the API. This means that you should add ' + ('the attribute "' + facet + '" to the list of attributes for faceting in ') + 'your index settings.');
}
}
function getDisplayName(Component) {
return Component.displayName || Component.name || 'UnknownComponent';
}
var resolved = Promise.resolve();
var defer = exports.defer = function defer(f) {
resolved.then(f);
};
function removeEmptyKey(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if ((0, _isEmpty3.default)(value) && (0, _isPlainObject3.default)(value)) {
delete obj[key];
} else if ((0, _isPlainObject3.default)(value)) {
removeEmptyKey(value);
}
});
return obj;
}
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
getPrototype = __webpack_require__(67),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
module.exports = isPlainObject;
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(163),
baseIsNaN = __webpack_require__(225),
strictIndexOf = __webpack_require__(226);
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
module.exports = baseIndexOf;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(168);
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
module.exports = baseAssignValue;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(89),
baseKeysIn = __webpack_require__(232),
isArrayLike = __webpack_require__(11);
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
module.exports = keysIn;
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
var baseFor = __webpack_require__(178),
keys = __webpack_require__(9);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
var arrayReduce = __webpack_require__(99),
baseEach = __webpack_require__(73),
baseIteratee = __webpack_require__(13),
baseReduce = __webpack_require__(265),
isArray = __webpack_require__(1);
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
module.exports = reduce;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
var toFinite = __webpack_require__(213);
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
module.exports = toInteger;
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isArray = __webpack_require__(1),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var stringTag = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
module.exports = isString;
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
var createFind = __webpack_require__(267),
findIndex = __webpack_require__(186);
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
module.exports = find;
/***/ }),
/* 54 */
/***/ (function(module, exports) {
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = func;
return object.placeholder;
}
module.exports = getHolder;
/***/ }),
/* 55 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 56 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if(!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(152),
Map = __webpack_require__(40),
Promise = __webpack_require__(153),
Set = __webpack_require__(154),
WeakMap = __webpack_require__(90),
baseGetTag = __webpack_require__(8),
toSource = __webpack_require__(77);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
var baseHas = __webpack_require__(155),
hasPath = __webpack_require__(91);
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
module.exports = has;
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(112),
isObjectLike = __webpack_require__(7);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(41),
setCacheAdd = __webpack_require__(141),
setCacheHas = __webpack_require__(142);
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
/***/ }),
/* 61 */
/***/ (function(module, exports) {
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
/***/ }),
/* 62 */
/***/ (function(module, exports) {
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(87),
stubArray = __webpack_require__(88);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
module.exports = getSymbols;
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(1),
isSymbol = __webpack_require__(23);
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
module.exports = isKey;
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(66);
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
module.exports = toString;
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16),
arrayMap = __webpack_require__(12),
isArray = __webpack_require__(1),
isSymbol = __webpack_require__(23);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = baseToString;
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(80);
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
/***/ }),
/* 68 */
/***/ (function(module, exports) {
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
module.exports = apply;
/***/ }),
/* 69 */
/***/ (function(module, exports) {
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = copyArray;
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6);
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
module.exports = baseCreate;
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(22),
toKey = __webpack_require__(24);
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
module.exports = baseGet;
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(71);
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
module.exports = get;
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(49),
createBaseEach = __webpack_require__(255);
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
module.exports = baseEach;
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46),
toInteger = __webpack_require__(51);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
module.exports = indexOf;
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(70),
isObject = __webpack_require__(6);
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
module.exports = createCtor;
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)))
/***/ }),
/* 77 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(60),
arraySome = __webpack_require__(143),
cacheHas = __webpack_require__(61);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(38),
nativeKeys = __webpack_require__(151);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ }),
/* 80 */
/***/ (function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(59);
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ }),
/* 83 */
/***/ (function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ }),
/* 84 */
/***/ (function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(86),
getSymbols = __webpack_require__(63),
keys = __webpack_require__(9);
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
module.exports = getAllKeys;
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(62),
isArray = __webpack_require__(1);
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
module.exports = baseGetAllKeys;
/***/ }),
/* 87 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = arrayFilter;
/***/ }),
/* 88 */
/***/ (function(module, exports) {
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
module.exports = stubArray;
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(146),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(21),
isIndex = __webpack_require__(32),
isTypedArray = __webpack_require__(34);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(22),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1),
isIndex = __webpack_require__(32),
isLength = __webpack_require__(42),
toKey = __webpack_require__(24);
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
module.exports = hasPath;
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46);
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
module.exports = arrayIncludes;
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetToString = __webpack_require__(228),
shortOut = __webpack_require__(169);
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
module.exports = setToString;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(11),
isObjectLike = __webpack_require__(7);
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
module.exports = isArrayLikeObject;
/***/ }),
/* 95 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(47),
eq = __webpack_require__(18);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignValue;
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(86),
getSymbolsIn = __webpack_require__(171),
keysIn = __webpack_require__(48);
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
module.exports = getAllKeysIn;
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
var Uint8Array = __webpack_require__(82);
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
module.exports = cloneArrayBuffer;
/***/ }),
/* 99 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
module.exports = arrayReduce;
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(9);
var intersection = __webpack_require__(250);
var forOwn = __webpack_require__(253);
var forEach = __webpack_require__(36);
var filter = __webpack_require__(101);
var map = __webpack_require__(17);
var reduce = __webpack_require__(50);
var omit = __webpack_require__(35);
var indexOf = __webpack_require__(74);
var isNaN = __webpack_require__(214);
var isArray = __webpack_require__(1);
var isEmpty = __webpack_require__(14);
var isEqual = __webpack_require__(81);
var isUndefined = __webpack_require__(185);
var isString = __webpack_require__(52);
var isFunction = __webpack_require__(19);
var find = __webpack_require__(53);
var trim = __webpack_require__(187);
var defaults = __webpack_require__(102);
var merge = __webpack_require__(103);
var valToNumber = __webpack_require__(280);
var filterState = __webpack_require__(281);
var RefinementList = __webpack_require__(282);
/**
* like _.find but using _.isEqual to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into
* @param {any} searchedValue the value we're looking for
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find(array, function(currentValue) {
return isEqual(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* Targeted index. This parameter is mandatory.
* @member {string}
*/
this.index = params.index || '';
// Query
/**
* Query string of the instant search. The empty string is a valid query.
* @member {string}
* @see https://www.algolia.com/doc/rest#param-query
*/
this.query = params.query || '';
// Facets
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
// Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* separated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
/**
* Contains the numeric filters in the raw format of the Algolia API. Setting
* this parameter is not compatible with the usage of numeric filters methods.
* @see https://www.algolia.com/doc/javascript#numericFilters
* @member {string}
*/
this.numericFilters = params.numericFilters;
/**
* Contains the tag filters in the raw format of the Algolia API. Setting this
* parameter is not compatible with the of the add/remove/toggle methods of the
* tag api.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.tagFilters = params.tagFilters;
/**
* Contains the optional tag filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalTagFilters = params.optionalTagFilters;
/**
* Contains the optional facet filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalFacetFilters = params.optionalFacetFilters;
// Misc. parameters
/**
* Number of hits to be returned by the search API
* @member {number}
* @see https://www.algolia.com/doc/rest#param-hitsPerPage
*/
this.hitsPerPage = params.hitsPerPage;
/**
* Number of values for each faceted attribute
* @member {number}
* @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet
*/
this.maxValuesPerFacet = params.maxValuesPerFacet;
/**
* The current page number
* @member {number}
* @see https://www.algolia.com/doc/rest#param-page
*/
this.page = params.page || 0;
/**
* How the query should be treated by the search engine.
* Possible values: prefixAll, prefixLast, prefixNone
* @see https://www.algolia.com/doc/rest#param-queryType
* @member {string}
*/
this.queryType = params.queryType;
/**
* How the typo tolerance behave in the search engine.
* Possible values: true, false, min, strict
* @see https://www.algolia.com/doc/rest#param-typoTolerance
* @member {string}
*/
this.typoTolerance = params.typoTolerance;
/**
* Number of characters to wait before doing one character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo
* @member {number}
*/
this.minWordSizefor1Typo = params.minWordSizefor1Typo;
/**
* Number of characters to wait before doing a second character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos
* @member {number}
*/
this.minWordSizefor2Typos = params.minWordSizefor2Typos;
/**
* Configure the precision of the proximity ranking criterion
* @see https://www.algolia.com/doc/rest#param-minProximity
*/
this.minProximity = params.minProximity;
/**
* Should the engine allow typos on numerics.
* @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens
* @member {boolean}
*/
this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens;
/**
* Should the plurals be ignored
* @see https://www.algolia.com/doc/rest#param-ignorePlurals
* @member {boolean}
*/
this.ignorePlurals = params.ignorePlurals;
/**
* Restrict which attribute is searched.
* @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes
* @member {string}
*/
this.restrictSearchableAttributes = params.restrictSearchableAttributes;
/**
* Enable the advanced syntax.
* @see https://www.algolia.com/doc/rest#param-advancedSyntax
* @member {boolean}
*/
this.advancedSyntax = params.advancedSyntax;
/**
* Enable the analytics
* @see https://www.algolia.com/doc/rest#param-analytics
* @member {boolean}
*/
this.analytics = params.analytics;
/**
* Tag of the query in the analytics.
* @see https://www.algolia.com/doc/rest#param-analyticsTags
* @member {string}
*/
this.analyticsTags = params.analyticsTags;
/**
* Enable the synonyms
* @see https://www.algolia.com/doc/rest#param-synonyms
* @member {boolean}
*/
this.synonyms = params.synonyms;
/**
* Should the engine replace the synonyms in the highlighted results.
* @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight
* @member {boolean}
*/
this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight;
/**
* Add some optional words to those defined in the dashboard
* @see https://www.algolia.com/doc/rest#param-optionalWords
* @member {string}
*/
this.optionalWords = params.optionalWords;
/**
* Possible values are "lastWords" "firstWords" "allOptional" "none" (default)
* @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults
* @member {string}
*/
this.removeWordsIfNoResults = params.removeWordsIfNoResults;
/**
* List of attributes to retrieve
* @see https://www.algolia.com/doc/rest#param-attributesToRetrieve
* @member {string}
*/
this.attributesToRetrieve = params.attributesToRetrieve;
/**
* List of attributes to highlight
* @see https://www.algolia.com/doc/rest#param-attributesToHighlight
* @member {string}
*/
this.attributesToHighlight = params.attributesToHighlight;
/**
* Code to be embedded on the left part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPreTag
* @member {string}
*/
this.highlightPreTag = params.highlightPreTag;
/**
* Code to be embedded on the right part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPostTag
* @member {string}
*/
this.highlightPostTag = params.highlightPostTag;
/**
* List of attributes to snippet
* @see https://www.algolia.com/doc/rest#param-attributesToSnippet
* @member {string}
*/
this.attributesToSnippet = params.attributesToSnippet;
/**
* Enable the ranking informations in the response, set to 1 to activate
* @see https://www.algolia.com/doc/rest#param-getRankingInfo
* @member {number}
*/
this.getRankingInfo = params.getRankingInfo;
/**
* Remove duplicates based on the index setting attributeForDistinct
* @see https://www.algolia.com/doc/rest#param-distinct
* @member {boolean|number}
*/
this.distinct = params.distinct;
/**
* Center of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundLatLng
* @member {string}
*/
this.aroundLatLng = params.aroundLatLng;
/**
* Center of the search, retrieve from the user IP.
* @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP
* @member {boolean}
*/
this.aroundLatLngViaIP = params.aroundLatLngViaIP;
/**
* Radius of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundRadius
* @member {number}
*/
this.aroundRadius = params.aroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundPrecision
* @member {number}
*/
this.minimumAroundRadius = params.minimumAroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-minimumAroundRadius
* @member {number}
*/
this.aroundPrecision = params.aroundPrecision;
/**
* Geo search inside a box.
* @see https://www.algolia.com/doc/rest#param-insideBoundingBox
* @member {string}
*/
this.insideBoundingBox = params.insideBoundingBox;
/**
* Geo search inside a polygon.
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.insidePolygon = params.insidePolygon;
/**
* Allows to specify an ellipsis character for the snippet when we truncate the text
* (added before and after if truncated).
* The default value is an empty string and we recommend to set it to "…"
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.snippetEllipsisText = params.snippetEllipsisText;
/**
* Allows to specify some attributes name on which exact won't be applied.
* Attributes are separated with a comma (for example "name,address" ), you can also use a
* JSON string array encoding (for example encodeURIComponent('["name","address"]') ).
* By default the list is empty.
* @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes
* @member {string|string[]}
*/
this.disableExactOnAttributes = params.disableExactOnAttributes;
/**
* Applies 'exact' on single word queries if the word contains at least 3 characters
* and is not a stop word.
* Can take two values: true or false.
* By default, its set to false.
* @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery
* @member {boolean}
*/
this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery;
// Undocumented parameters, still needed otherwise we fail
this.offset = params.offset;
this.length = params.length;
var self = this;
forOwn(params, function checkForUnknownParameter(paramValue, paramName) {
if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) {
self[paramName] = paramValue;
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = keys(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function(partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = [
'aroundPrecision',
'aroundRadius',
'getRankingInfo',
'minWordSizefor2Typos',
'minWordSizefor1Typo',
'page',
'maxValuesPerFacet',
'distinct',
'minimumAroundRadius',
'hitsPerPage',
'minProximity'
];
forEach(numberKeys, function(k) {
var value = partialState[k];
if (isString(value)) {
var parsedValue = parseFloat(value);
numbers[k] = isNaN(parsedValue) ? value : parsedValue;
}
});
if (partialState.numericRefinements) {
var numericRefinements = {};
forEach(partialState.numericRefinements, function(operators, attribute) {
numericRefinements[attribute] = {};
forEach(operators, function(values, operator) {
var parsedValues = map(values, function(v) {
if (isArray(v)) {
return map(v, function(vPrime) {
if (isString(vPrime)) {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (isString(v)) {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
forEach(newParameters.hierarchicalFacets, function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
}
// get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error(
'[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' +
'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error(
'[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' +
'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (currentState.numericFilters && params.numericRefinements && !isEmpty(params.numericRefinements)) {
return new Error(
"[Numeric filters] Can't switch from the advanced to the managed API. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
if (!isEmpty(currentState.numericRefinements) && params.numericFilters) {
return new Error(
"[Numeric filters] Can't switch from the managed API to the advanced. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var clear = RefinementList.clearRefinement;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'),
facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'),
disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'),
hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet')
});
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) faceting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function(attribute, operator, v) {
var value = valToNumber(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge({}, this.numericRefinements);
mod[attribute] = merge({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getConjunctiveRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsRefinements[facetName] || [];
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getDisjunctiveRefinements: function(facetName) {
if (!this.isDisjunctiveFacet(facetName)) {
throw new Error(
facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration'
);
}
return this.disjunctiveFacetsRefinements[facetName] || [];
},
/**
* Get the list of hierarchical refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getHierarchicalRefinement: function(facetName) {
// we send an array but we currently do not support multiple
// hierarchicalRefinements for a hierarchicalFacet
return this.hierarchicalFacetsRefinements[facetName] || [];
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getExcludeRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsExcludes[facetName] || [];
},
/**
* Remove all the numeric filter for a given (attribute, operator)
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} [number] the value to be removed
* @return {SearchParameters}
*/
removeNumericRefinement: function(attribute, operator, paramValue) {
if (paramValue !== undefined) {
var paramValueAsNumber = valToNumber(paramValue);
if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator && isEqual(value.val, paramValueAsNumber);
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(this.numericRefinements, attribute);
} else if (isFunction(attribute)) {
return reduce(this.numericRefinements, function(memo, operators, key) {
var operatorList = {};
forEach(operators, function(values, operator) {
var outValues = [];
forEach(values, function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (!isEmpty(outValues)) operatorList[operator] = outValues;
});
if (!isEmpty(operatorList)) memo[key] = operatorList;
return memo;
}, {});
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error(
'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Exclude a value from a "normal" facet
* @method
* @param {string} facet attribute to apply the exclusion on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Adds a refinement on a disjunctive facet.
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.addRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.concat(tag)
};
return this.setQueryParameters(modification);
},
/**
* Remove a facet from the facets attribute of the helper configuration, if it
* is present.
* @method
* @param {string} facet facet name to remove
* @return {SearchParameters}
*/
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
facets: filter(this.facets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: filter(this.disjunctiveFacets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: filter(this.hierarchicalFacets, function(f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the faceted attribute.
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} [value] value used to filter
* @return {SearchParameters}
*/
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Remove a negative refinement on a facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Remove a refinement on a disjunctive facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.removeRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Remove a tag from the list of tag refinements
* @method
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; })
};
return this.setQueryParameters(modification);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
* @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement}
*/
toggleRefinement: function toggleRefinement(facet, value) {
return this.toggleFacetRefinement(facet, value);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
*/
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) {
return this.toggleHierarchicalFacetRefinement(facet, value);
} else if (this.isConjunctiveFacet(facet)) {
return this.toggleConjunctiveFacetRefinement(facet, value);
} else if (this.isDisjunctiveFacet(facet)) {
return this.toggleDisjunctiveFacetRefinement(facet, value);
}
throw new Error('Cannot refine the undeclared facet ' + facet +
'; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.toggleRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined &&
this.hierarchicalFacetsRefinements[facet].length > 0 && (
// remove current refinement:
// refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0] === value ||
// remove a parent refinement of the current refinement:
// - refinement was 'beer > IPA > Flying dog'
// - call is toggleRefine('beer > IPA')
// - refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0
);
if (upOneOrMultipleLevel) {
if (value.indexOf(separator) === -1) {
// go back to root level
mod[facet] = [];
} else {
mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
}
} else {
mod[facet] = [value];
}
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is not refined.');
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function(facet) {
return indexOf(this.disjunctiveFacets, facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function(facet) {
return indexOf(this.facets, facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value, optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
/**
* Returns true if the facet contains exclusions or if a specific value is
* excluded.
*
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return indexOf(refinements, value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (isUndefined(value) && isUndefined(operator)) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined = this.numericRefinements[attribute] &&
!isUndefined(this.numericRefinements[attribute][operator]);
if (isUndefined(value) || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber(value);
var isAttributeValueDefined = !isUndefined(
findArray(this.numericRefinements[attribute][operator], parsedValue)
);
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return indexOf(this.tagRefinements, tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection(
keys(this.numericRefinements),
this.disjunctiveFacets
);
return keys(this.disjunctiveFacetsRefinements)
.concat(disjunctiveNumericRefinedFacets)
.concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
return intersection(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
map(this.hierarchicalFacets, 'name'),
keys(this.hierarchicalFacetsRefinements)
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return filter(this.disjunctiveFacets, function(f) {
return indexOf(refinedFacets, f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
forOwn(this, function(paramValue, paramName) {
if (indexOf(managedParameters, paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user retrieve any parameter value from the SearchParameters
* @param {string} paramName name of the parameter
* @return {any} the value of the parameter
*/
getQueryParameter: function getQueryParameter(paramName) {
if (!this.hasOwnProperty(paramName)) {
throw new Error(
"Parameter '" + paramName + "' is not an attribute of SearchParameters " +
'(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)');
}
return this[paramName];
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var parsedParams = SearchParameters._parseNumbers(params);
return this.mutateMe(function mergeWith(newInstance) {
var ks = keys(params);
forEach(ks, function(k) {
newInstance[k] = parsedParams[k];
});
return newInstance;
});
},
/**
* Returns an object with only the selected attributes.
* @param {string[]} filters filters to retrieve only a subset of the state. It
* accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage)
* or attributes of the index with the notation 'attribute:nameOfMyAttribute'
* @return {object}
*/
filter: function(filters) {
return filterState(this, filters);
},
/**
* Helper function to make it easier to build new instances from a mutating
* function
* @private
* @param {function} fn newMutableState -> previousState -> () function that will
* change the value of the newMutable to the desired state
* @return {SearchParameters} a new instance with the specified modifications applied
*/
mutateMe: function mutateMe(fn) {
var newState = new this.constructor(this);
fn(newState, this);
return newState;
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find(
this.hierarchicalFacets,
{name: hierarchicalFacetName}
);
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
throw new Error(
'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return map(path, trim);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
module.exports = SearchParameters;
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(87),
baseFilter = __webpack_require__(256),
baseIteratee = __webpack_require__(13),
isArray = __webpack_require__(1);
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, baseIteratee(predicate, 3));
}
module.exports = filter;
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(68),
assignInWith = __webpack_require__(275),
baseRest = __webpack_require__(25),
customDefaultsAssignIn = __webpack_require__(276);
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(args) {
args.push(undefined, customDefaultsAssignIn);
return apply(assignInWith, undefined, args);
});
module.exports = defaults;
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(277),
createAssigner = __webpack_require__(188);
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
module.exports = merge;
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
var baseOrderBy = __webpack_require__(289),
isArray = __webpack_require__(1);
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
module.exports = orderBy;
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(191),
createBind = __webpack_require__(294),
createCurry = __webpack_require__(295),
createHybrid = __webpack_require__(193),
createPartial = __webpack_require__(307),
getData = __webpack_require__(197),
mergeData = __webpack_require__(308),
setData = __webpack_require__(199),
setWrapToString = __webpack_require__(200),
toInteger = __webpack_require__(51);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
module.exports = createWrap;
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(70),
baseLodash = __webpack_require__(107);
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
module.exports = LazyWrapper;
/***/ }),
/* 107 */
/***/ (function(module, exports) {
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
module.exports = baseLodash;
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
exports.arrayToObject = function (source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
target[source] = true;
}
} else {
return [target, source];
}
return target;
}
if (typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
if (target[i] && typeof target[i] === 'object') {
target[i] = exports.merge(target[i], item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (has.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.assign = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function (acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D // -
|| c === 0x2E // .
|| c === 0x5F // _
|| c === 0x7E // ~
|| (c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)]
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function (obj, references) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && typeof obj[i] === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
keys.forEach(function (key) {
obj[key] = exports.compact(obj[key], refs);
});
return obj;
};
exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
/***/ }),
/* 109 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
var basePick = __webpack_require__(326),
flatRest = __webpack_require__(176);
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
module.exports = pick;
/***/ }),
/* 111 */,
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
equalArrays = __webpack_require__(78),
equalByTag = __webpack_require__(144),
equalObjects = __webpack_require__(145),
getTag = __webpack_require__(57),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(21),
isTypedArray = __webpack_require__(34);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
/***/ }),
/* 113 */
/***/ (function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(29);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(29);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(29);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(29);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(28);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ }),
/* 119 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ }),
/* 120 */
/***/ (function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ }),
/* 121 */
/***/ (function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(28),
Map = __webpack_require__(40),
MapCache = __webpack_require__(41);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(19),
isMasked = __webpack_require__(126),
isObject = __webpack_require__(6),
toSource = __webpack_require__(77);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
/***/ }),
/* 125 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(127);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ }),
/* 128 */
/***/ (function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(130),
ListCache = __webpack_require__(28),
Map = __webpack_require__(40);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(131),
hashDelete = __webpack_require__(132),
hashGet = __webpack_require__(133),
hashHas = __webpack_require__(134),
hashSet = __webpack_require__(135);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(30);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ }),
/* 132 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(30);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(30);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(30);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(31);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ }),
/* 137 */
/***/ (function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(31);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(31);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(31);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ }),
/* 141 */
/***/ (function(module, exports) {
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
/***/ }),
/* 142 */
/***/ (function(module, exports) {
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
/***/ }),
/* 143 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16),
Uint8Array = __webpack_require__(82),
eq = __webpack_require__(18),
equalArrays = __webpack_require__(78),
mapToArray = __webpack_require__(83),
setToArray = __webpack_require__(84);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
var getAllKeys = __webpack_require__(85);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ }),
/* 146 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ }),
/* 148 */
/***/ (function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isLength = __webpack_require__(42),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(76);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(56)(module)))
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(80);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ }),
/* 155 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
module.exports = baseHas;
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
var memoizeCapped = __webpack_require__(157);
/** Used to match property names within property paths. */
var reLeadingDot = /^\./,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (reLeadingDot.test(string)) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
module.exports = stringToPath;
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
var memoize = __webpack_require__(158);
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
module.exports = memoizeCapped;
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(41);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
module.exports = memoize;
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var emptyFunction = __webpack_require__(160);
var invariant = __webpack_require__(161);
var ReactPropTypesSecret = __webpack_require__(162);
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (false) {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/* 163 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ }),
/* 164 */
/***/ (function(module, exports) {
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
module.exports = arrayIncludesWith;
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(62),
isFlattenable = __webpack_require__(227);
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
module.exports = baseFlatten;
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(68);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
module.exports = overRest;
/***/ }),
/* 167 */
/***/ (function(module, exports) {
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = constant;
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10);
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
module.exports = defineProperty;
/***/ }),
/* 169 */
/***/ (function(module, exports) {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
module.exports = shortOut;
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(56)(module)))
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(62),
getPrototype = __webpack_require__(67),
getSymbols = __webpack_require__(63),
stubArray = __webpack_require__(88);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
module.exports = getSymbolsIn;
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(98);
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
module.exports = cloneTypedArray;
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(70),
getPrototype = __webpack_require__(67),
isPrototype = __webpack_require__(38);
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
module.exports = initCloneObject;
/***/ }),
/* 174 */
/***/ (function(module, exports) {
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
module.exports = last;
/***/ }),
/* 175 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
var flatten = __webpack_require__(177),
overRest = __webpack_require__(166),
setToString = __webpack_require__(93);
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
module.exports = flatRest;
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
var baseFlatten = __webpack_require__(165);
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
module.exports = flatten;
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
var createBaseFor = __webpack_require__(254);
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(26);
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
module.exports = castFunction;
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6);
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
module.exports = isStrictComparable;
/***/ }),
/* 181 */
/***/ (function(module, exports) {
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
module.exports = matchesStrictComparable;
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
var baseHasIn = __webpack_require__(261),
hasPath = __webpack_require__(91);
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
module.exports = hasIn;
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(73),
isArrayLike = __webpack_require__(11);
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
module.exports = baseMap;
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
module.exports = isNumber;
/***/ }),
/* 185 */
/***/ (function(module, exports) {
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
module.exports = isUndefined;
/***/ }),
/* 186 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(163),
baseIteratee = __webpack_require__(13),
toInteger = __webpack_require__(51);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index);
}
module.exports = findIndex;
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(66),
castSlice = __webpack_require__(268),
charsEndIndex = __webpack_require__(269),
charsStartIndex = __webpack_require__(270),
stringToArray = __webpack_require__(271),
toString = __webpack_require__(65);
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
module.exports = trim;
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(25),
isIterateeCall = __webpack_require__(215);
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(47),
eq = __webpack_require__(18);
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignMergeValue;
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(36);
var compact = __webpack_require__(283);
var indexOf = __webpack_require__(74);
var findIndex = __webpack_require__(186);
var get = __webpack_require__(72);
var sumBy = __webpack_require__(284);
var find = __webpack_require__(53);
var includes = __webpack_require__(286);
var map = __webpack_require__(17);
var orderBy = __webpack_require__(104);
var defaults = __webpack_require__(102);
var merge = __webpack_require__(103);
var isArray = __webpack_require__(1);
var isFunction = __webpack_require__(19);
var partial = __webpack_require__(293);
var partialRight = __webpack_require__(309);
var formatSort = __webpack_require__(201);
var generateHierarchicalTree = __webpack_require__(312);
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the faceting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objects matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} value the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric filters.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
function getIndices(obj) {
var indices = {};
forEach(obj, function(val, idx) { indices[val] = idx; });
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find(
hierarchicalFacets,
function facetKeyMatchesAttribute(hierarchicalFacet) {
return includes(hierarchicalFacet.attributes, hierarchicalAttributeName);
}
);
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, results) {
var mainSubResponse = results[0];
this._rawResults = results;
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = sumBy(results, 'processingTimeMS');
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutCounts = mainSubResponse.timeoutCounts;
/**
* Boolean that indicates if the computation of the hits did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutHits = mainSubResponse.timeoutHits;
/**
* True if the counts of the facets is exhaustive
* @member {boolean}
*/
this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount;
/**
* True if the number of hits is exhaustive
* @member {boolean}
*/
this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = map(state.hierarchicalFacets, function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this;
// Since we send request only for disjunctive facets that have been refined,
// we get the facets informations from the first, general, response.
forEach(mainSubResponse.facets, function(facetValueObject, facetKey) {
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(
state.hierarchicalFacets,
facetKey
);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = indexOf(state.disjunctiveFacets, facetKey) !== -1;
var isFacetConjunctive = indexOf(state.facets, facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
// Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact(this.hierarchicalFacets);
// aggregate the refined disjunctive facets
forEach(disjunctiveFacets, function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
forEach(result.facets, function(facetResults, dfacet) {
var position;
if (hierarchicalFacet) {
position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge(
{},
self.hierarchicalFacets[position][attributeIndex].data,
facetResults
);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaults({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
indexOf(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = results[nextDisjunctiveResult];
forEach(result.facets, function(facetResults, dfacet) {
var position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
// when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaults(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
forEach(state.facetsExcludes, function(excludes, facetName) {
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
forEach(excludes, function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
this.hierarchicalFacets = map(this.hierarchicalFacets, generateHierarchicalTree(state));
this.facets = compact(this.facets);
this.disjunctiveFacets = compact(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the faceted attribute
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
var predicate = {name: name};
return find(this.facets, predicate) ||
find(this.disjunctiveFacets, predicate) ||
find(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the faceted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
var predicate = {name: attribute};
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find(results.facets, predicate);
if (!facet) return [];
return map(facet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isFacetRefined(attribute, k),
isExcluded: results._state.isExcludeRefined(attribute, k)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return map(disjunctiveFacet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = map(node.data, partial(recSort, sortFn));
var sortedChildren = sortFn(children);
var newNode = merge({}, node, {data: sortedChildren});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('results', function(content){
* //get values ordered only by name ascending using the string predicate
* content.getFacetValues('city', {sortBy: ['name:asc']});
* //get values ordered only by count ascending using a function
* content.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.');
var options = defaults({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (isArray(facetValues)) {
return orderBy(facetValues, order[0], order[1]);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partialRight(orderBy, order[0], order[1]), facetValues);
} else if (isFunction(options.sortBy)) {
if (isArray(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partial(vanillaSortFn, options.sortBy), facetValues);
}
throw new Error(
'options.sortBy is optional but if defined it must be ' +
'either an array of string (predicates) or a sorting function'
);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the faceted attribute
* @return {object} The stats of the facet
*/
SearchResults.prototype.getFacetStats = function(attribute) {
if (this._state.isConjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.facets, attribute);
} else if (this._state.isDisjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
}
throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`');
};
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find(facetList, {name: facetName});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhausistivity for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
forEach(state.facetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
forEach(state.facetsExcludes, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
forEach(state.disjunctiveFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
forEach(state.hierarchicalFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
forEach(state.numericRefinements, function(operators, attributeName) {
forEach(operators, function(values, operator) {
forEach(values, function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
forEach(state.tagRefinements, function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var count = get(facet, 'data[' + name + ']');
var exhaustive = get(facet, 'exhaustive');
return {
type: type,
attributeName: attributeName,
name: name,
count: count || 0,
exhaustive: exhaustive || false
};
}
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var splitted = name.split(facetDeclaration.separator);
var configuredName = splitted[splitted.length - 1];
for (var i = 0; facet !== undefined && i < splitted.length; ++i) {
facet = find(facet.data, {name: splitted[i]});
}
var count = get(facet, 'count');
var exhaustive = get(facet, 'exhaustive');
return {
type: 'hierarchical',
attributeName: attributeName,
name: configuredName,
count: count || 0,
exhaustive: exhaustive || false
};
}
module.exports = SearchResults;
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(26),
metaMap = __webpack_require__(192);
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
module.exports = baseSetData;
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
var WeakMap = __webpack_require__(90);
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(194),
composeArgsRight = __webpack_require__(195),
countHolders = __webpack_require__(296),
createCtor = __webpack_require__(75),
createRecurry = __webpack_require__(196),
getHolder = __webpack_require__(54),
reorder = __webpack_require__(306),
replaceHolders = __webpack_require__(37),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_ARY_FLAG = 128,
WRAP_FLIP_FLAG = 512;
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
module.exports = createHybrid;
/***/ }),
/* 194 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
module.exports = composeArgs;
/***/ }),
/* 195 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
module.exports = composeArgsRight;
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
var isLaziable = __webpack_require__(297),
setData = __webpack_require__(199),
setWrapToString = __webpack_require__(200);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
module.exports = createRecurry;
/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {
var metaMap = __webpack_require__(192),
noop = __webpack_require__(298);
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
module.exports = getData;
/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(70),
baseLodash = __webpack_require__(107);
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
module.exports = LodashWrapper;
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(191),
shortOut = __webpack_require__(169);
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
module.exports = setData;
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
var getWrapDetails = __webpack_require__(303),
insertWrapDetails = __webpack_require__(304),
setToString = __webpack_require__(93),
updateWrapDetails = __webpack_require__(305);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
module.exports = setWrapToString;
/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var reduce = __webpack_require__(50);
var find = __webpack_require__(53);
var startsWith = __webpack_require__(310);
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
module.exports = function formatSort(sortBy, defaults) {
return reduce(sortBy, function preparePredicate(out, sortInstruction) {
var sortInstructions = sortInstruction.split(':');
if (defaults && sortInstructions.length === 1) {
var similarDefault = find(defaults, function(predicate) {
return startsWith(predicate, sortInstruction[0]);
});
if (similarDefault) {
sortInstructions = similarDefault.split(':');
}
}
out[0].push(sortInstructions[0]);
out[1].push(sortInstructions[1]);
return out;
}, [[], []]);
};
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(71),
baseSet = __webpack_require__(314),
castPath = __webpack_require__(22);
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
module.exports = basePickBy;
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = __webpack_require__(316);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(317);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55), __webpack_require__(109)))
/***/ }),
/* 204 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Module containing the functions to serialize and deserialize
* {SearchParameters} in the query string format
* @module algoliasearchHelper.url
*/
var shortener = __webpack_require__(319);
var SearchParameters = __webpack_require__(100);
var qs = __webpack_require__(322);
var bind = __webpack_require__(325);
var forEach = __webpack_require__(36);
var pick = __webpack_require__(110);
var map = __webpack_require__(17);
var mapKeys = __webpack_require__(327);
var mapValues = __webpack_require__(328);
var isString = __webpack_require__(52);
var isPlainObject = __webpack_require__(45);
var isArray = __webpack_require__(1);
var isEmpty = __webpack_require__(14);
var invert = __webpack_require__(206);
var encode = __webpack_require__(108).encode;
function recursiveEncode(input) {
if (isPlainObject(input)) {
return mapValues(input, recursiveEncode);
}
if (isArray(input)) {
return map(input, recursiveEncode);
}
if (isString(input)) {
return encode(input);
}
return input;
}
var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR'];
var stateKeys = shortener.ENCODED_PARAMETERS;
function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) {
if (prefixRegexp !== null) {
a = a.replace(prefixRegexp, '');
b = b.replace(prefixRegexp, '');
}
a = invertedMapping[a] || a;
b = invertedMapping[b] || b;
if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) {
if (a === 'q') return -1;
if (b === 'q') return 1;
var isARefinements = refinementsParameters.indexOf(a) !== -1;
var isBRefinements = refinementsParameters.indexOf(b) !== -1;
if (isARefinements && !isBRefinements) {
return 1;
} else if (isBRefinements && !isARefinements) {
return -1;
}
}
return a.localeCompare(b);
}
/**
* Read a query string and return an object containing the state
* @param {string} queryString the query string that will be decoded
* @param {object} [options] accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
*/
exports.getStateFromQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var partialStateWithPrefix = qs.parse(queryString);
var prefixRegexp = new RegExp('^' + prefixForParameters);
var partialState = mapKeys(
partialStateWithPrefix,
function(v, k) {
var hasPrefix = prefixForParameters && prefixRegexp.test(k);
var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k;
var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey);
return decodedKey || unprefixedKey;
}
);
var partialStateWithParsedNumbers = SearchParameters._parseNumbers(partialState);
return pick(partialStateWithParsedNumbers, SearchParameters.PARAMETERS);
};
/**
* Retrieve an object of all the properties that are not understandable as helper
* parameters.
* @param {string} queryString the query string to read
* @param {object} [options] the options
* - prefixForParameters : prefix used for the helper configuration keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
exports.getUnrecognizedParametersInQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix;
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var foreignConfig = {};
var config = qs.parse(queryString);
if (prefixForParameters) {
var prefixRegexp = new RegExp('^' + prefixForParameters);
forEach(config, function(v, key) {
if (!prefixRegexp.test(key)) foreignConfig[key] = v;
});
} else {
forEach(config, function(v, key) {
if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v;
});
}
return foreignConfig;
};
/**
* Generate a query string for the state passed according to the options
* @param {SearchParameters} state state to serialize
* @param {object} [options] May contain the following parameters :
* - prefix : prefix in front of the keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* - moreAttributes : more values to be added in the query string. Those values
* won't be prefixed.
* - safe : get safe urls for use in emails, chat apps or any application auto linking urls.
* All parameters and values will be encoded in a way that it's safe to share them.
* Default to false for legacy reasons ()
* @return {string} the query string
*/
exports.getQueryStringFromState = function(state, options) {
var moreAttributes = options && options.moreAttributes;
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var safe = options && options.safe || false;
var invertedMapping = invert(mapping);
var stateForUrl = safe ? state : recursiveEncode(state);
var encodedState = mapKeys(
stateForUrl,
function(v, k) {
var shortK = shortener.encode(k);
return prefixForParameters + (mapping[shortK] || shortK);
}
);
var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters);
var sort = bind(sortQueryStringValues, null, prefixRegexp, invertedMapping);
if (!isEmpty(moreAttributes)) {
var stateQs = qs.stringify(encodedState, {encode: safe, sort: sort});
var moreQs = qs.stringify(moreAttributes, {encode: safe});
if (!stateQs) return moreQs;
return stateQs + '&' + moreQs;
}
return qs.stringify(encodedState, {encode: safe, sort: sort});
};
/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(167),
createInverter = __webpack_require__(320),
identity = __webpack_require__(26);
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
result[value] = key;
}, constant(identity));
module.exports = invert;
/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
module.exports = {
'default': 'RFC3986',
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = '2.21.2';
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* connectRange connector provides the logic to create connected
* components that will give the ability for a user to refine results using
* a numeric range.
* @name connectRange
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - Name of the attribute for faceting
* @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
*/
function getId(props) {
return props.attributeName;
}
var namespace = 'range';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), {}, function (currentRefinement) {
var min = currentRefinement.min,
max = currentRefinement.max;
if (typeof min === 'string') {
min = parseInt(min, 10);
}
if (typeof max === 'string') {
max = parseInt(max, 10);
}
return { min: min, max: max };
});
}
function _refine(props, searchState, nextRefinement, context) {
if (!isFinite(nextRefinement.min) || !isFinite(nextRefinement.max)) {
throw new Error("You can't provide non finite values to the range connector");
}
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaRange',
propTypes: {
id: _propTypes2.default.string,
attributeName: _propTypes2.default.string.isRequired,
defaultRefinement: _propTypes2.default.shape({
min: _propTypes2.default.number.isRequired,
max: _propTypes2.default.number.isRequired
}),
min: _propTypes2.default.number,
max: _propTypes2.default.number
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var min = props.min,
max = props.max;
var hasMin = typeof min !== 'undefined';
var hasMax = typeof max !== 'undefined';
var results = (0, _indexUtils.getResults)(searchResults, this.context);
if (!hasMin || !hasMax) {
if (!results) {
return {
canRefine: false
};
}
var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
if (!stats) {
return {
canRefine: false
};
}
if (!hasMin) {
min = stats.min;
}
if (!hasMax) {
max = stats.max;
}
}
var count = results ? results.getFacetValues(attributeName).map(function (v) {
return {
value: v.name,
count: v.count
};
}) : [];
var _getCurrentRefinement = getCurrentRefinement(props, searchState, this.context),
_getCurrentRefinement2 = _getCurrentRefinement.min,
valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2,
_getCurrentRefinement3 = _getCurrentRefinement.max,
valueMax = _getCurrentRefinement3 === undefined ? max : _getCurrentRefinement3;
return {
min: min,
max: max,
currentRefinement: { min: valueMin, max: valueMax },
count: count,
canRefine: count.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
params = params.addDisjunctiveFacet(attributeName);
var min = currentRefinement.min,
max = currentRefinement.max;
if (typeof min !== 'undefined') {
params = params.addNumericRefinement(attributeName, '>=', min);
}
if (typeof max !== 'undefined') {
params = params.addNumericRefinement(attributeName, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var item = void 0;
var hasMin = typeof currentRefinement.min !== 'undefined';
var hasMax = typeof currentRefinement.max !== 'undefined';
if (hasMin || hasMax) {
var itemLabel = '';
if (hasMin) {
itemLabel += currentRefinement.min + ' <= ';
}
itemLabel += props.attributeName;
if (hasMax) {
itemLabel += ' <= ' + currentRefinement.max;
}
item = {
label: itemLabel,
currentRefinement: currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _cleanUp(props, nextState, _this.context);
}
};
}
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: item ? [item] : []
};
}
});
/***/ }),
/* 210 */,
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectCurrentRefinements connector provides the logic to build a widget that will
* give the user the ability to remove all or some of the filters that were
* set.
* @name connectCurrentRefinements
* @kind connector
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {function} [clearsQuery=false] - Pass true to also clear the search query
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values.
* @providedPropType {string} query - the search query
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaCurrentRefinements',
propTypes: {
transformItems: _propTypes2.default.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) {
var items = metadata.reduce(function (res, meta) {
if (typeof meta.items !== 'undefined') {
if (!props.clearsQuery && meta.id === 'query') {
return res;
} else {
if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') {
return res;
}
return res.concat(meta.items);
}
}
return res;
}, []);
return {
items: props.transformItems ? props.transformItems(items) : items,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, items) {
// `value` corresponds to our internal clear function computed in each connector metadata.
var refinementsToClear = items instanceof Array ? items.map(function (item) {
return item.value;
}) : [items];
return refinementsToClear.reduce(function (res, clear) {
return clear(res);
}, searchState);
}
});
/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var AlgoliaSearchHelper = __webpack_require__(249);
var SearchParameters = __webpack_require__(100);
var SearchResults = __webpack_require__(190);
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(result) {
* console.log(result);
* });
* helper.toggleRefine('Movies & TV Shows')
* .toggleRefine('Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new AlgoliaSearchHelper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = __webpack_require__(208);
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults;
/**
* URL tools to generate query string and parse them from/into
* SearchParameters
* @member module:algoliasearchHelper.url
* @type {object} {@link url}
*
*/
algoliasearchHelper.url = __webpack_require__(205);
module.exports = algoliasearchHelper;
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
var toNumber = __webpack_require__(266);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
module.exports = toFinite;
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
var isNumber = __webpack_require__(184);
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
module.exports = isNaN;
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(18),
isArrayLike = __webpack_require__(11),
isIndex = __webpack_require__(32),
isObject = __webpack_require__(6);
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
module.exports = isIterateeCall;
/***/ }),
/* 216 */,
/* 217 */,
/* 218 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _highlight = __webpack_require__(330);
var _highlight2 = _interopRequireDefault(_highlight);
var _highlightTags = __webpack_require__(219);
var _highlightTags2 = _interopRequireDefault(_highlightTags);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var highlight = function highlight(_ref) {
var attributeName = _ref.attributeName,
hit = _ref.hit,
highlightProperty = _ref.highlightProperty;
return (0, _highlight2.default)({
attributeName: attributeName,
hit: hit,
preTag: _highlightTags2.default.highlightPreTag,
postTag: _highlightTags2.default.highlightPostTag,
highlightProperty: highlightProperty
});
};
/**
* connectHighlight connector provides the logic to create an highlighter
* component that will retrieve, parse and render an highlighted attribute
* from an Algolia hit.
* @name connectHighlight
* @kind connector
* @category connector
* @providedPropType {function} highlight - the function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attribute: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute to look for and `hit` which is the hit from Algolia. It returns an array of object `{value: string, isHighlighted: boolean}`.
* @example
* import React from 'react';
* import { connectHighlight } from 'react-instantsearch/connectors';
* import { InstantSearch, Hits } from 'react-instantsearch/dom';
*
* const CustomHighlight = connectHighlight(
* ({ highlight, attributeName, hit, highlightProperty }) => {
* const parsedHit = highlight({ attributeName, hit, highlightProperty: '_highlightResult' });
* const highlightedHits = parsedHit.map(part => {
* if (part.isHighlighted) return <mark>{part.value}</mark>;
* return part.value;
* });
* return <div>{highlightedHits}</div>;
* }
* );
*
* const Hit = ({hit}) =>
* <p>
* <CustomHighlight attributeName="description" hit={hit} />
* </p>;
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea">
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHighlighter',
propTypes: {},
getProvidedProps: function getProvidedProps() {
return { highlight: highlight };
}
});
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
highlightPreTag: "<ais-highlight-0000000000>",
highlightPostTag: "</ais-highlight-0000000000>"
};
/***/ }),
/* 220 */,
/* 221 */,
/* 222 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys2 = __webpack_require__(9);
var _keys3 = _interopRequireDefault(_keys2);
var _difference2 = __webpack_require__(223);
var _difference3 = _interopRequireDefault(_difference2);
var _omit2 = __webpack_require__(35);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'configure';
}
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var items = (0, _omit3.default)(props, 'children');
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
var items = (0, _omit3.default)(props, 'children');
var nonPresentKeys = this._props ? (0, _difference3.default)((0, _keys3.default)(this._props), (0, _keys3.default)(props)) : [];
this._props = props;
var nextValue = _defineProperty({}, id, _extends({}, (0, _omit3.default)(nextSearchState[id], nonPresentKeys), items));
return (0, _indexUtils.refineValue)(nextSearchState, nextValue, this.context);
},
cleanUp: function cleanUp(props, searchState) {
var id = getId();
var index = (0, _indexUtils.getIndex)(this.context);
var subState = (0, _indexUtils.hasMultipleIndex)(this.context) && searchState.indices ? searchState.indices[index] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = _defineProperty({}, id, configureState);
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context);
}
});
/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {
var baseDifference = __webpack_require__(224),
baseFlatten = __webpack_require__(165),
baseRest = __webpack_require__(25),
isArrayLikeObject = __webpack_require__(94);
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
module.exports = difference;
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(60),
arrayIncludes = __webpack_require__(92),
arrayIncludesWith = __webpack_require__(164),
arrayMap = __webpack_require__(12),
baseUnary = __webpack_require__(43),
cacheHas = __webpack_require__(61);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
module.exports = baseDifference;
/***/ }),
/* 225 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
module.exports = baseIsNaN;
/***/ }),
/* 226 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = strictIndexOf;
/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1);
/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
module.exports = isFlattenable;
/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(167),
defineProperty = __webpack_require__(168),
identity = __webpack_require__(26);
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
module.exports = baseSetToString;
/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
arrayEach = __webpack_require__(95),
assignValue = __webpack_require__(96),
baseAssign = __webpack_require__(230),
baseAssignIn = __webpack_require__(231),
cloneBuffer = __webpack_require__(170),
copyArray = __webpack_require__(69),
copySymbols = __webpack_require__(234),
copySymbolsIn = __webpack_require__(235),
getAllKeys = __webpack_require__(85),
getAllKeysIn = __webpack_require__(97),
getTag = __webpack_require__(57),
initCloneArray = __webpack_require__(236),
initCloneByTag = __webpack_require__(237),
initCloneObject = __webpack_require__(173),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(21),
isObject = __webpack_require__(6),
keys = __webpack_require__(9);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
module.exports = baseClone;
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
keys = __webpack_require__(9);
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
module.exports = baseAssign;
/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
keysIn = __webpack_require__(48);
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
module.exports = baseAssignIn;
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6),
isPrototype = __webpack_require__(38),
nativeKeysIn = __webpack_require__(233);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = baseKeysIn;
/***/ }),
/* 233 */
/***/ (function(module, exports) {
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
module.exports = nativeKeysIn;
/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
getSymbols = __webpack_require__(63);
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
module.exports = copySymbols;
/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
getSymbolsIn = __webpack_require__(171);
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
module.exports = copySymbolsIn;
/***/ }),
/* 236 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
module.exports = initCloneArray;
/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(98),
cloneDataView = __webpack_require__(238),
cloneMap = __webpack_require__(239),
cloneRegExp = __webpack_require__(241),
cloneSet = __webpack_require__(242),
cloneSymbol = __webpack_require__(244),
cloneTypedArray = __webpack_require__(172);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return cloneMap(object, isDeep, cloneFunc);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return cloneSymbol(object);
}
}
module.exports = initCloneByTag;
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(98);
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
module.exports = cloneDataView;
/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {
var addMapEntry = __webpack_require__(240),
arrayReduce = __webpack_require__(99),
mapToArray = __webpack_require__(83);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map);
return arrayReduce(array, addMapEntry, new map.constructor);
}
module.exports = cloneMap;
/***/ }),
/* 240 */
/***/ (function(module, exports) {
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
module.exports = addMapEntry;
/***/ }),
/* 241 */
/***/ (function(module, exports) {
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
module.exports = cloneRegExp;
/***/ }),
/* 242 */
/***/ (function(module, exports, __webpack_require__) {
var addSetEntry = __webpack_require__(243),
arrayReduce = __webpack_require__(99),
setToArray = __webpack_require__(84);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set);
return arrayReduce(array, addSetEntry, new set.constructor);
}
module.exports = cloneSet;
/***/ }),
/* 243 */
/***/ (function(module, exports) {
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
module.exports = addSetEntry;
/***/ }),
/* 244 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
module.exports = cloneSymbol;
/***/ }),
/* 245 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(22),
last = __webpack_require__(174),
parent = __webpack_require__(246),
toKey = __webpack_require__(24);
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
module.exports = baseUnset;
/***/ }),
/* 246 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(71),
baseSlice = __webpack_require__(175);
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
module.exports = parent;
/***/ }),
/* 247 */
/***/ (function(module, exports, __webpack_require__) {
var isPlainObject = __webpack_require__(45);
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
module.exports = customOmitClone;
/***/ }),
/* 248 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getId = undefined;
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _algoliasearchHelper = __webpack_require__(212);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var getId = exports.getId = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue(path, props, searchState, context) {
var id = props.id,
attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement(props, searchState, context);
var nextRefinement = void 0;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new _algoliasearchHelper.SearchParameters({
hierarchicalFacets: [{
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}]
});
nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0];
}
return nextRefinement;
}
function transformValue(value, limit, props, searchState, context) {
return value.slice(0, limit).map(function (v) {
return {
label: v.name,
value: getValue(v.path, props, searchState, context),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue(v.data, limit, props, searchState, context)
};
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
var sortBy = ['name:asc'];
/**
* connectHierarchicalMenu connector provides the logic to build a widget that will
* give the user the ability to explore a tree-like structure.
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
* @name connectHierarchicalMenu
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax.
* @propType {number} [limitMin=10] - The maximum number of items displayed.
* @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHierarchicalMenu',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
separator: _propTypes2.default.string,
rootPath: _propTypes2.default.string,
showParentLevel: _propTypes2.default.bool,
defaultRefinement: _propTypes2.default.string,
showMore: _propTypes2.default.bool,
limitMin: _propTypes2.default.number,
limitMax: _propTypes2.default.number,
transformItems: _propTypes2.default.func
},
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var id = getId(props);
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: false
};
}
var limit = showMore ? limitMax : limitMin;
var value = results.getFacetValues(id, { sortBy: sortBy });
var items = value.data ? transformValue(value.data, limit, props, searchState, this.context) : [];
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var id = getId(props);
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var rootAttribute = props.attributes[0];
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: !currentRefinement ? [] : [{
label: rootAttribute + ': ' + currentRefinement,
attributeName: rootAttribute,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 249 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var SearchParameters = __webpack_require__(100);
var SearchResults = __webpack_require__(190);
var DerivedHelper = __webpack_require__(315);
var requestBuilder = __webpack_require__(318);
var util = __webpack_require__(203);
var events = __webpack_require__(204);
var flatten = __webpack_require__(177);
var forEach = __webpack_require__(36);
var isEmpty = __webpack_require__(14);
var map = __webpack_require__(17);
var url = __webpack_require__(205);
var version = __webpack_require__(208);
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {SearchParameters} state the current parameters with the latest changes applied
* @property {SearchResults} lastResults the previous results received from Algolia. `null` before
* the first request
* @example
* helper.on('change', function(state, lastResults) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {SearchParameters} state the parameters used for this search
* @property {SearchResults} lastResults the results from the previous search. `null` if
* it is the first search.
* @example
* helper.on('search', function(state, lastResults) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {SearchParameters} state the parameters used for this search
* it is the first search.
* @property {string} facet the facet searched into
* @property {string} query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(state, facet, query) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {SearchParameters} state the parameters used for this search
* it is the first search.
* @example
* helper.on('searchOnce', function(state) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {SearchResults} results the results received from Algolia
* @property {SearchParameters} state the parameters used to query Algolia. Those might
* be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(results, state) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {Error} error the error returned by the Algolia.
* @example
* helper.on('error', function(error) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Event triggered when the queue of queries have been depleted (with any result or outdated queries)
* @event AlgoliaSearchHelper#event:searchQueueEmpty
* @example
* helper.on('searchQueueEmpty', function() {
* console.log('No more search pending');
* // This is received before the result event if we're not expecting new results
* });
*
* helper.search();
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line
else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version);
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
this._currentNbQueries = 0;
}
util.inherits(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function() {
this._search();
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper.prototype.getQuery = function() {
var state = this.state;
return requestBuilder._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occurred it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder._getQueries(tempState.index, tempState);
var self = this;
this._currentNbQueries++;
this.emit('searchOnce', tempState);
if (cb) {
return this.client.search(
queries,
function(err, content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
if (err) cb(err, null, tempState);
else cb(err, new SearchResults(tempState, content.results), tempState);
}
);
}
return this.client.search(queries).then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
return {
content: new SearchResults(tempState, content.results),
state: tempState,
_originalResponse: content
};
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurrence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {object}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query inside the engine
*/
/**
* Search for facet values based on an query and the name of a faceted attribute. This
* triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} maxFacetHits the maximum number values returned. Should be > 0 and <= 100
* @return {promise<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits) {
var state = this.state;
var index = this.client.initIndex(this.state.index);
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, maxFacetHits, this.state);
this._currentNbQueries++;
var self = this;
this.emit('searchForFacetValues', state, facet, query);
return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
content.facetHits = forEach(content.facetHits, function(f) {
f.isRefined = isDisjunctive ?
state.isDisjunctiveFacetRefined(facet, f.value) :
state.isFacetRefined(facet, f.value);
});
return content;
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this.state = this.state.setPage(0).setQuery(q);
this._change();
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this.state = this.state.setPage(0).clearRefinements(name);
this._change();
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this.state = this.state.setPage(0).clearTags();
this._change();
return this;
};
/**
* Adds a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value);
this._change();
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Adds a filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).addExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this.state = this.state.setPage(0).addTagRefinement(tag);
this._change();
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optional, triggering different behavior:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Removes a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet);
this._change();
return this;
};
/**
* Removes a filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).removeExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this.state = this.state.setPage(0).removeTagRefinement(tag);
this._change();
return this;
};
/**
* Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).toggleFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this.state = this.state.setPage(0).toggleTagRefinement(tag);
this._change();
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
return this.setPage(this.state.page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
return this.setPage(this.state.page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this.state = this.state.setPage(page);
this._change();
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this.state = this.state.setPage(0).setIndex(name);
this._change();
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
var newState = this.state.setPage(0).setQueryParameter(parameter, value);
if (this.state === newState) return this;
this.state = newState;
this._change();
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this.state = new SearchParameters(newState);
this._change();
return this;
};
/**
* Get the current search state stored in the helper. This object is immutable.
* @param {string[]} [filters] optional filters to retrieve only a subset of the state
* @return {SearchParameters|object} if filters is specified a plain object is
* returned containing only the requested fields, otherwise return the unfiltered
* state
* @example
* // Get the complete state as stored in the helper
* helper.getState();
* @example
* // Get a part of the state with all the refinements on attributes and the query
* helper.getState(['query', 'attribute:category']);
*/
AlgoliaSearchHelper.prototype.getState = function(filters) {
if (filters === undefined) return this.state;
return this.state.filter(filters);
};
/**
* DEPRECATED Get part of the state as a query string. By default, the output keys will not
* be prefixed and will only take the applied refinements and the query.
* @deprecated
* @param {object} [options] May contain the following parameters :
*
* **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for
* the index, all the refinements with `attribute:*` or for some specific attributes with
* `attribute:theAttribute`
*
* **prefix** : prefix in front of the keys
*
* **moreAttributes** : more values to be added in the query string. Those values
* won't be prefixed.
* @return {string} the query string
*/
AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) {
var filters = options && options.filters || ['query', 'attribute:*'];
var partialState = this.getState(filters);
return url.getQueryStringFromState(partialState, options);
};
/**
* DEPRECATED Read a query string and return an object containing the state. Use
* url module.
* @deprecated
* @static
* @param {string} queryString the query string that will be decoded
* @param {object} options accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
* @see {@link url#getStateFromQueryString}
*/
AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString;
/**
* DEPRECATED Retrieve an object of all the properties that are not understandable as helper
* parameters. Use url module.
* @deprecated
* @static
* @param {string} queryString the query string to read
* @param {object} options the options
* - prefixForParameters : prefix used for the helper configuration keys
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString;
/**
* DEPRECATED Overrides part of the state with the properties stored in the provided query
* string.
* @deprecated
* @param {string} queryString the query string containing the informations to url the state
* @param {object} options optional parameters :
* - prefix : prefix used for the algolia parameters
* - triggerChange : if set to true the state update will trigger a change event
*/
AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) {
var triggerChange = options && options.triggerChange || false;
var configuration = url.getStateFromQueryString(queryString, options);
var updatedState = this.state.setQueryParameters(configuration);
if (triggerChange) this.setState(updatedState);
else this.overrideStateWithoutTriggeringChangeEvent(updatedState);
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters(newState);
return this;
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isRefined = function(facet, value) {
if (this.state.isConjunctiveFacet(facet)) {
return this.state.isFacetRefined(facet, value);
} else if (this.state.isDisjunctiveFacet(facet)) {
return this.state.isDisjunctiveFacetRefined(facet, value);
}
throw new Error(facet +
' is not properly defined in this helper configuration' +
'(use the facets or disjunctiveFacets keys to configure it)');
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (!isEmpty(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific faceted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean}
*/
AlgoliaSearchHelper.prototype.hasTag = function(tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper.prototype.isTagRefined = function() {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string}
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper.prototype.getIndex = function() {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper.prototype.getTags = function() {
return this.state.tagRefinements;
};
/**
* Get a parameter of the search by its name. It is possible that a parameter is directly
* defined in the index dashboard, but it will be undefined using this method.
*
* The complete list of parameters is
* available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters have their own API)
* @param {string} parameterName the parameter name
* @return {any} the parameter value
* @example
* var hitsPerPage = helper.getQueryParameter('hitsPerPage');
*/
AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) {
return this.state.getQueryParameter(parameterName);
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for faceting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper.prototype.getRefinements = function(facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
forEach(conjRefinements, function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
forEach(excludeRefinements, function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
forEach(disjRefinements, function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
forEach(numericRefinements, function(value, operator) {
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
// /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function() {
var state = this.state;
var mainQueries = requestBuilder._getQueries(state.index, state);
var states = [{
state: state,
queriesCount: mainQueries.length,
helper: this
}];
this.emit('search', state, this.lastResults);
var derivedQueries = map(this.derivedHelpers, function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var queries = requestBuilder._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: queries.length,
helper: derivedHelper
});
derivedHelper.emit('search', derivedState, derivedHelper.lastResults);
return queries;
});
var queries = mainQueries.concat(flatten(derivedQueries));
var queryId = this._queryId++;
this._currentNbQueries++;
this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId));
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable object that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>}
* state state used for to generate the request
* @param {number} queryId id of the current request
* @param {Error} err error if any, null otherwise
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) {
// FIXME remove the number of outdated queries discarded instead of just one
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= (queryId - this._lastQueryIdReceived);
this._lastQueryIdReceived = queryId;
if (err) {
this.emit('error', err);
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
} else {
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results;
forEach(states, function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults(state, specificResults);
helper.emit('result', formattedResponse, state);
});
}
};
AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
facetFilters.length !== 0 ||
numericFilters.length !== 0 ||
tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] &&
this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function() {
this.emit('change', this.state, this.lastResults);
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.setClient = function(newClient) {
if (this.client === newClient) return this;
if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version);
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch}
*/
AlgoliaSearchHelper.prototype.getClient = function() {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `result` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @return {DerivedHelper}
*/
AlgoliaSearchHelper.prototype.derive = function(fn) {
var derivedHelper = new DerivedHelper(this, fn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @return {undefined}
* @throws Error
*/
AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error('Derived helper already detached');
this.derivedHelpers.splice(pos, 1);
};
/**
* This method returns true if there is currently at least one on-going search.
* @return {boolean} true if there is a search pending
*/
AlgoliaSearchHelper.prototype.hasPendingRequests = function() {
return this._currentNbQueries > 0;
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the faceting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
/*
* This function tests if the _ua parameter of the client
* already contains the JS Helper UA
*/
function doesClientAgentContainsHelper(client) {
// this relies on JS Client internal variable, this might break if implementation changes
var currentAgent = client._ua;
return !currentAgent ? false :
currentAgent.indexOf('JS Helper') !== -1;
}
module.exports = AlgoliaSearchHelper;
/***/ }),
/* 250 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseIntersection = __webpack_require__(251),
baseRest = __webpack_require__(25),
castArrayLikeObject = __webpack_require__(252);
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
module.exports = intersection;
/***/ }),
/* 251 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(60),
arrayIncludes = __webpack_require__(92),
arrayIncludesWith = __webpack_require__(164),
arrayMap = __webpack_require__(12),
baseUnary = __webpack_require__(43),
cacheHas = __webpack_require__(61);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
module.exports = baseIntersection;
/***/ }),
/* 252 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLikeObject = __webpack_require__(94);
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
module.exports = castArrayLikeObject;
/***/ }),
/* 253 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(49),
castFunction = __webpack_require__(179);
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, castFunction(iteratee));
}
module.exports = forOwn;
/***/ }),
/* 254 */
/***/ (function(module, exports) {
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
/***/ }),
/* 255 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(11);
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
module.exports = createBaseEach;
/***/ }),
/* 256 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(73);
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
module.exports = baseFilter;
/***/ }),
/* 257 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsMatch = __webpack_require__(258),
getMatchData = __webpack_require__(259),
matchesStrictComparable = __webpack_require__(181);
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
module.exports = baseMatches;
/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
baseIsEqual = __webpack_require__(59);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
/***/ }),
/* 259 */
/***/ (function(module, exports, __webpack_require__) {
var isStrictComparable = __webpack_require__(180),
keys = __webpack_require__(9);
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
module.exports = getMatchData;
/***/ }),
/* 260 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(59),
get = __webpack_require__(72),
hasIn = __webpack_require__(182),
isKey = __webpack_require__(64),
isStrictComparable = __webpack_require__(180),
matchesStrictComparable = __webpack_require__(181),
toKey = __webpack_require__(24);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
module.exports = baseMatchesProperty;
/***/ }),
/* 261 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
module.exports = baseHasIn;
/***/ }),
/* 262 */
/***/ (function(module, exports, __webpack_require__) {
var baseProperty = __webpack_require__(263),
basePropertyDeep = __webpack_require__(264),
isKey = __webpack_require__(64),
toKey = __webpack_require__(24);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
module.exports = property;
/***/ }),
/* 263 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
/***/ }),
/* 264 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(71);
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
module.exports = basePropertyDeep;
/***/ }),
/* 265 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
module.exports = baseReduce;
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6),
isSymbol = __webpack_require__(23);
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = toNumber;
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(13),
isArrayLike = __webpack_require__(11),
keys = __webpack_require__(9);
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
module.exports = createFind;
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
var baseSlice = __webpack_require__(175);
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
module.exports = castSlice;
/***/ }),
/* 269 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46);
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsEndIndex;
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46);
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsStartIndex;
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
var asciiToArray = __webpack_require__(272),
hasUnicode = __webpack_require__(273),
unicodeToArray = __webpack_require__(274);
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
module.exports = stringToArray;
/***/ }),
/* 272 */
/***/ (function(module, exports) {
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
module.exports = asciiToArray;
/***/ }),
/* 273 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
module.exports = hasUnicode;
/***/ }),
/* 274 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
module.exports = unicodeToArray;
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
createAssigner = __webpack_require__(188),
keysIn = __webpack_require__(48);
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
module.exports = assignInWith;
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(18);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
module.exports = customDefaultsAssignIn;
/***/ }),
/* 277 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
assignMergeValue = __webpack_require__(189),
baseFor = __webpack_require__(178),
baseMergeDeep = __webpack_require__(278),
isObject = __webpack_require__(6),
keysIn = __webpack_require__(48);
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
if (isObject(srcValue)) {
stack || (stack = new Stack);
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(object[key], srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
module.exports = baseMerge;
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
var assignMergeValue = __webpack_require__(189),
cloneBuffer = __webpack_require__(170),
cloneTypedArray = __webpack_require__(172),
copyArray = __webpack_require__(69),
initCloneObject = __webpack_require__(173),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1),
isArrayLikeObject = __webpack_require__(94),
isBuffer = __webpack_require__(21),
isFunction = __webpack_require__(19),
isObject = __webpack_require__(6),
isPlainObject = __webpack_require__(45),
isTypedArray = __webpack_require__(34),
toPlainObject = __webpack_require__(279);
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = object[key],
srcValue = source[key],
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
module.exports = baseMergeDeep;
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
keysIn = __webpack_require__(48);
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
module.exports = toPlainObject;
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var map = __webpack_require__(17);
var isArray = __webpack_require__(1);
var isNumber = __webpack_require__(184);
var isString = __webpack_require__(52);
function valToNumber(v) {
if (isNumber(v)) {
return v;
} else if (isString(v)) {
return parseFloat(v);
} else if (isArray(v)) {
return map(v, valToNumber);
}
throw new Error('The value should be a number, a parseable string or an array of those.');
}
module.exports = valToNumber;
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(36);
var filter = __webpack_require__(101);
var map = __webpack_require__(17);
var isEmpty = __webpack_require__(14);
var indexOf = __webpack_require__(74);
function filterState(state, filters) {
var partialState = {};
var attributeFilters = filter(filters, function(f) { return f.indexOf('attribute:') !== -1; });
var attributes = map(attributeFilters, function(aF) { return aF.split(':')[1]; });
if (indexOf(attributes, '*') === -1) {
forEach(attributes, function(attr) {
if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) {
if (!partialState.facetsRefinements) partialState.facetsRefinements = {};
partialState.facetsRefinements[attr] = state.facetsRefinements[attr];
}
if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) {
if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {};
partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr];
}
if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) {
if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {};
partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr];
}
var numericRefinements = state.getNumericRefinements(attr);
if (!isEmpty(numericRefinements)) {
if (!partialState.numericRefinements) partialState.numericRefinements = {};
partialState.numericRefinements[attr] = state.numericRefinements[attr];
}
});
} else {
if (!isEmpty(state.numericRefinements)) {
partialState.numericRefinements = state.numericRefinements;
}
if (!isEmpty(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements;
if (!isEmpty(state.disjunctiveFacetsRefinements)) {
partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements;
}
if (!isEmpty(state.hierarchicalFacetsRefinements)) {
partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements;
}
}
var searchParameters = filter(
filters,
function(f) {
return f.indexOf('attribute:') === -1;
}
);
forEach(
searchParameters,
function(parameterKey) {
partialState[parameterKey] = state[parameterKey];
}
);
return partialState;
}
module.exports = filterState;
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var isUndefined = __webpack_require__(185);
var isString = __webpack_require__(52);
var isFunction = __webpack_require__(19);
var isEmpty = __webpack_require__(14);
var defaults = __webpack_require__(102);
var reduce = __webpack_require__(50);
var filter = __webpack_require__(101);
var omit = __webpack_require__(35);
var lib = {
/**
* Adds a refinement to a RefinementList
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated refinement list
*/
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) {
return refinementList;
}
var valueAsString = '' + value;
var facetRefinement = !refinementList[attribute] ?
[valueAsString] :
refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaults({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (isUndefined(value)) {
return lib.clearRefinement(refinementList, attribute);
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* kinds of behavior can happen:
* - if no attribute is provided: clears the whole list
* - if an attribute is provided as a string: clears the list for the specific attribute
* - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optional parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(refinementList, attribute);
} else if (isFunction(attribute)) {
return reduce(refinementList, function(memo, values, key) {
var facetList = filter(values, function(value) {
return !attribute(value, key, refinementType);
});
if (!isEmpty(facetList)) memo[key] = facetList;
return memo;
}, {});
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var indexOf = __webpack_require__(74);
var containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (isUndefined(refinementValue) || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return indexOf(refinementList[attribute], refinementValueAsString) !== -1;
}
};
module.exports = lib;
/***/ }),
/* 283 */
/***/ (function(module, exports) {
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = compact;
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(13),
baseSum = __webpack_require__(285);
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, baseIteratee(iteratee, 2))
: 0;
}
module.exports = sumBy;
/***/ }),
/* 285 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
module.exports = baseSum;
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46),
isArrayLike = __webpack_require__(11),
isString = __webpack_require__(52),
toInteger = __webpack_require__(51),
values = __webpack_require__(287);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
module.exports = includes;
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
var baseValues = __webpack_require__(288),
keys = __webpack_require__(9);
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
module.exports = values;
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12);
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
module.exports = baseValues;
/***/ }),
/* 289 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseIteratee = __webpack_require__(13),
baseMap = __webpack_require__(183),
baseSortBy = __webpack_require__(290),
baseUnary = __webpack_require__(43),
compareMultiple = __webpack_require__(291),
identity = __webpack_require__(26);
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
var index = -1;
iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
module.exports = baseOrderBy;
/***/ }),
/* 290 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
module.exports = baseSortBy;
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
var compareAscending = __webpack_require__(292);
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
module.exports = compareMultiple;
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(23);
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
module.exports = compareAscending;
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(25),
createWrap = __webpack_require__(105),
getHolder = __webpack_require__(54),
replaceHolders = __webpack_require__(37);
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partial.placeholder = {};
module.exports = partial;
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
var createCtor = __webpack_require__(75),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
module.exports = createBind;
/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(68),
createCtor = __webpack_require__(75),
createHybrid = __webpack_require__(193),
createRecurry = __webpack_require__(196),
getHolder = __webpack_require__(54),
replaceHolders = __webpack_require__(37),
root = __webpack_require__(3);
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
module.exports = createCurry;
/***/ }),
/* 296 */
/***/ (function(module, exports) {
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
module.exports = countHolders;
/***/ }),
/* 297 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(106),
getData = __webpack_require__(197),
getFuncName = __webpack_require__(299),
lodash = __webpack_require__(301);
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
module.exports = isLaziable;
/***/ }),
/* 298 */
/***/ (function(module, exports) {
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
module.exports = noop;
/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {
var realNames = __webpack_require__(300);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
module.exports = getFuncName;
/***/ }),
/* 300 */
/***/ (function(module, exports) {
/** Used to lookup unminified function names. */
var realNames = {};
module.exports = realNames;
/***/ }),
/* 301 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(106),
LodashWrapper = __webpack_require__(198),
baseLodash = __webpack_require__(107),
isArray = __webpack_require__(1),
isObjectLike = __webpack_require__(7),
wrapperClone = __webpack_require__(302);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
module.exports = lodash;
/***/ }),
/* 302 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(106),
LodashWrapper = __webpack_require__(198),
copyArray = __webpack_require__(69);
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
module.exports = wrapperClone;
/***/ }),
/* 303 */
/***/ (function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
module.exports = getWrapDetails;
/***/ }),
/* 304 */
/***/ (function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
module.exports = insertWrapDetails;
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(95),
arrayIncludes = __webpack_require__(92);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
module.exports = updateWrapDetails;
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
var copyArray = __webpack_require__(69),
isIndex = __webpack_require__(32);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
module.exports = reorder;
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(68),
createCtor = __webpack_require__(75),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
module.exports = createPartial;
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(194),
composeArgsRight = __webpack_require__(195),
replaceHolders = __webpack_require__(37);
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
module.exports = mergeData;
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(25),
createWrap = __webpack_require__(105),
getHolder = __webpack_require__(54),
replaceHolders = __webpack_require__(37);
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partialRight.placeholder = {};
module.exports = partialRight;
/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {
var baseClamp = __webpack_require__(311),
baseToString = __webpack_require__(66),
toInteger = __webpack_require__(51),
toString = __webpack_require__(65);
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
module.exports = startsWith;
/***/ }),
/* 311 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
module.exports = baseClamp;
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = generateTrees;
var last = __webpack_require__(174);
var map = __webpack_require__(17);
var reduce = __webpack_require__(50);
var orderBy = __webpack_require__(104);
var trim = __webpack_require__(187);
var find = __webpack_require__(53);
var pickBy = __webpack_require__(313);
var prepareHierarchicalFacetSortBy = __webpack_require__(201);
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
}
return reduce(results, generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
data: null
});
};
}
function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
parent = parent && find(parent.data, {isRefined: true});
level++;
}
}
// we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath,
currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
parent.data = orderBy(
map(
pickBy(hierarchicalFacetResult.data, onlyMatchingValuesFn),
formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement)
),
sortBy[0], sortBy[1]
);
}
return hierarchicalTree;
};
}
function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel) {
return function(facetCount, facetValue) {
// we want the facetValue is a child of hierarchicalRootPath
if (hierarchicalRootPath &&
(facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) {
return false;
}
// we always want root levels (only when there is no prefix path)
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 ||
// if there is a rootPath, being root level mean 1 level under rootPath
hierarchicalRootPath &&
facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 ||
// if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
facetValue.indexOf(hierarchicalSeparator) === -1 &&
currentRefinement.indexOf(hierarchicalSeparator) === -1 ||
// currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 ||
// facetValue is a child of the current parent, add it
facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 &&
(hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
};
}
function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) {
return function format(facetCount, facetValue) {
return {
name: trim(last(facetValue.split(hierarchicalSeparator))),
path: facetValue,
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
data: null
};
};
}
/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseIteratee = __webpack_require__(13),
basePickBy = __webpack_require__(202),
getAllKeysIn = __webpack_require__(97);
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = baseIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
module.exports = pickBy;
/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(96),
castPath = __webpack_require__(22),
isIndex = __webpack_require__(32),
isObject = __webpack_require__(6),
toKey = __webpack_require__(24);
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
module.exports = baseSet;
/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(203);
var events = __webpack_require__(204);
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
*/
function DerivedHelper(mainHelper, fn) {
this.main = mainHelper;
this.fn = fn;
this.lastResults = null;
}
util.inherits(DerivedHelper, events.EventEmitter);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper.prototype.detach = function() {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper.prototype.getModifiedState = function(parameters) {
return this.fn(parameters);
};
module.exports = DerivedHelper;
/***/ }),
/* 316 */
/***/ (function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/* 317 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 318 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(36);
var map = __webpack_require__(17);
var reduce = __webpack_require__(50);
var merge = __webpack_require__(103);
var isArray = __webpack_require__(1);
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = [];
// One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
});
// One for each disjunctive facets
forEach(state.getRefinedDisjunctiveFacets(), function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function(state) {
var facets = state.facets
.concat(state.disjunctiveFacets)
.concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(
state,
hierarchicalFacet,
hierarchicalRootLevel
);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
forEach(state.numericRefinements, function(operators, attribute) {
forEach(operators, function(values, operator) {
if (facetName !== attribute) {
forEach(values, function(value) {
if (isArray(value)) {
var vs = map(value, function(v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
forEach(state.facetsRefinements, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
forEach(state.facetsExcludes, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
forEach(state.disjunctiveFacetsRefinements, function(facetValues, facetName) {
if (facetName === facet || !facetValues || facetValues.length === 0) return;
var orFilters = [];
forEach(facetValues, function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
forEach(state.hierarchicalFacetsRefinements, function(facetValues, facetName) {
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
// we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) ||
(rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return reduce(
state.hierarchicalFacets,
// ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
// if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || '';
// if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) {
var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ?
state.clearRefinements(facetName) :
state;
var searchForFacetSearchParameters = {
facetQuery: query,
facetName: facetName
};
if (typeof maxFacetHits === 'number') {
searchForFacetSearchParameters.maxFacetHits = maxFacetHits;
}
var queries = merge(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters);
return queries;
}
};
module.exports = requestBuilder;
/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var invert = __webpack_require__(206);
var keys = __webpack_require__(9);
var keys2Short = {
advancedSyntax: 'aS',
allowTyposOnNumericTokens: 'aTONT',
analyticsTags: 'aT',
analytics: 'a',
aroundLatLngViaIP: 'aLLVIP',
aroundLatLng: 'aLL',
aroundPrecision: 'aP',
aroundRadius: 'aR',
attributesToHighlight: 'aTH',
attributesToRetrieve: 'aTR',
attributesToSnippet: 'aTS',
disjunctiveFacetsRefinements: 'dFR',
disjunctiveFacets: 'dF',
distinct: 'd',
facetsExcludes: 'fE',
facetsRefinements: 'fR',
facets: 'f',
getRankingInfo: 'gRI',
hierarchicalFacetsRefinements: 'hFR',
hierarchicalFacets: 'hF',
highlightPostTag: 'hPoT',
highlightPreTag: 'hPrT',
hitsPerPage: 'hPP',
ignorePlurals: 'iP',
index: 'idx',
insideBoundingBox: 'iBB',
insidePolygon: 'iPg',
length: 'l',
maxValuesPerFacet: 'mVPF',
minimumAroundRadius: 'mAR',
minProximity: 'mP',
minWordSizefor1Typo: 'mWS1T',
minWordSizefor2Typos: 'mWS2T',
numericFilters: 'nF',
numericRefinements: 'nR',
offset: 'o',
optionalWords: 'oW',
page: 'p',
queryType: 'qT',
query: 'q',
removeWordsIfNoResults: 'rWINR',
replaceSynonymsInHighlight: 'rSIH',
restrictSearchableAttributes: 'rSA',
synonyms: 's',
tagFilters: 'tF',
tagRefinements: 'tR',
typoTolerance: 'tT',
optionalTagFilters: 'oTF',
optionalFacetFilters: 'oFF',
snippetEllipsisText: 'sET',
disableExactOnAttributes: 'dEOA',
enableExactOnSingleWordQuery: 'eEOSWQ'
};
var short2Keys = invert(keys2Short);
module.exports = {
/**
* All the keys of the state, encoded.
* @const
*/
ENCODED_PARAMETERS: keys(short2Keys),
/**
* Decode a shorten attribute
* @param {string} shortKey the shorten attribute
* @return {string} the decoded attribute, undefined otherwise
*/
decode: function(shortKey) {
return short2Keys[shortKey];
},
/**
* Encode an attribute into a short version
* @param {string} key the attribute
* @return {string} the shorten attribute
*/
encode: function(key) {
return keys2Short[key];
}
};
/***/ }),
/* 320 */
/***/ (function(module, exports, __webpack_require__) {
var baseInverter = __webpack_require__(321);
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
module.exports = createInverter;
/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(49);
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
module.exports = baseInverter;
/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var stringify = __webpack_require__(323);
var parse = __webpack_require__(324);
var formats = __webpack_require__(207);
module.exports = {
formats: formats,
parse: parse,
stringify: stringify
};
/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(108);
var formats = __webpack_require__(207);
var arrayPrefixGenerators = {
brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
return prefix + '[]';
},
indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
return prefix;
}
};
var toISO = Date.prototype.toISOString;
var defaults = {
delimiter: '&',
encode: true,
encoder: utils.encode,
encodeValuesOnly: false,
serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var stringify = function stringify( // eslint-disable-line func-name-matching
object,
prefix,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(
obj[key],
generateArrayPrefix(prefix, key),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
} else {
values = values.concat(stringify(
obj[key],
prefix + (allowDots ? '.' + key : '[' + key + ']'),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
}
}
return values;
};
module.exports = function (object, opts) {
var obj = object;
var options = opts ? utils.assign({}, opts) : {};
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder;
var sort = typeof options.sort === 'function' ? options.sort : null;
var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
if (typeof options.format === 'undefined') {
options.format = formats.default;
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.');
}
var formatter = formats.formatters[options.format];
var objKeys;
var filter;
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(
obj[key],
key,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encode ? encoder : null,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
}
var joined = keys.join(delimiter);
var prefix = options.addQueryPrefix === true ? '?' : '';
return joined.length > 0 ? prefix + joined : '';
};
/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(108);
var has = Object.prototype.hasOwnProperty;
var defaults = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
decoder: utils.decode,
delimiter: '&',
depth: 5,
parameterLimit: 1000,
plainObjects: false,
strictNullHandling: false
};
var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var bracketEqualsPos = part.indexOf(']=');
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part, defaults.decoder);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults.decoder);
val = options.decoder(part.slice(pos + 1), defaults.decoder);
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function parseObjectRecursive(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index)
&& root !== cleanRoot
&& String(index) === cleanRoot
&& index >= 0
&& (options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = parseObject(chain, val, options);
}
}
return obj;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
// The regex chunks
var brackets = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
// Get the parent
var segment = brackets.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
// Stash the parent if it exists
var keys = [];
if (parent) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(parent);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
module.exports = function (str, opts) {
var options = opts ? utils.assign({}, opts) : {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.ignoreQueryPrefix = options.ignoreQueryPrefix === true;
options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
/***/ }),
/* 325 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(25),
createWrap = __webpack_require__(105),
getHolder = __webpack_require__(54),
replaceHolders = __webpack_require__(37);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
// Assign default placeholders.
bind.placeholder = {};
module.exports = bind;
/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {
var basePickBy = __webpack_require__(202),
hasIn = __webpack_require__(182);
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
module.exports = basePick;
/***/ }),
/* 327 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(47),
baseForOwn = __webpack_require__(49),
baseIteratee = __webpack_require__(13);
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
module.exports = mapKeys;
/***/ }),
/* 328 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(47),
baseForOwn = __webpack_require__(49),
baseIteratee = __webpack_require__(13);
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
module.exports = mapValues;
/***/ }),
/* 329 */,
/* 330 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get2 = __webpack_require__(72);
var _get3 = _interopRequireDefault(_get2);
exports.default = parseAlgoliaHit;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it,
* and provided an array of objects with the string value and a boolean if this
* value is highlighted.
*
* In order to use this feature, highlight must be activated in the configuration of
* the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and
* highligtPostTag in Algolia configuration.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightProperty - the property that contains the highlight structure in the results
* @param {string} attributeName - the highlighted attribute to look for
* @param {object} hit - the actual hit returned by Algolia.
* @return {object[]} - An array of {value: string, isDefined: boolean}.
*/
function parseAlgoliaHit(_ref) {
var _ref$preTag = _ref.preTag,
preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag,
_ref$postTag = _ref.postTag,
postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag,
highlightProperty = _ref.highlightProperty,
attributeName = _ref.attributeName,
hit = _ref.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = (0, _get3.default)(hit[highlightProperty], attributeName);
var highlightedValue = !highlightObject ? '' : highlightObject.value;
return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightedValue });
}
/**
* Parses an highlighted attribute into an array of objects with the string value, and
* a boolean that indicated if this part is highlighted.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature
* @return {object[]} - An array of {value: string, isDefined: boolean}.
*/
function parseHighlightedAttribute(_ref2) {
var preTag = _ref2.preTag,
postTag = _ref2.postTag,
highlightedValue = _ref2.highlightedValue;
var splitByPreTag = highlightedValue.split(preTag);
var firstValue = splitByPreTag.shift();
var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }];
if (postTag === preTag) {
var isHighlighted = true;
splitByPreTag.forEach(function (split) {
elements.push({ value: split, isHighlighted: isHighlighted });
isHighlighted = !isHighlighted;
});
} else {
splitByPreTag.forEach(function (split) {
var splitByPostTag = split.split(postTag);
elements.push({
value: splitByPostTag[0],
isHighlighted: true
});
if (splitByPostTag[1] !== '') {
elements.push({
value: splitByPostTag[1],
isHighlighted: false
});
}
});
}
return elements;
}
/***/ }),
/* 331 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectHits connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
* @name connectHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var hits = results ? results.hits : [];
return { hits: hits };
},
/* Hits needs to be considered as a widget to trigger a search if no others widgets are used.
* To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState
* See createConnector.js
* */
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
/***/ }),
/* 332 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'hitsPerPage';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* connectHitsPerPage connector provides the logic to create connected
* components that will allow a user to choose to display more or less results from Algolia.
* @name connectHitsPerPage
* @kind connector
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {{value: number, label: string}[]} items - List of hits per page options.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHitsPerPage',
propTypes: {
defaultRefinement: _propTypes2.default.number.isRequired,
items: _propTypes2.default.arrayOf(_propTypes2.default.shape({
label: _propTypes2.default.string,
value: _propTypes2.default.number.isRequired
})).isRequired,
transformItems: _propTypes2.default.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false });
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement(props, searchState, this.context));
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 333 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function getId() {
return 'page';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
var page = 1;
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
currentRefinement = parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* InfiniteHits connector provides the logic to create connected
* components that will render an continuous list of results retrieved from
* Algolia. This connector provides a function to load more results.
* @name connectInfiniteHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {boolean} hasMore - indicates if there are more pages to load
* @providedPropType {function} refine - call to load more results
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = (0, _indexUtils.getResults)(searchResults, this.context);
if (!results) {
this._allResults = [];
return {
hits: this._allResults,
hasMore: false
};
}
var hits = results.hits,
page = results.page,
nbPages = results.nbPages;
// If it is the same page we do not touch the page result list
if (page === 0) {
this._allResults = hits;
} else if (page > this.previousPage) {
this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hits));
} else if (page < this.previousPage) {
this._allResults = hits;
}
var lastPageIndex = nbPages - 1;
var hasMore = page < lastPageIndex;
this.previousPage = page;
return {
hits: this._allResults,
hasMore: hasMore
};
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQueryParameters({
page: getCurrentRefinement(props, searchState, this.context) - 1
});
},
refine: function refine(props, searchState) {
var id = getId();
var nextPage = getCurrentRefinement(props, searchState, this.context) + 1;
var nextValue = _defineProperty({}, id, nextPage);
var resetPage = false;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
}
});
/***/ }),
/* 334 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _orderBy2 = __webpack_require__(104);
var _orderBy3 = _interopRequireDefault(_orderBy2);
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var namespace = 'menu';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement(props, searchState, context);
return name === currentRefinement ? '' : name;
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
var sortBy = ['count:desc', 'name:asc'];
/**
* connectMenu connector provides the logic to build a widget that will
* give the user the ability to choose a single value for a specific facet.
* @name connectMenu
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of diplayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaMenu',
propTypes: {
attributeName: _propTypes2.default.string.isRequired,
showMore: _propTypes2.default.bool,
limitMin: _propTypes2.default.number,
limitMax: _propTypes2.default.number,
defaultRefinement: _propTypes2.default.string,
transformItems: _propTypes2.default.func,
withSearchBox: _propTypes2.default.bool,
searchForFacetValues: _propTypes2.default.bool // @deprecated
},
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var _this = this;
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.');
}
// Search For Facet Values is not available with derived helper (used for multi index search)
if (props.withSearchBox && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: canRefine
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) {
return {
label: v.name,
value: getValue(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var sortedItems = withSearchBox && !isFromSearch ? (0, _orderBy3.default)(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items;
var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
searchParameters = searchParameters.addDisjunctiveFacet(attributeName);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this2 = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: currentRefinement === null ? [] : [{
label: props.attributeName + ': ' + currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _refine(props, nextState, '', _this2.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 335 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEmpty2 = __webpack_require__(14);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _find3 = __webpack_require__(53);
var _find4 = _interopRequireDefault(_find3);
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
return (item.start ? item.start : '') + ':' + (item.end ? item.end : '');
}
function parseItem(value) {
if (value.length === 0) {
return { start: null, end: null };
}
var _value$split = value.split(':'),
_value$split2 = _slicedToArray(_value$split, 2),
startStr = _value$split2[0],
endStr = _value$split2[1];
return {
start: startStr.length > 0 ? parseInt(startStr, 10) : null,
end: endStr.length > 0 ? parseInt(endStr, 10) : null
};
}
var namespace = 'multiRange';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), '', function (currentRefinement) {
if (currentRefinement === '') {
return '';
}
return currentRefinement;
});
}
function isRefinementsRangeIncludesInsideItemRange(stats, start, end) {
return stats.min > start && stats.min < end || stats.max > start && stats.max < end;
}
function isItemRangeIncludedInsideRefinementsRange(stats, start, end) {
return start > stats.min && start < stats.max || end > stats.min && end < stats.max;
}
function itemHasRefinement(attributeName, results, value) {
var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
var range = value.split(':');
var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]);
var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]);
return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end)));
}
function _refine(props, searchState, nextRefinement, context) {
var nextValue = _defineProperty({}, getId(props, searchState), nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectMultiRange connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectMultiRange
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaMultiRange',
propTypes: {
id: _propTypes2.default.string,
attributeName: _propTypes2.default.string.isRequired,
items: _propTypes2.default.arrayOf(_propTypes2.default.shape({
label: _propTypes2.default.node,
start: _propTypes2.default.number,
end: _propTypes2.default.number
})).isRequired,
transformItems: _propTypes2.default.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: results ? itemHasRefinement(getId(props), results, value) : false
};
});
var stats = results && results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
var refinedItem = (0, _find4.default)(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: (0, _isEmpty3.default)(refinedItem),
noRefinement: !stats,
label: 'All'
});
}
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement,
canRefine: items.length > 0 && items.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName;
var _parseItem = parseItem(getCurrentRefinement(props, searchState, this.context)),
start = _parseItem.start,
end = _parseItem.end;
searchParameters = searchParameters.addDisjunctiveFacet(attributeName);
if (start) {
searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start);
}
if (end) {
searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var value = getCurrentRefinement(props, searchState, this.context);
var items = [];
var index = (0, _indexUtils.getIndex)(this.context);
if (value !== '') {
var _find2 = (0, _find4.default)(props.items, function (item) {
return stringifyItem(item) === value;
}),
label = _find2.label;
items.push({
label: props.attributeName + ': ' + label,
attributeName: props.attributeName,
currentRefinement: label,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
/***/ }),
/* 336 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'page';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
var page = 1;
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
function _refine(props, searchState, nextPage, context) {
var id = getId();
var nextValue = _defineProperty({}, id, nextPage);
var resetPage = false;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage);
}
/**
* connectPagination connector provides the logic to build a widget that will
* let the user displays hits corresponding to a certain page.
* @name connectPagination
* @kind connector
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [pagesPadding=3] - How many page links to display around the current page.
* @propType {number} [maxPages=Infinity] - Maximum number of pages to display.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {number} nbPages - the total of existing pages
* @providedPropType {number} currentRefinement - the page refinement currently applied
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = (0, _indexUtils.getResults)(searchResults, this.context);
if (!results) {
return null;
}
var nbPages = results.nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
return _refine(props, searchState, nextPage, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement(props, searchState, this.context) - 1);
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 337 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectPoweredBy connector provides the logic to build a widget that
* will display a link to algolia.
* @name connectPoweredBy
* @kind connector
* @providedPropType {string} url - the url to redirect to algolia
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaPoweredBy',
propTypes: {},
getProvidedProps: function getProvidedProps(props) {
var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + (props.canRender ? location.hostname : '') + '&') + 'utm_campaign=poweredby';
return { url: url };
}
});
/***/ }),
/* 338 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var namespace = 'refinementList';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), [], function (currentRefinement) {
if (typeof currentRefinement === 'string') {
// All items were unselected
if (currentRefinement === '') {
return [];
}
// Only one item was in the searchState but we know it should be an array
return [currentRefinement];
}
return currentRefinement;
});
}
function getValue(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement(props, searchState, context);
var isAnewValue = currentRefinement.indexOf(name) === -1;
var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates
: currentRefinement.filter(function (selectedValue) {
return selectedValue !== name;
}); // cannot use .splice(), it mutates
return nextRefinement;
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
// Setting the value to an empty string ensures that it is persisted in
// the URL as an empty value.
// This is necessary in the case where `defaultRefinement` contains one
// item and we try to deselect it. `nextSelected` would be an empty array,
// which would not be persisted to the URL.
// {foo: ['bar']} => "foo[0]=bar"
// {foo: []} => ""
var nextValue = _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectRefinementList connector provides the logic to build a widget that will
* give the user the ability to choose multiple values for a specific facet.
* @name connectRefinementList
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of displayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var sortBy = ['isRefined', 'count:desc', 'name:asc'];
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: _propTypes2.default.string,
attributeName: _propTypes2.default.string.isRequired,
operator: _propTypes2.default.oneOf(['and', 'or']),
showMore: _propTypes2.default.bool,
limitMin: _propTypes2.default.number,
limitMax: _propTypes2.default.number,
defaultRefinement: _propTypes2.default.arrayOf(_propTypes2.default.string),
withSearchBox: _propTypes2.default.bool,
searchForFacetValues: _propTypes2.default.bool, // @deprecated
transformItems: _propTypes2.default.func
},
defaultProps: {
operator: 'or',
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var _this = this;
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.');
}
// Search For Facet Values is not available with derived helper (used for multi index search)
if (props.withSearchBox && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: canRefine,
isFromSearch: isFromSearch,
withSearchBox: withSearchBox
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) {
return {
label: v.name,
value: getValue(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
operator = props.operator,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet';
var addRefinementKey = addKey + 'Refinement';
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
searchParameters = searchParameters[addKey](attributeName);
return getCurrentRefinement(props, searchState, this.context).reduce(function (res, val) {
return res[addRefinementKey](attributeName, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId(props);
var context = this.context;
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: getCurrentRefinement(props, searchState, context).length > 0 ? [{
attributeName: props.attributeName,
label: props.attributeName + ': ',
currentRefinement: getCurrentRefinement(props, searchState, context),
value: function value(nextState) {
return _refine(props, nextState, [], context);
},
items: getCurrentRefinement(props, searchState, context).map(function (item) {
return {
label: '' + item,
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement(props, nextState, context).filter(function (other) {
return other !== item;
});
return _refine(props, searchState, nextSelectedItems, context);
}
};
})
}] : []
};
}
});
/***/ }),
/* 339 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(35);
var _omit3 = _interopRequireDefault(_omit2);
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
var _utils = __webpack_require__(44);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectScrollTo connector provides the logic to build a widget that will
* let the page scroll to a certain point.
* @name connectScrollTo
* @kind connector
* @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget.
* @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo
* @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default)
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: _propTypes2.default.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var id = props.scrollOn;
var value = (0, _indexUtils.getCurrentRefinementValue)(props, searchState, this.context, id, null, function (currentRefinement) {
return currentRefinement;
});
if (!this._prevSearchState) {
this._prevSearchState = {};
}
/* Get the subpart of the state that interest us*/
if ((0, _indexUtils.hasMultipleIndex)(this.context)) {
var index = (0, _indexUtils.getIndex)(this.context);
searchState = searchState.indices ? searchState.indices[index] : {};
}
/*
if there is a change in the app that has been triggered by another element than
"props.scrollOn (id) or the Configure widget, we need to keep track of the search state to
know if there's a change in the app that was not triggered by the props.scrollOn (id)
or the Configure widget. This is useful when using ScrollTo in combination of Pagination.
As pagination can be change by every widget, we want to scroll only if it cames from the pagination
widget itself. We also remove the configure key from the search state to do this comparaison because for
now configure values are not present in the search state before a first refinement has been made
and will false the results.
See: https://github.com/algolia/react-instantsearch/issues/164
*/
var cleanedSearchState = (0, _omit3.default)((0, _omit3.default)(searchState, 'configure'), id);
var hasNotChanged = (0, _utils.shallowEqual)(this._prevSearchState, cleanedSearchState);
this._prevSearchState = cleanedSearchState;
return { value: value, hasNotChanged: hasNotChanged };
}
});
/***/ }),
/* 340 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'query';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId(props);
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, '', function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return '';
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, getId());
}
/**
* connectSearchBox connector provides the logic to build a widget that will
* let the user search for a query.
* @name connectSearchBox
* @kind connector
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the query to search for.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: _propTypes2.default.string
},
getProvidedProps: function getProvidedProps(props, searchState) {
return {
currentRefinement: getCurrentRefinement(props, searchState, this.context)
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context));
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: currentRefinement === null ? [] : [{
label: id + ': ' + currentRefinement,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 341 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'sortBy';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId(props);
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return null;
});
}
/**
* The connectSortBy connector provides the logic to build a widget that will
* display a list of indices. This allows a user to change how the hits are being sorted.
* @name connectSortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind connector
* @propType {string} defaultRefinement - The default selected index.
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaSortBy',
propTypes: {
defaultRefinement: _propTypes2.default.string,
items: _propTypes2.default.arrayOf(_propTypes2.default.shape({
label: _propTypes2.default.string,
value: _propTypes2.default.string.isRequired
})).isRequired,
transformItems: _propTypes2.default.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false });
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement(props, searchState, this.context);
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 342 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectStats connector provides the logic to build a widget that will
* displays algolia search statistics (hits number and processing time).
* @name connectStats
* @kind connector
* @providedPropType {number} nbHits - number of hits returned by Algolia.
* @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = (0, _indexUtils.getResults)(searchResults, this.context);
if (!results) {
return null;
}
return {
nbHits: results.nbHits,
processingTimeMS: results.processingTimeMS
};
}
});
/***/ }),
/* 343 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId(props) {
return props.attributeName;
}
var namespace = 'toggle';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), false, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return false;
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectToggle connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization.
* @name connectToggle
* @kind connector
* @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attributeName`.
* @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {boolean} currentRefinement - the refinement currently applied
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaToggle',
propTypes: {
label: _propTypes2.default.string,
filter: _propTypes2.default.func,
attributeName: _propTypes2.default.string,
value: _propTypes2.default.any,
defaultRefinement: _propTypes2.default.bool
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return { currentRefinement: currentRefinement };
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
value = props.value,
filter = props.filter;
var checked = getCurrentRefinement(props, searchState, this.context);
if (checked) {
if (attributeName) {
searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value);
}
if (filter) {
searchParameters = filter(searchParameters);
}
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var checked = getCurrentRefinement(props, searchState, this.context);
var items = [];
var index = (0, _indexUtils.getIndex)(this.context);
if (checked) {
items.push({
label: props.label,
currentRefinement: props.label,
attributeName: props.attributeName,
value: function value(nextState) {
return _refine(props, nextState, false, _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
/***/ }),
/* 344 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getId = undefined;
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var getId = exports.getId = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function transformValue(values) {
return values.reduce(function (acc, item) {
if (item.isRefined) {
acc.push({
label: item.name,
// If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label
// If dealing with the first level, "value" is equal to the current label
value: item.path
});
// Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one
if (item.data) {
acc = acc.concat(transformValue(item.data, acc));
}
}
return acc;
}, []);
}
/**
* The breadcrumb component is s a type of secondary navigation scheme that
* reveals the user’s location in a website or web application.
*
* @name connectBreadcrumb
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a Breadcrumb of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} {React.Element} [separator=' > '] - Specifies the level separator used in the data.
* @propType {string} [rootURL=null] - The root element's URL (the originating page).
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaBreadcrumb',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
rootURL: _propTypes2.default.string,
separator: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.element]),
transformItems: _propTypes2.default.func
},
defaultProps: {
rootURL: null,
separator: ' > '
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var id = getId(props);
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
canRefine: false
};
}
var values = results.getFacetValues(id);
var items = values.data ? transformValue(values.data) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
canRefine: transformedItems.length > 0,
items: transformedItems
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
}
});
/***/ }),
/* 345 */,
/* 346 */,
/* 347 */,
/* 348 */,
/* 349 */,
/* 350 */,
/* 351 */,
/* 352 */,
/* 353 */,
/* 354 */,
/* 355 */,
/* 356 */,
/* 357 */,
/* 358 */,
/* 359 */,
/* 360 */,
/* 361 */,
/* 362 */,
/* 363 */,
/* 364 */,
/* 365 */,
/* 366 */,
/* 367 */,
/* 368 */,
/* 369 */,
/* 370 */,
/* 371 */,
/* 372 */,
/* 373 */,
/* 374 */,
/* 375 */,
/* 376 */,
/* 377 */,
/* 378 */,
/* 379 */,
/* 380 */,
/* 381 */,
/* 382 */,
/* 383 */,
/* 384 */,
/* 385 */,
/* 386 */,
/* 387 */,
/* 388 */,
/* 389 */,
/* 390 */,
/* 391 */,
/* 392 */,
/* 393 */,
/* 394 */,
/* 395 */,
/* 396 */,
/* 397 */,
/* 398 */,
/* 399 */,
/* 400 */,
/* 401 */,
/* 402 */,
/* 403 */,
/* 404 */,
/* 405 */,
/* 406 */,
/* 407 */,
/* 408 */,
/* 409 */,
/* 410 */,
/* 411 */,
/* 412 */,
/* 413 */,
/* 414 */,
/* 415 */,
/* 416 */,
/* 417 */,
/* 418 */,
/* 419 */,
/* 420 */,
/* 421 */,
/* 422 */,
/* 423 */,
/* 424 */,
/* 425 */,
/* 426 */,
/* 427 */,
/* 428 */,
/* 429 */,
/* 430 */,
/* 431 */,
/* 432 */,
/* 433 */,
/* 434 */,
/* 435 */,
/* 436 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectConfigure = __webpack_require__(222);
Object.defineProperty(exports, 'connectConfigure', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectConfigure).default;
}
});
var _connectCurrentRefinements = __webpack_require__(211);
Object.defineProperty(exports, 'connectCurrentRefinements', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectCurrentRefinements).default;
}
});
var _connectHierarchicalMenu = __webpack_require__(248);
Object.defineProperty(exports, 'connectHierarchicalMenu', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectHierarchicalMenu).default;
}
});
var _connectHighlight = __webpack_require__(218);
Object.defineProperty(exports, 'connectHighlight', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectHighlight).default;
}
});
var _connectHits = __webpack_require__(331);
Object.defineProperty(exports, 'connectHits', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectHits).default;
}
});
var _connectAutoComplete = __webpack_require__(437);
Object.defineProperty(exports, 'connectAutoComplete', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectAutoComplete).default;
}
});
var _connectHitsPerPage = __webpack_require__(332);
Object.defineProperty(exports, 'connectHitsPerPage', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectHitsPerPage).default;
}
});
var _connectInfiniteHits = __webpack_require__(333);
Object.defineProperty(exports, 'connectInfiniteHits', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectInfiniteHits).default;
}
});
var _connectMenu = __webpack_require__(334);
Object.defineProperty(exports, 'connectMenu', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectMenu).default;
}
});
var _connectMultiRange = __webpack_require__(335);
Object.defineProperty(exports, 'connectMultiRange', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectMultiRange).default;
}
});
var _connectPagination = __webpack_require__(336);
Object.defineProperty(exports, 'connectPagination', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectPagination).default;
}
});
var _connectPoweredBy = __webpack_require__(337);
Object.defineProperty(exports, 'connectPoweredBy', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectPoweredBy).default;
}
});
var _connectRange = __webpack_require__(209);
Object.defineProperty(exports, 'connectRange', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectRange).default;
}
});
var _connectRefinementList = __webpack_require__(338);
Object.defineProperty(exports, 'connectRefinementList', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectRefinementList).default;
}
});
var _connectScrollTo = __webpack_require__(339);
Object.defineProperty(exports, 'connectScrollTo', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectScrollTo).default;
}
});
var _connectBreadcrumb = __webpack_require__(344);
Object.defineProperty(exports, 'connectBreadcrumb', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectBreadcrumb).default;
}
});
var _connectSearchBox = __webpack_require__(340);
Object.defineProperty(exports, 'connectSearchBox', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectSearchBox).default;
}
});
var _connectSortBy = __webpack_require__(341);
Object.defineProperty(exports, 'connectSortBy', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectSortBy).default;
}
});
var _connectStats = __webpack_require__(342);
Object.defineProperty(exports, 'connectStats', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectStats).default;
}
});
var _connectToggle = __webpack_require__(343);
Object.defineProperty(exports, 'connectToggle', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectToggle).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/***/ }),
/* 437 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var getId = function getId() {
return 'query';
};
function getCurrentRefinement(props, searchState, context) {
var id = getId();
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, '', function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return '';
});
}
function getHits(searchResults) {
if (searchResults.results) {
if (searchResults.results.hits && Array.isArray(searchResults.results.hits)) {
return searchResults.results.hits;
} else {
return Object.keys(searchResults.results).reduce(function (hits, index) {
return [].concat(_toConsumableArray(hits), [{
index: index,
hits: searchResults.results[index].hits
}]);
}, []);
}
} else {
return [];
}
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, getId());
}
/**
* connectAutoComplete connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
* @name connectAutoComplete
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state.
* @providedPropType {function} refine - a function to change the query.
* @providedPropType {string} currentRefinement - the query to search for.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaAutoComplete',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
return {
hits: getHits(searchResults),
currentRefinement: getCurrentRefinement(props, searchState, this.context)
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
/* connectAutoComplete needs to be considered as a widget to trigger a search if no others widgets are used.
* To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState
* See createConnector.js
* */
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context));
}
});
/***/ })
/******/ ]);
});
//# sourceMappingURL=Connectors.js.map |
demo/src/containers/Button.js | ilxanlar/cathode | import React from 'react';
import { Button, ButtonGroup, Grid } from '../../../src';
import { moodKeys } from '../../../src/helpers/propTypes';
export default () => (
<div>
<Grid.Row multi>
{
moodKeys.map((mood, key) => (
<Grid.Column key={key} xs={12} sm={12} md={6} xl={4} xxl={3}>
<Button mood={mood} block>
{mood}
</Button>
</Grid.Column>
))
}
</Grid.Row>
<Grid.Row multi>
{
moodKeys.map((mood, key) => (
<Grid.Column key={key} xs={12} sm={12} md={6} xl={4} xxl={3}>
<Button mood={mood} block disabled loading>
{mood}
</Button>
</Grid.Column>
))
}
</Grid.Row>
<Grid.Row multi>
{
moodKeys.map((mood, key) => (
<Grid.Column key={key} xs={12} sm={12} md={6} xl={4} xxl={3}>
<Button mood={mood} block ghost>
{mood}
</Button>
</Grid.Column>
))
}
</Grid.Row>
<Grid.Row multi>
{
moodKeys.map((mood, key) => (
<Grid.Column key={key} xs={12} sm={12} md={6} xl={4} xxl={3}>
<Button mood={mood} block glass>
{mood}
</Button>
</Grid.Column>
))
}
</Grid.Row>
<Grid.Row multi>
{
moodKeys.map((mood, key) => (
<Grid.Column key={key} xs={12} sm={12} md={6} xl={4} xxl={3}>
<Button mood={mood} block ghost disabled>
{mood}
</Button>
</Grid.Column>
))
}
</Grid.Row>
<Grid.Row multi>
{
moodKeys.map((mood, key) => (
<Grid.Column key={key} xs={12} sm={12} md={6} xl={4} xxl={3}>
<Button mood={mood} block disableHoverStyles disablePressStyles>
{mood}
</Button>
</Grid.Column>
))
}
</Grid.Row>
<br />
<ButtonGroup>
<Button>Button</Button>
<Button mood="error" wide>Button</Button>
<Button mood="success" wide>Button</Button>
<Button disabled>Button</Button>
<Button ghost>Button</Button>
<Button ghost disabled>Button</Button>
</ButtonGroup>
</div>
);
|
src/svg-icons/av/remove-from-queue.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvRemoveFromQueue = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2H8v-2h8z"/>
</SvgIcon>
);
AvRemoveFromQueue = pure(AvRemoveFromQueue);
AvRemoveFromQueue.displayName = 'AvRemoveFromQueue';
export default AvRemoveFromQueue;
|
actor-apps/app-web/src/app/components/Main.react.js | yangchenghu/actor-platform | import React from 'react';
import {PeerTypes} from 'constants/ActorAppConstants';
import requireAuth from 'utils/require-auth';
import ActorClient from 'utils/ActorClient';
import PeerUtils from 'utils/PeerUtils';
import RouterContainer from 'utils/RouterContainer';
import DialogActionCreators from 'actions/DialogActionCreators';
import VisibilityActionCreators from 'actions/VisibilityActionCreators';
import SidebarSection from 'components/SidebarSection.react';
import DialogSection from 'components/DialogSection.react';
import Banner from 'components/common/Banner.react';
import Favicon from 'components/common/Favicon.react';
const visibilitychange = 'visibilitychange';
const onVisibilityChange = () => {
if (!document.hidden) {
VisibilityActionCreators.createAppVisible();
} else {
VisibilityActionCreators.createAppHidden();
}
};
class Main extends React.Component {
static contextTypes = {
router: React.PropTypes.func
};
static propTypes = {
params: React.PropTypes.object
};
constructor(props) {
super(props);
const { params } = props;
document.addEventListener(visibilitychange, onVisibilityChange);
if (!document.hidden) {
VisibilityActionCreators.createAppVisible();
}
const peer = PeerUtils.stringToPeer(params.id);
if (peer) {
// It is needed to prevent failure on opening dialog while library didn't load dialogs (right after auth)
let peerInfo = undefined;
if (peer.type == PeerTypes.GROUP) {
peerInfo = ActorClient.getGroup(peer.id)
} else {
peerInfo = ActorClient.getUser(peer.id)
}
if (peerInfo) {
DialogActionCreators.selectDialogPeer(peer);
} else {
RouterContainer.get().transitionTo('/');
}
}
}
render() {
const { params } = this.props;
const peer = PeerUtils.stringToPeer(params.id);
return (
<div className="app">
<Favicon/>
<Banner/>
<SidebarSection selectedPeer={peer}/>
<DialogSection peer={peer}/>
</div>
);
}
}
export default requireAuth(Main);
|
app/jsx/canvas_cropper/cropperMaker.js | venturehive/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import ReactDOM from 'react-dom'
import CanvasCropper from './cropper'
// CanvasCropperMaker is the component you'll create if injecting the cropper
// into existing non-react UI (see UploadFileView.coffee for sample usage)
// let cropper = new Cropper(@$('.avatar-preview')[0], {imgFile: @file, width: @avatarSize.w, height: @avatarSize.h})
// cropper.render()
//
class CanvasCropperMaker {
// @param root: DOM node where I want the cropper created
// @param props: properties
// imgFile: the File object returned from the native file open dialog
// width: desired width in px of the final cropped image
// height: desired height in px if the final cropped image
constructor (root, props) {
this.root = root; // DOM node we render into
this.imgFile = props.imgFile;
this.width = props.width || 128;
this.height = props.width || 128;
this.cropper = null;
}
unmount () {
ReactDOM.unmountComponentAtNode(this.root);
}
render () {
ReactDOM.render(
<CanvasCropper ref={(el) => { this.cropper = el }} imgFile={this.imgFile} width={this.width} height={this.height} />,
this.root
)
}
// crop the image.
// returns a promise that resolves with the cropped image as a blob
crop () {
return this.cropper
? this.cropper.crop()
: null;
}
}
export default CanvasCropperMaker
|
docs/app/Examples/modules/Embed/Types/EmbedExampleCustom.js | koenvg/Semantic-UI-React | import React from 'react'
import { Embed } from 'semantic-ui-react'
const EmbedExampleCustom = () => (
<Embed
icon='right circle arrow'
placeholder='http://semantic-ui.com/images/image-16by9.png'
url='http://www.myfav.es/jack'
/>
)
export default EmbedExampleCustom
|
ReactJS_Seed_Project/app/views/Minor.js | huang6349/inspinia | import React, { Component } from 'react';
class Minor extends Component {
render() {
return (
<div className="wrapper wrapper-content animated fadeInRight">
<div className="row">
<div className="col-lg-12">
<div className="text-center m-t-lg">
<h1>
Sample example of second view
</h1>
<small>
Written in Minor.js component
</small>
</div>
</div>
</div>
</div>
)
}
}
export default Minor |
src/ChromeTab/Tab.js | teramotodaiki/h4p | import React from 'react';
import { SourceFile } from '../File/';
const getUniqueId = ((id) => () => 'Tab__' + ++id)(0);
export default class Tab {
constructor(props) {
this.props = Object.freeze(props);
this.key = props.key || getUniqueId();
}
get file() {
return this.props.getFile() || new SourceFile({
name: 'Not Found',
type: 'text/plain',
text: 'File Not Found :-/',
});
}
get label() {
const { plane, ext } = this.file;
return plane + ext;
}
get isSelected() {
return !!this.props.isSelected;
}
is(tab) {
if (!tab.file || !this.file) {
return false;
}
return (tab.key === this.key) ||
tab.file.key === this.file.key;
};
select(isSelected) {
const props = Object.assign({}, this.props, {
key: this.key,
isSelected,
});
return new Tab(props);
}
renderContent(props) {
if (!this.file) {
return null;
}
return (
<this.file.component
file={this.file}
{...props}
/>
);
}
}
|
packages/icons/src/actions.js | yldio/joyent-portal | import React from 'react';
import Rotate from './rotate';
import calcFill from './fill';
export default ({
fill = null,
light = false,
disabled = false,
direction = 'down',
colors = {},
style = {},
...rest
}) => (
<Rotate direction={direction}>
{({ style: rotateStyle }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="4"
height="16"
viewBox="0 0 4 16"
style={{ ...style, ...rotateStyle }}
{...rest}
>
<path
fill={calcFill({ fill, disabled, light, colors })}
d="M2,16a2,2,0,1,0-2-2A2,2,0,0,0,2,16Zm0-6A2,2,0,1,0,0,8,2,2,0,0,0,2,10ZM2,4A2,2,0,1,0,0,2,2,2,0,0,0,2,4Z"
/>
</svg>
)}
</Rotate>
);
|
src/components/header/Header.js | metasfresh/metasfresh-webui-frontend | import counterpart from 'counterpart';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import classnames from 'classnames';
import {
deleteRequest,
duplicateRequest,
openFile,
} from '../../actions/GenericActions';
import { openModal } from '../../actions/WindowActions';
import logo from '../../assets/images/metasfresh_logo_green_thumb.png';
import keymap from '../../shortcuts/keymap';
import Indicator from '../app/Indicator';
import Prompt from '../app/Prompt';
import NewEmail from '../email/NewEmail';
import Inbox from '../inbox/Inbox';
import NewLetter from '../letter/NewLetter';
import GlobalContextShortcuts from '../keyshortcuts/GlobalContextShortcuts';
import Tooltips from '../tooltips/Tooltips';
import MasterWidget from '../widget/MasterWidget';
import Breadcrumb from './Breadcrumb';
import SideList from './SideList';
import Subheader from './SubHeader';
import UserDropdown from './UserDropdown';
/**
* @file The Header component is shown in every view besides Modal or RawModal in frontend. It defines
* the top bar with different menus and icons in metasfresh WebUI. It hosts the action menu,
* breadcrumb, logo, notification menu, avatar and sidelist menu.
* @module Header
* @extends Component
*/
class Header extends Component {
state = {
isSubheaderShow: false,
isSideListShow: false,
sideListTab: null,
isMenuOverlayShow: false,
menuOverlay: null,
scrolled: false,
isInboxOpen: false,
isUDOpen: false,
tooltipOpen: '',
isEmailOpen: false,
prompt: { open: false },
};
udRef = React.createRef();
inboxRef = React.createRef();
componentDidMount() {
this.initEventListeners();
}
componentWillUnmount() {
this.toggleScrollScope(false);
this.removeEventListeners();
}
UNSAFE_componentWillUpdate(nextProps) {
const { dropzoneFocused } = this.props;
if (
nextProps.dropzoneFocused !== dropzoneFocused &&
nextProps.dropzoneFocused
) {
this.closeOverlays();
}
}
componentDidUpdate(prevProps, prevState) {
if (
prevProps.me.language !== undefined &&
JSON.stringify(prevProps.me.language) !==
JSON.stringify(this.props.me.language) &&
!Array.isArray(prevProps.me.language)
) {
// Need to reload page completely when current locale gets changed
window.location.reload(false);
} else if (
this.state.isUDOpen &&
!prevState.isUDOpen &&
!!this.udRef.current
) {
this.udRef.current.enableOnClickOutside();
} else if (
!this.state.isUDOpen &&
prevState.isUDOpen &&
!!this.udRef.current
) {
this.udRef.current.disableOnClickOutside();
} else if (
this.state.isInboxOpen &&
!prevState.isInboxOpen &&
!!this.inboxRef.current
) {
this.inboxRef.current.enableOnClickOutside();
} else if (
!this.state.isInboxOpen &&
prevState.isInboxOpen &&
!!this.inboxRef.current
) {
this.inboxRef.current.disableOnClickOutside();
}
}
/**
* @method initEventListeners
* @summary ToDo: Describe the method
*/
initEventListeners = () => {
document.addEventListener('scroll', this.handleScroll);
};
/**
* @method removeEventListeners
* @summary ToDo: Describe the method
*/
removeEventListeners = () => {
document.removeEventListener('scroll', this.handleScroll);
};
/**
* @method handleInboxOpen
* @summary ToDo: Describe the method
* @param {object} state
*/
handleInboxOpen = (state) => {
this.setState({ isInboxOpen: !!state });
};
/**
* @method handleInboxToggle
* @summary ToDo: Describe the method
*/
handleInboxToggle = () => {
this.setState({ isInboxOpen: !this.state.isInboxOpen });
};
/**
* @method handleUDOpen
* @summary ToDo: Describe the method
* @param {object} state
*/
handleUDOpen = (state) => {
this.setState({ isUDOpen: !!state });
};
/**
* @method handleUDScroll
* @summary ToDo: Describe the method
*/
handleUDToggle = () => {
this.setState({ isUDOpen: !this.state.isUDOpen });
};
/**
* @method handleMenuOverlay
* @summary ToDo: Describe the method
* @param {object} e
* @param {string} nodeId
*/
handleMenuOverlay = (e, nodeId) => {
const { isSubheaderShow, isSideListShow } = this.state;
if (e) {
e.preventDefault();
}
let toggleBreadcrumb = () => {
this.setState(
{
menuOverlay: nodeId,
},
() => {
if (nodeId !== '') {
this.setState({ isMenuOverlayShow: true });
} else {
this.setState({ isMenuOverlayShow: false });
}
}
);
};
if (!isSubheaderShow && !isSideListShow) {
toggleBreadcrumb();
}
};
/**
* @method handleScroll
* @summary ToDo: Describe the method
* @param {object} event
*/
handleScroll = (event) => {
const target = event.srcElement;
let scrollTop = target && target.body.scrollTop;
if (!scrollTop) {
scrollTop = document.documentElement.scrollTop;
}
if (scrollTop > 0) {
this.setState({ scrolled: true });
} else {
this.setState({ scrolled: false });
}
};
/**
* @method handleDashboardLink
* @summary ToDo: Describe the method
*/
handleDashboardLink = () => {
const { dispatch } = this.props;
dispatch(push('/'));
};
/**
* @method toggleScrollScope
* @summary ToDo: Describe the method
* @param {bool} open
*/
toggleScrollScope = (open) => {
if (!open) {
document.body.style.overflow = 'auto';
} else {
document.body.style.overflow = 'hidden';
}
};
/**
* @method toggleTooltip
* @summary ToDo: Describe the method
* @param {object} event
*/
toggleTooltip = (tooltip) => {
this.setState({ tooltipOpen: tooltip });
};
/**
* @method handleComments
* @summary opens the modal with the comments panel
*/
handleComments = () => {
const { windowId } = this.props;
this.openModal(
windowId,
'static',
counterpart.translate('window.comments.caption'),
null,
null,
null,
null,
'comments'
);
};
/**
* @method openModel
* @summary ToDo: Describe the method
* @param {string} windowId
* @param {*} modalType
* @param {*} caption
* @param {bool} isAdvanced
* @param {*} selected
* @param {*} childViewId
* @param {*} childViewSelectedIds
* @param {*} staticModalType
*/
openModal = (
windowId,
modalType,
caption,
isAdvanced,
selected,
childViewId,
childViewSelectedIds,
staticModalType
) => {
const { dispatch, query } = this.props;
dispatch(
openModal(
caption,
windowId,
modalType,
null,
null,
isAdvanced,
query && query.viewId,
selected,
null,
null,
null,
null,
childViewId,
childViewSelectedIds,
staticModalType
)
);
};
/**
* @method openModalRow
* @summary ToDo: Describe the method
* @param {string} windowId
* @param {*} modalType
* @param {*} caption
* @param {string} tabId
* @param {string} rowId
* @param {string} rowId
*/
openModalRow = (
windowId,
modalType,
caption,
tabId,
rowId,
staticModalType
) => {
const { dispatch } = this.props;
dispatch(
openModal(
caption,
windowId,
modalType,
tabId,
rowId,
false,
null,
null,
null,
null,
null,
null,
null,
null,
staticModalType
)
);
};
/**
* @method handlePrint
* @summary ToDo: Describe the method
* @param {string} windowId
* @param {string} docId
* @param {string} docNo
*/
handlePrint = (windowId, docId, docNo) => {
openFile(
'window',
windowId,
docId,
'print',
`${windowId}_${docNo ? `${docNo}` : `${docId}`}.pdf`
);
};
/**
* @method handleClone
* @summary ToDo: Describe the method
* @param {string} windowId
* @param {string} docId
*/
handleClone = (windowId, docId) => {
const { dispatch } = this.props;
duplicateRequest('window', windowId, docId).then((response) => {
if (response && response.data && response.data.id) {
dispatch(push(`/window/${windowId}/${response.data.id}`));
}
});
};
/**
* @method handleDelete
* @summary ToDo: Describe the method
*/
handleDelete = () => {
this.setState({
prompt: Object.assign({}, this.state.prompt, { open: true }),
});
};
/**
* @method handleEmail
* @summary ToDo: Describe the method
*/
handleEmail = () => {
this.setState({ isEmailOpen: true });
};
/**
* @method handleLetter
* @summary ToDo: Describe the method
*/
handleLetter = () => {
this.setState({ isLetterOpen: true });
};
/**
* @method handleCloseEmail
* @summary ToDo: Describe the method
*/
handleCloseEmail = () => {
this.setState({ isEmailOpen: false });
};
/**
* @method handleCloseLetter
* @summary ToDo: Describe the method
*/
handleCloseLetter = () => {
this.setState({ isLetterOpen: false });
};
/**
* @method handlePromptCancelClick
* @summary ToDo: Describe the method
*/
handlePromptCancelClick = () => {
this.setState({
prompt: Object.assign({}, this.state.prompt, { open: false }),
});
};
/**
* @method handlePromptScroll
* @summary ToDo: Describe the method
* @param {string} windowId
* @param {docId} docId
*/
handlePromptSubmitClick = (windowId, docId) => {
const { dispatch, handleDeletedStatus } = this.props;
this.setState(
{
prompt: Object.assign({}, this.state.prompt, { open: false }),
},
() => {
deleteRequest('window', windowId, null, null, [docId]).then(() => {
handleDeletedStatus(true);
dispatch(push(`/window/${windowId}`));
});
}
);
};
/**
* @method handleDocStatusToggle
* @summary ToDo: Describe the method
* @param {object} event
*/
handleDocStatusToggle = (close) => {
const elem = document.getElementsByClassName('js-dropdown-toggler')[0];
if (close) {
elem.blur();
} else {
if (document.activeElement === elem) {
elem.blur();
} else {
elem.focus();
}
}
};
/**
* @method handleSidelistToggle
* @summary ToDo: Describe the method
* @param {string} id
*/
handleSidelistToggle = (id = null) => {
const { sideListTab } = this.state;
const isSideListShow = id !== null && id !== sideListTab;
this.toggleScrollScope(isSideListShow);
this.setState({
isSideListShow,
sideListTab: id !== sideListTab ? id : null,
});
};
/**
* @method closeOverlays
* @summary ToDo: Describe the method
* @param {object} clickedItem
*/
closeOverlays = (clickedItem, callback) => {
const { isSubheaderShow } = this.state;
const state = {
menuOverlay: null,
isMenuOverlayShow: false,
isInboxOpen: false,
isUDOpen: false,
isSideListShow: false,
tooltipOpen: '',
};
if (clickedItem) {
delete state[clickedItem];
}
state.isSubheaderShow =
clickedItem === 'isSubheaderShow' ? !isSubheaderShow : false;
this.setState(state, callback);
if (
document.getElementsByClassName('js-dropdown-toggler')[0] &&
clickedItem !== 'dropdown'
) {
this.handleDocStatusToggle(true);
}
};
/**
* @method redirect
* @summary ToDo: Describe the method
* @param {*} where
*/
redirect = (where) => {
const { dispatch } = this.props;
dispatch(push(where));
};
/**
* @method render
* @summary ToDo: Describe the method
*/
render() {
const {
docSummaryData,
siteName,
docNoData,
docStatus,
docStatusData,
dataId,
breadcrumb,
showSidelist,
inbox,
entity,
query,
showIndicator,
windowId,
// TODO: We should be using indicator from the state instead of another variable
isDocumentNotSaved,
notfound,
docId,
me,
editmode,
handleEditModeToggle,
activeTab,
plugins,
} = this.props;
const {
isSubheaderShow,
isSideListShow,
menuOverlay,
isInboxOpen,
scrolled,
isMenuOverlayShow,
tooltipOpen,
prompt,
sideListTab,
isUDOpen,
isEmailOpen,
isLetterOpen,
} = this.state;
return (
<div>
{prompt.open && (
<Prompt
title="Delete"
text="Are you sure?"
buttons={{ submit: 'Delete', cancel: 'Cancel' }}
onCancelClick={this.handlePromptCancelClick}
onSubmitClick={() => this.handlePromptSubmitClick(windowId, dataId)}
/>
)}
<nav
className={classnames('header header-super-faded', {
'header-shadow': scrolled,
})}
>
<div className="container-fluid">
<div className="header-container">
<div className="header-left-side">
<div
onClick={() => this.closeOverlays('isSubheaderShow')}
onMouseEnter={() =>
this.toggleTooltip(keymap.OPEN_ACTIONS_MENU)
}
onMouseLeave={() => this.toggleTooltip('')}
className={classnames(
'btn-square btn-header',
'tooltip-parent js-not-unselect',
{
'btn-meta-default-dark btn-subheader-open btn-header-open': isSubheaderShow,
'btn-meta-primary': !isSubheaderShow,
}
)}
>
<i className="meta-icon-more" />
{tooltipOpen === keymap.OPEN_ACTIONS_MENU && (
<Tooltips
name={keymap.OPEN_ACTIONS_MENU}
action={counterpart.translate(
'mainScreen.actionMenu.tooltip'
)}
type=""
/>
)}
</div>
<Breadcrumb
breadcrumb={breadcrumb}
windowType={windowId}
docSummaryData={docSummaryData}
dataId={dataId}
siteName={siteName}
menuOverlay={menuOverlay}
docId={docId}
isDocumentNotSaved={isDocumentNotSaved}
handleMenuOverlay={this.handleMenuOverlay}
openModal={this.openModal}
/>
</div>
<div className="header-center js-not-unselect">
<img
src={logo}
className="header-logo pointer"
onClick={this.handleDashboardLink}
/>
</div>
<div className="header-right-side">
{docStatus && (
<div
className="hidden-sm-down tooltip-parent js-not-unselect"
onClick={() => this.toggleTooltip('')}
onMouseEnter={() => this.toggleTooltip(keymap.DOC_STATUS)}
>
<MasterWidget
entity="window"
windowType={windowId}
dataId={dataId}
docId={docId}
activeTab={activeTab}
widgetData={[docStatusData]}
noLabel
type="primary"
dropdownOpenCallback={() =>
this.closeOverlays('dropdown')
}
{...docStatus}
/>
{tooltipOpen === keymap.DOC_STATUS && (
<Tooltips
name={keymap.DOC_STATUS}
action={counterpart.translate(
'mainScreen.docStatus.tooltip'
)}
type=""
/>
)}
</div>
)}
<div
className={classnames(
'header-item-container',
'header-item-container-static',
'pointer tooltip-parent js-not-unselect',
{
'header-item-open': isInboxOpen,
}
)}
onClick={() =>
this.closeOverlays('', () => this.handleInboxOpen(true))
}
onMouseEnter={() =>
this.toggleTooltip(keymap.OPEN_INBOX_MENU)
}
onMouseLeave={() => this.toggleTooltip('')}
>
<span className="header-item header-item-badge icon-lg">
<i className="meta-icon-notifications" />
{inbox.unreadCount > 0 && (
<span className="notification-number">
{inbox.unreadCount}
</span>
)}
</span>
{tooltipOpen === keymap.OPEN_INBOX_MENU && (
<Tooltips
name={keymap.OPEN_INBOX_MENU}
action={counterpart.translate('mainScreen.inbox.tooltip')}
type={''}
/>
)}
</div>
<Inbox
ref={this.inboxRef}
open={isInboxOpen}
close={this.handleInboxOpen}
onFocus={() => this.handleInboxOpen(true)}
disableOnClickOutside={true}
inbox={inbox}
/>
<UserDropdown
ref={this.udRef}
open={isUDOpen}
handleUDOpen={this.handleUDOpen}
disableOnClickOutside={true}
redirect={this.redirect}
shortcut={keymap.OPEN_AVATAR_MENU}
toggleTooltip={this.toggleTooltip}
tooltipOpen={tooltipOpen}
me={me}
plugins={plugins}
/>
{showSidelist && (
<div
className={classnames(
'tooltip-parent btn-header',
'side-panel-toggle btn-square',
'js-not-unselect',
{
'btn-meta-default-bright btn-header-open': isSideListShow,
'btn-meta-primary': !isSideListShow,
}
)}
onClick={() => this.handleSidelistToggle(0)}
onMouseEnter={() =>
this.toggleTooltip(keymap.OPEN_SIDEBAR_MENU_0)
}
onMouseLeave={() => this.toggleTooltip('')}
>
<i className="meta-icon-list" />
{tooltipOpen === keymap.OPEN_SIDEBAR_MENU_0 && (
<Tooltips
name={keymap.OPEN_SIDEBAR_MENU_0}
action={counterpart.translate(
/* eslint-disable max-len */
'mainScreen.sideList.tooltip'
/* eslint-enable max-len */
)}
type=""
/>
)}
</div>
)}
</div>
</div>
</div>
{showIndicator && (
<Indicator isDocumentNotSaved={isDocumentNotSaved} />
)}
</nav>
{isSubheaderShow && (
<Subheader
closeSubheader={() => this.closeOverlays('isSubheaderShow')}
docNo={docNoData && docNoData.value}
openModal={this.openModal}
openModalRow={this.openModalRow}
handlePrint={this.handlePrint}
handleClone={this.handleClone}
handleDelete={this.handleDelete}
handleEmail={this.handleEmail}
handleLetter={this.handleLetter}
handleComments={this.handleComments}
redirect={this.redirect}
disableOnClickOutside={!isSubheaderShow}
breadcrumb={breadcrumb}
notfound={notfound}
query={query}
entity={entity}
dataId={dataId}
windowId={windowId}
viewId={query && query.viewId}
siteName={siteName}
editmode={editmode}
handleEditModeToggle={handleEditModeToggle}
activeTab={activeTab}
/>
)}
{showSidelist && isSideListShow && (
<SideList
windowType={windowId ? windowId : ''}
closeOverlays={this.closeOverlays}
closeSideList={this.handleSidelistToggle}
isSideListShow={isSideListShow}
disableOnClickOutside={!showSidelist}
docId={dataId}
defaultTab={sideListTab}
open
/>
)}
{isEmailOpen && (
<NewEmail
windowId={windowId ? windowId : ''}
docId={dataId}
handleCloseEmail={this.handleCloseEmail}
/>
)}
{isLetterOpen && (
<NewLetter
windowId={windowId ? windowId : ''}
docId={dataId}
handleCloseLetter={this.handleCloseLetter}
/>
)}
<GlobalContextShortcuts
handleSidelistToggle={this.handleSidelistToggle}
handleMenuOverlay={
isMenuOverlayShow
? () => this.handleMenuOverlay('', '')
: () =>
this.closeOverlays('', () => this.handleMenuOverlay('', '0'))
}
handleInboxToggle={this.handleInboxToggle}
handleUDToggle={this.handleUDToggle}
openModal={
dataId
? () => this.openModal(windowId, 'window', 'Advanced edit', true)
: undefined
}
handlePrint={
dataId
? () => this.handlePrint(windowId, dataId, docNoData.value)
: undefined
}
handleEmail={this.handleEmail}
handleComments={this.handleComments}
handleLetter={this.handleLetter}
handleDelete={dataId ? this.handleDelete : undefined}
handleClone={
dataId ? () => this.handleClone(windowId, dataId) : undefined
}
redirect={
windowId
? () => this.redirect(`/window/${windowId}/new`)
: undefined
}
handleDocStatusToggle={
document.getElementsByClassName('js-dropdown-toggler')[0]
? this.handleDocStatusToggle
: undefined
}
handleEditModeToggle={handleEditModeToggle}
closeOverlays={this.closeOverlays}
/>
</div>
);
}
}
/**
* @typedef {object} Props Component props
* @prop {*} activeTab
* @prop {*} breadcrumb
* @prop {string} dataId
* @prop {func} dispatch
* @prop {string} docId
* @prop {*} docSummaryData
* @prop {*} docNoData
* @prop {*} docStatus
* @prop {*} docStatusData
* @prop {*} dropzoneFocused
* @prop {*} editmode
* @prop {*} entity
* @prop {*} handleDeletedStatus
* @prop {*} handleEditModeToggle
* @prop {object} inbox
* @prop {bool} isDocumentNotSaved
* @prop {object} me
* @prop {*} notfound
* @prop {*} plugins
* @prop {*} query
* @prop {*} showSidelist
* @prop {*} showIndicator
* @prop {*} siteName
* @prop {*} windowId
*/
Header.propTypes = {
activeTab: PropTypes.any,
breadcrumb: PropTypes.any,
dataId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
docId: PropTypes.string,
docSummaryData: PropTypes.any,
docNoData: PropTypes.any,
docStatus: PropTypes.any,
docStatusData: PropTypes.any,
dropzoneFocused: PropTypes.any,
editmode: PropTypes.any,
entity: PropTypes.any,
handleDeletedStatus: PropTypes.any,
handleEditModeToggle: PropTypes.any,
inbox: PropTypes.object.isRequired,
isDocumentNotSaved: PropTypes.bool,
me: PropTypes.object.isRequired,
notfound: PropTypes.any,
plugins: PropTypes.any,
query: PropTypes.any,
showSidelist: PropTypes.any,
showIndicator: PropTypes.any,
siteName: PropTypes.any,
windowId: PropTypes.string,
};
/**
* @method mapStateToProps
* @summary ToDo: Describe the method
* @param {object} state
*/
const mapStateToProps = (state) => ({
inbox: state.appHandler.inbox,
me: state.appHandler.me,
pathname: state.routing.locationBeforeTransitions.pathname,
plugins: state.pluginsHandler.files,
});
export default connect(mapStateToProps)(Header);
|
src/page/spa/root/Root.hot.js | SteamerTeam/steamer-react | import { AppContainer } from 'react-hot-loader';
import React from 'react';
import { render } from 'react-dom';
import App from './Root.dev';
const rootEl = document.getElementById('pages');
render(
<AppContainer>
<App />
</AppContainer>,
rootEl
);
if (module.hot) {
module.hot.accept('./Root.dev', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./Root.dev').default;
render(
<AppContainer>
<NextApp />
</AppContainer>,
rootEl
);
});
} |
modules/experimental/AsyncProps.js | omerts/react-router | import React from 'react';
import invariant from 'invariant';
var { func, array, shape, object } = React.PropTypes;
var contextTypes = {
asyncProps: shape({
reloadComponent: func,
propsArray: array,
componentsArray: array
})
};
var _serverPropsArray = null;
function setServerPropsArray(array) {
invariant(!_serverPropsArray, 'You cannot call AsyncProps.hydrate more than once');
_serverPropsArray = array;
}
export function _clearCacheForTesting() {
_serverPropsArray = null;
}
function hydrate(routerState, cb) {
var { components, params } = routerState;
var flatComponents = filterAndFlattenComponents(components);
loadAsyncProps(flatComponents, params, cb);
}
function eachComponents(components, iterator) {
for (var i = 0, l = components.length; i < l; i++) {
if (typeof components[i] === 'object') {
for (var key in components[i]) {
iterator(components[i][key], i, key);
}
} else {
iterator(components[i], i);
}
}
}
function filterAndFlattenComponents(components) {
var flattened = [];
eachComponents(components, function(Component) {
if (Component.loadProps)
flattened.push(Component);
});
return flattened;
}
function loadAsyncProps(components, params, cb) {
var propsArray = [];
var componentsArray = [];
var canceled = false;
var needToLoadCounter = components.length;
components.forEach(function(Component, index) {
Component.loadProps(params, function(error, props) {
needToLoadCounter--;
propsArray[index] = props;
componentsArray[index] = Component;
maybeFinish();
});
});
function maybeFinish() {
if (canceled === false && needToLoadCounter === 0)
cb(null, {propsArray, componentsArray});
}
return {
cancel () {
canceled = true;
}
};
}
function getPropsForComponent(Component, componentsArray, propsArray) {
var index = componentsArray.indexOf(Component);
return propsArray[index];
}
function mergeAsyncProps(current, changes) {
for (var i = 0, l = changes.propsArray.length; i < l; i++) {
let Component = changes.componentsArray[i];
let position = current.componentsArray.indexOf(Component);
let isNew = position === -1;
if (isNew) {
current.propsArray.push(changes.propsArray[i]);
current.componentsArray.push(changes.componentsArray[i]);
} else {
current.propsArray[position] = changes.propsArray[i];
}
}
}
function arrayDiff(previous, next) {
var diff = [];
for (var i = 0, l = next.length; i < l; i++)
if (previous.indexOf(next[i]) === -1)
diff.push(next[i]);
return diff;
}
function shallowEqual(a, b) {
var key;
var ka = 0;
var kb = 0;
for (key in a) {
if (a.hasOwnProperty(key) && a[key] !== b[key])
return false;
ka++;
}
for (key in b)
if (b.hasOwnProperty(key))
kb++;
return ka === kb;
}
var RouteComponentWrapper = React.createClass({
contextTypes: contextTypes,
// this is here to meet the case of reloading the props when a component's params change,
// the place we know that is here, but the problem is we get occasional waterfall loads
// when clicking links quickly at the same route, AsyncProps doesn't know to load the next
// props until the previous finishes rendering.
//
// if we could tell that a component needs its props reloaded in AsyncProps instead of here
// (by the arrayDiff stuff in componentWillReceiveProps) then we wouldn't need this code at
// all, and we coudl get rid of the terrible forceUpdate hack as well. I'm just not sure
// right now if we can know to reload a pivot transition.
componentWillReceiveProps(nextProps, context) {
var paramsChanged = !shallowEqual(
this.props.routerState.routeParams,
nextProps.routerState.routeParams
);
if (paramsChanged) {
this.reloadProps(nextProps.routerState.routeParams);
}
},
reloadProps(params) {
this.context.asyncProps.reloadComponent(
this.props.Component,
params || this.props.routerState.routeParams,
this
);
},
render() {
var { Component, routerState } = this.props;
var { componentsArray, propsArray, loading } = this.context.asyncProps;
var asyncProps = getPropsForComponent(Component, componentsArray, propsArray);
return <Component {...routerState} {...asyncProps} loading={loading} reloadAsyncProps={this.reloadProps} />;
}
});
var AsyncProps = React.createClass({
statics: {
hydrate: hydrate,
rehydrate: setServerPropsArray,
createElement(Component, state) {
return typeof Component.loadProps === 'function' ?
<RouteComponentWrapper Component={Component} routerState={state}/> :
<Component {...state}/>;
}
},
childContextTypes: contextTypes,
getChildContext() {
return {
asyncProps: Object.assign({
reloadComponent: this.reloadComponent,
loading: this.state.previousProps !== null
}, this.state.asyncProps),
};
},
getInitialState() {
return {
asyncProps: {
propsArray: _serverPropsArray,
componentsArray: _serverPropsArray ? filterAndFlattenComponents(this.props.components) : null,
},
previousProps: null
};
},
componentDidMount() {
var initialLoad = this.state.asyncProps.propsArray === null;
if (initialLoad) {
hydrate(this.props, (err, asyncProps) => {
this.setState({ asyncProps });
});
}
},
componentWillReceiveProps(nextProps) {
var routerTransitioned = nextProps.location !== this.props.location;
if (!routerTransitioned)
return;
var oldComponents = this.props.components;
var newComponents = nextProps.components;
var components = arrayDiff(
filterAndFlattenComponents(oldComponents),
filterAndFlattenComponents(newComponents)
);
if (components.length === 0)
return;
this.loadAsyncProps(components, nextProps.params);
},
beforeLoad(cb) {
this.setState({
previousProps: this.props
}, cb);
},
afterLoad(err, asyncProps, cb) {
this.inflightLoader = null;
mergeAsyncProps(this.state.asyncProps, asyncProps);
this.setState({
previousProps: null,
asyncProps: this.state.asyncProps
}, cb);
},
loadAsyncProps(components, params, cb) {
if (this.inflightLoader) {
this.inflightLoader.cancel();
}
this.beforeLoad(() => {
this.inflightLoader = loadAsyncProps(components, params, (err, asyncProps) => {
this.afterLoad(err, asyncProps, cb);
});
});
},
reloadComponent(Component, params, instance) {
this.loadAsyncProps([Component], params, () => {
// gotta fix this hack ... change in context doesn't cause the
// RouteComponentWrappers to rerender (first one will because
// of cloneElement)
if (instance.isMounted())
instance.forceUpdate();
});
},
render() {
var { route } = this.props;
var { asyncProps, previousProps } = this.state;
var initialLoad = asyncProps.propsArray === null;
if (initialLoad)
return route.renderInitialLoad ? route.renderInitialLoad() : null;
else if (previousProps)
return React.cloneElement(previousProps.children, { loading: true });
else
return this.props.children;
}
});
export default AsyncProps;
|
src/containers/weather_list.js | riquet28/Weather_ReactRedux | import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
import GoogleMap from '../components/google_map';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(weather => weather.main.temp);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
const { lon, lat } = cityData.city.coord;
return (
<tr key={name}>
<td><GoogleMap lon={lon} lat={lat} /></td>
<td><Chart data={temps} color="orange" units="K" /></td>
<td><Chart data={pressures} color="green" units="hPa" /></td>
<td><Chart data={humidities} color="black" units="%" /></td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (K)</th>
<th>Pression (hPa)</th>
<th>Humidité (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
function mapStateToProp({ weather }) {
return { weather }; // { weather } === { weather: weather }
}
export default connect(mapStateToProp)(WeatherList);
|
ignite/DevScreens/ComponentExamplesScreen.js | TylerKirby/Phrontis | // An All Components Screen is a great way to dev and quick-test components
import React from 'react'
import { Platform, View, ScrollView, Text, Image, TouchableOpacity } from 'react-native'
import { Images } from './DevTheme'
import styles from './Styles/ComponentExamplesScreenStyles'
// Examples Render Engine
import ExamplesRegistry from '../../App/Services/ExamplesRegistry'
class ComponentExamplesScreen extends React.Component {
renderAndroidWarning () {
if (Platform.OS === 'android') {
return (
<Text style={styles.sectionText}>
Android only: Animations are slow? You are probably running the app in debug mode.
It will run more smoothly once your app will be built.
</Text>
)
}
return null
}
render () {
return (
<View style={[styles.container, styles.mainContainer]}>
<Image source={Images.background} style={styles.backgroundImage} resizeMode='stretch' />
<TouchableOpacity onPress={() => this.props.navigation.goBack()} style={{
position: 'absolute',
paddingTop: 30,
paddingHorizontal: 5,
zIndex: 10
}}>
<Image source={Images.backButton} />
</TouchableOpacity>
<ScrollView showsVerticalScrollIndicator={false} style={styles.container}>
<View style={{alignItems: 'center', paddingTop: 60}}>
<Image source={Images.components} style={styles.logo} />
<Text style={styles.titleText}>Components</Text>
</View>
<View style={styles.description}>
{this.renderAndroidWarning()}
<Text style={styles.sectionText}>
Sometimes called a 'Style Guide', or 'Pattern Library', Examples Screen is filled with usage examples
of fundamental components for a given application. Use this merge-friendly way for your team
to show/use/test components. Examples are registered inside each component's file for quick changes and usage identification.
</Text>
</View>
{ExamplesRegistry.renderComponentExamples()}
</ScrollView>
</View>
)
}
}
export default ComponentExamplesScreen
|
src/components/Router1.js | hong1012/FreePay | import React from 'react'
export default React.createClass({
render() {
return <div>Hello, React Router!</div>
}
})
|
src/app.js | menthena/project-a | import React from 'react';
import styles from './app.css';
export default ({children}) => {
return (
<div id="container">
{children}
</div>
);
}
|
packages/ringcentral-widgets/components/OfflineModeBadge/index.js | u9520107/ringcentral-js-widget | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Draggable from '../Draggable';
import Badge from '../Badge';
import i18n from './i18n';
import styles from './styles.scss';
export default function OfflineModeBadge({
className,
offline,
currentLocale,
showOfflineAlert,
}) {
if (offline) {
return (
<Draggable className={styles.root}>
<Badge
className={classnames(className, styles.badge)}
name={i18n.getString('offlineMode', currentLocale)}
onClick={showOfflineAlert}
>
{i18n.getString('offlineMode', currentLocale)}
</Badge>
</Draggable>
);
}
return null;
}
OfflineModeBadge.propTypes = {
offline: PropTypes.bool.isRequired,
showOfflineAlert: PropTypes.func.isRequired,
currentLocale: PropTypes.string.isRequired,
className: PropTypes.string,
};
OfflineModeBadge.defaultProps = {
className: null,
};
|
src/routes/account/Role/Search.js | pmg1989/dva-admin | import React from 'react'
import PropTypes from 'prop-types'
import { Form, Button, Row, Col, Icon } from 'antd'
const Search = ({
addPower,
onAdd,
}) => {
return (
<Row gutter={24}>
{addPower &&
<Col lg={24} md={24} sm={24} xs={24} style={{ marginBottom: 16, textAlign: 'right' }}>
<Button size="large" type="ghost" onClick={onAdd}><Icon type="plus-circle-o" />添加</Button>
</Col>}
</Row>
)
}
Search.propTypes = {
onAdd: PropTypes.func.isRequired,
addPower: PropTypes.bool.isRequired,
}
export default Form.create()(Search)
|
docs/app/Examples/elements/Button/Groups/ButtonExampleGroupIcon.js | clemensw/stardust | import React from 'react'
import { Button } from 'semantic-ui-react'
const ButtonExampleGroupIcon = () => (
<div>
<Button.Group>
<Button icon='align left' />
<Button icon='align center' />
<Button icon='align right' />
<Button icon='align justify' />
</Button.Group>
{' '}
<Button.Group>
<Button icon='bold' />
<Button icon='underline' />
<Button icon='text width' />
</Button.Group>
</div>
)
export default ButtonExampleGroupIcon
|
app/containers/App/index.js | codekiln/beetimer | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
static/src/containers/Authorize.js | cas-x/cas-server | /**
* @Author: BingWu Yang <detailyang>
* @Date: 2016-03-13T22:43:06+08:00
* @Email: [email protected]
* @Last modified by: detailyang
* @Last modified time: 2016-07-05T16:25:37+08:00
* @License: The MIT License (MIT)
*/
import { Icon, Button, Row, Col, message } from 'antd';
import url from 'url';
import querystring from 'querystring';
import React from 'react';
import { fetch } from '../utils';
export default React.createClass({
handleClick(e) {
e.preventDefault();
fetch('', { method: 'POST' })
.then((res) => {
location.href = res.value;
})
.catch((err, resp) => {
message.error(resp.data.value, 3);
});
},
render() {
const qs = querystring.parse(url.parse(location.href).query);
const name = qs.name || '';
const AvatarStyle = {
height: 100,
width: 100,
borderRadius: '50%',
};
const IconStyle = {
'fontSize': 16,
'marginRight': 16,
};
const CheckIconStyle = {
'fontSize': 16,
color: '#79d858',
};
const Style = {
'marginTop': 100,
};
const H1Style = {
'color': '#333',
};
const ButtonStyle = {
'marginTop': 25,
'marginBottom': 15,
};
const NameStyle = {
color: 'red',
};
return (
<Row type="flex" justify="center">
<Col className="box" span={12} style={Style} >
<Row style={{ 'borderBottom': '1px solid #ddd', marginBottom: 15 }}>
<Col span="18">
<h1 style={H1Style}>Authorize application</h1>
<p>
<strong style={NameStyle}>{name}</strong> would
like permission to access your account
</p>
</Col>
<Col span="6">
<img style={AvatarStyle} src="/api/users/self/avatar" alt="avatar" />
</Col>
</Row>
<Row>
<h1 style={H1Style}>
Review Permissions
</h1>
</Row>
<div style={{ border: '1px solid #ddd', padding: 25 }}>
<Row style={{ padding: 10 }}>
<Col span="10">
<Icon type="user" style={IconStyle} />
Read your personal user data
</Col>
<Col span="1" offset="11">
<Icon type="check" style={CheckIconStyle} />
</Col>
</Row>
<Row style={{ padding: 10 }}>
<Col span="10">
<Icon type="setting" style={IconStyle} />
Setting your personal user data
</Col>
<Col span="1" offset="11">
<Icon type="check" style={CheckIconStyle} />
</Col>
</Row>
</div>
<Row>
<Button onClick={this.handleClick} style={ButtonStyle} type="primary" size="large">
确认
</Button>
</Row>
</Col>
</Row>
);
},
});
|
app/pages/app/Tabbar/index.js | czy0729/react-alumni | /**
* Tabbar 导航条
* @Date: 2017-03-06 19:46:25
* @Last Modified by: Administrator
* @Last Modified time: 2017-03-31 08:12:10
*/
'use strict';
import React from 'react';
import classNames from 'classnames';
import { observer } from 'decorators';
import { $app } from 'stores';
import { TabBar, Icon } from 'antd-mobile';
import './index.less';
const prefixCls = 'pages-app__tabbar';
@observer
export default class AppTabbar extends React.Component {
constructor() {
super();
this.timeout = 0;
}
renderTabBarItem(props) {
const { location } = this.props;
const { pathname, title, icon, selectedIcon, ...other } = props;
return (
<TabBar.Item
key={pathname}
title={title}
icon={icon}
selectedIcon={selectedIcon || icon}
selected={location.pathname === pathname}
onPress={() => {
Utils.router.push(pathname);
if (pathname !== '_down') {
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = setTimeout(() => {
$app.hideTabbar();
this.timeout = 0;
}, 3000);
}
}}
{...other}
/>
);
}
render() {
return (
<div className={prefixCls}>
<TabBar
unselectedTintColor={Const.ui.color_default}
tintColor={Const.ui.color_primary}
hidden={!$app.state.tabbar.show}
>
{this.renderTabBarItem({
title: '新建',
icon: <Icon size="xxs" type={require('svg/file_default.svg')} />,
selectedIcon: <Icon size="xxs" type={require('svg/file.svg')} />,
pathname: Const.router.add_alumni(),
})}
{this.renderTabBarItem({
title: '校友录',
icon: <Icon size="xxs" type={require('svg/bag_default.svg')} />,
selectedIcon: <Icon size="xxs" type={require('svg/bag.svg')} />,
pathname: Const.router.user_alumni(),
})}
{this.renderTabBarItem({
title: '个人',
icon: <Icon size="xxs" type={require('svg/smile_default.svg')} />,
selectedIcon: <Icon size="xxs" type={require('svg/smile.svg')} />,
pathname: Const.router.user_center(),
})}
{this.renderTabBarItem({
title: '收起',
icon: <Icon size="xxs" type={require('svg/cross_default.svg')} />,
pathname: '_down',
onPress: () => $app.hideTabbar(),
})}
</TabBar>
<div
className={classNames({
[`${prefixCls}__btn-toggle`]: 1,
[`${prefixCls}__btn-toggle_active`]: !$app.state.tabbar.show,
})}
onClick={() => $app.showTabbar()}
>
<Icon size="xxs" type={require('common/svg/up.svg')} />
</div>
</div>
);
}
}; |
src/svg-icons/device/battery-alert.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBatteryAlert = (props) => (
<SvgIcon {...props}>
<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM13 18h-2v-2h2v2zm0-4h-2V9h2v5z"/>
</SvgIcon>
);
DeviceBatteryAlert = pure(DeviceBatteryAlert);
DeviceBatteryAlert.displayName = 'DeviceBatteryAlert';
export default DeviceBatteryAlert;
|
src/components/Ad/Ad.js | dontexpectanythingsensible/random-utils | import React from 'react';
export default class Ad extends React.Component {
componentDidMount () {
(window.adsbygoogle = window.adsbygoogle || []).push({});
}
render () {
return (
<div className='ad'>
<ins className='adsbygoogle'
style={ { display: 'block' } }
data-ad-client='ca-pub-3476090171072918'
data-ad-slot='4523218787'
data-ad-format='auto' />
</div>
);
}
}
|
app/javascript/mastodon/components/permalink.js | verniy6462/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class Permalink extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
className: PropTypes.string,
href: PropTypes.string.isRequired,
to: PropTypes.string.isRequired,
children: PropTypes.node,
};
handleClick = (e) => {
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(this.props.to);
}
}
render () {
const { href, children, className, ...other } = this.props;
return (
<a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}>
{children}
</a>
);
}
}
|
client/lib/createRootComponent.js | brewgauge/bg-frontend | 'use strict'
import React from 'react'
import {Provider} from 'react-redux'
import thunkMiddleware from 'redux-thunk'
import loggerMiddleware from 'redux-logger'
import {combineReducers, createStore, applyMiddleware} from 'redux'
import {browserHistory, Router, Route, IndexRoute} from 'react-router'
import {routerReducer, routerMiddleware, syncHistoryWithStore} from 'react-router-redux'
import authReducer from '../reducers/auth'
import sensorReducer from '../reducers/sensor'
import {logout, validateCookie} from '../actions/auth'
import Shell from '../containers/shell'
import Login from '../containers/login'
import Overview from '../containers/overview'
import Messages from '../containers/messages'
import Sensors from '../containers/sensors'
import ProcessById from '../containers/process_by_id'
import Profile from '../containers/profile'
const rootReducer = combineReducers({
routing: routerReducer,
auth: authReducer,
sensor: sensorReducer
})
const buildStore = applyMiddleware(
thunkMiddleware,
routerMiddleware(browserHistory)
//loggerMiddleware()
)(createStore)
const initalState = {
auth: {
hasError: false,
isLoggedIn: true
}
}
const store = buildStore(rootReducer, initalState)
const history = syncHistoryWithStore(browserHistory, store)
export default function createRootComponent () {
function requireAuth (nextState, replace, done) {
const isLoggedIn = store.getState().auth.isLoggedIn
if (!isLoggedIn) {
replace({nextPathname: nextState.location.pathname, pathname: '/login', query: nextState.location.query})
} else {
store.dispatch({type: 'AUTH_VALIDATED', isLoggedIn: true})
}
done()
}
function handleLogout () {
store.dispatch(logout())
}
return (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={Shell}>
<IndexRoute component={Sensors} onEnter={requireAuth}/>
<Route path="sensors" component={Sensors} onEnter={requireAuth}/>
<Route path="messages" component={Messages} onEnter={requireAuth}/>
<Route path="process/:id" component={ProcessById} onEnter={requireAuth}/>
<Route path="profile" component={Profile} onEnter={requireAuth}/>
<Route path="login" component={Login} />
<Route path="logout" onEnter={handleLogout} />
</Route>
</Router>
</Provider>
)
}
|
src/components/tos.js | pol-is/polisClientAdmin | import React from 'react';
import Radium from 'radium';
import _ from 'lodash';
import { doSignout } from '../actions';
import StaticContentContainer from "./framework/static-content-container";
const styles = {
card: {
position: "relative",
zIndex: 10,
padding: "50px",
borderRadius: 3,
color: "rgb(130,130,130)",
maxWidth: 700,
margin: 50
},
}
@Radium
class TOS extends React.Component {
render() {
return (
<StaticContentContainer
backgroundColor={"#03a9f4"}
headerBackgroundColor={"#03a9f4"}
footerBackgroundColor={"#03a9f4"}
image={false}>
<div style={styles.card}>
<p>"Last Updated: 6/26/2014"</p>
<p>"Po.lis Terms of Use"</p>
<p>"Welcome, and thank you for your interest in Polis Technology Inc ('Pol.is', 'we,'
or 'us') and our Web site at <a href='http://pol.is/'>http://pol.is/</a> (the
'Site'), as well as all related web sites, networks, embeddable widgets, downloadable
software, mobile applications (including tablet applications), and other services
provided by us and on which a link to these Terms of Use is displayed (collectively,
together with the Site, our 'Service'). These Terms of Use are a legally binding
contract between you and Pol.is regarding your use of the Service."</p>
<p>"PLEASE READ THE FOLLOWING TERMS OF USE CAREFULLY. BY CLICKING 'I ACCEPT,' YOU
ACKNOWLEDGE THAT YOU HAVE READ, UNDERSTOOD, AND AGREE TO BE BOUND BY THE FOLLOWING
TERMS AND CONDITIONS, INCLUDING THE POL.IS PRIVACY POLICY <a href=
'https://pol.is/privacy'>https://pol.is/privacy</a> (COLLECTIVELY, THESE 'TERMS'). If
you are not eligible, or do not agree to these Terms, then please do not use the
Service."</p>
<p>"These Terms of Use provide that all disputes between you and Pol.is will be
resolved by BINDING ARBITRATION. YOU AGREE TO GIVE UP YOUR RIGHT TO GO TO COURT to
assert or defend your rights under this contract (except for matters that may be
taken to small claims court). Your rights will be determined by a NEUTRAL ARBITRATOR
and NOT a judge or jury and your claims cannot be brought as a class action. Please
review the Arbitration Agreement below for the details regarding your agreement to
arbitrate any disputes with Pol.is."</p>
<ol>
<li>"Eligibility. You must be at least thirteen (13) years of age to use the
Service. By agreeing to these Terms, you represent and warrant to us: (i) that you
are at least thirteen (13) years of age; (ii) that you have not previously been
suspended or removed from the Service; and (iii) that your registration and your
use of the Service is in compliance with any and all applicable laws and
regulations. If you are using the Service on behalf of an entity, organization, or
company, you represent and warrant that you have the authority to bind such
organization to these Terms and you agree to be bound by these Terms on behalf of
such organization."</li>
<li>"Accounts and Registration. To access most features of the Service, you must
register for an account. When you register for an account, you may be required to
provide us with some information about yourself (such as your e-mail address or
other contact information). You agree that the information you provide to us is
accurate and that you will keep it accurate and up-to-date at all times. When you
register, you will be asked to provide a password. You are solely responsible for
maintaining the confidentiality of your account and password. You agree to accept
responsibility for all activities that occur under your account. If you have reason
to believe that your account is no longer secure, then you must immediately notify
us at [email protected]."</li>
<li>"Payment. Access to the Service, or to certain features of the Service, may
require you to pay fees. Before you are required to pay any fees, you will have an
opportunity to review and accept the applicable fees that you will be charged. All
fees are in U.S. Dollars and are non-refundable. Pol.is may change the fees for the
Service or any feature of the Service, including by adding additional fees or
charges, on a going-forward basis at any time. Pol.is will charge the payment
method you specify at the time of purchase. You authorize Pol.is to charge all sums
described herein to such payment method. If you pay any applicable fees with a
credit card, Pol.is may seek pre-authorization of your credit card account prior to
your purchase to verify that the credit card is valid and has the necessary funds
or credit available to cover your purchase."</li>
<li>User Content
<ol>
<li>"User Content Generally. Certain features of the Service may permit users
to post content, including messages, questions, responses, data, text, and
other types of works (collectively, 'User Content') and to publish User Content
on the Service. You retain copyright and any other proprietary rights that you
may hold in the User Content that you post to the Service."</li>
<li>"Limited License Grant to Pol.is. By posting or publishing User Content,
you grant Pol.is a worldwide, non-exclusive, royalty-free right and license
(with the right to sublicense) to host, store, transfer, display, perform,
reproduce, modify, and distribute your User Content, in whole or in part, in
any media formats and through any media channels (now known or hereafter
developed). Any such use of your User Content by Pol.is may be without any
compensation paid to you."</li>
<li>"Limited License Grant to Other Users. By posting User Content or sharing
User Content with another user of the Service, you hereby grant to other users
of the Service a non-exclusive license to access and use such User Content as
permitted by these Terms and the functionality of the Service."</li>
<li>"User Content Representations and Warranties. You are solely responsible
for your User Content and the consequences of posting or publishing User
Content. By posting and publishing User Content, you affirm, represent, and
warrant that:"</li>
</ol>
</li>
<li>"you are the creator and owner of, or have the necessary licenses, rights,
consents, and permissions to use and to authorize Pol.is and users of the Service
to use and distribute your User Content as necessary to exercise the licenses
granted by you in this Section 4 and in the manner contemplated by Pol.is and these
Terms; and "</li>
<li>"your User Content, and the use thereof as contemplated herein, does not and
will not: (i) infringe, violate, or misappropriate any third-party right, including
any copyright, trademark, patent, trade secret, moral right, privacy right, right
of publicity, or any other intellectual property or proprietary right; or (ii)
slander, defame, libel, or invade the right of privacy, publicity or other property
rights of any other person."
<ol>
<li>"User Content Disclaimer. We are under no obligation to edit or control
User Content that you or other users post or publish, and will not be in any
way responsible or liable for User Content. Pol.is may, however, at any time
and without prior notice, screen, remove, edit, or block any User Content that
in our sole judgment violates these Terms or is otherwise objectionable. You
understand that when using the Service you will be exposed to User Content from
a variety of sources and acknowledge that User Content may be inaccurate,
offensive, indecent or objectionable. You agree to waive, and hereby do waive,
any legal or equitable rights or remedies you have or may have against Pol.is
with respect to User Content. We expressly disclaim any and all liability in
connection with User Content. If notified by a user or content owner that User
Content allegedly does not conform to these Terms, we may investigate the
allegation and determine in our sole discretion whether to remove the User
Content, which we reserve the right to do at any time and without notice. For
clarity, Pol.is does not permit copyright-infringing activities on the
Service."</li>
</ol>
</li>
<li>"Prohibited Conduct. BY USING THE SERVICE YOU AGREE NOT TO:"
<ol>
<li>"use the Service for any illegal purpose, or in violation of any local,
state, national, or international law;"</li>
<li>"violate, or encourage others to violate, the rights of third parties,
including by infringing or misappropriating third party intellectual property
rights;"</li>
<li>"post, upload, or distribute any User Content or other content that is
unlawful, defamatory, libelous, inaccurate, or that a reasonable person could
deem to be objectionable, profane, indecent, pornographic, harassing,
threatening, embarrassing, hateful, or otherwise inappropriate;"</li>
<li>"interfere with security-related features of the Service, including without
limitation by (i) disabling or circumventing features that prevent or limit use
or copying of any content, or (ii) reverse engineering or otherwise attempting
to discover the source code of the Service or any part thereof except to the
extent that such activity is expressly permitted by applicable law; "</li>
<li>"interfere with the operation of the Service or any user's enjoyment of the
Service, including without limitation by (i) uploading or otherwise
disseminating viruses, adware, spyware, worms, or other malicious code, (ii)
making unsolicited offers or advertisements to other users of the Service,
(iii) attempting to collect, personal information about users or third parties
without their consent; or (iv) interfering with or disrupting any networks,
equipment, or servers connected to or used to provide the Service, or violating
the regulations, policies, or procedures of such networks, equipment, or
servers;"</li>
<li>"perform any fraudulent activity including impersonating any person or
entity, claiming false affiliations, accessing the Service accounts of others
without permission, or falsifying your age or date of birth; "</li>
<li>"sell or otherwise transfer the access granted herein or any Materials (as
defined in Section 10 below) or any right or ability to view, access, or use
any Materials; or"</li>
<li>"attempt to do any of the foregoing in this Section 5, or assist or permit
any persons in engaging in any of the activities described in this Section
5."</li>
</ol>
</li>
<li>"Third-Party Services and Linked Websites. Pol.is may provide tools through the
Service that enable you to export information, including User Content, to third
party services such as Twitter or Facebook or to web sites. By using these tools,
you agree that we may transfer such information to the applicable third-party
service or web site. Such third party services and web sites are not under our
control, and we are not responsible for their use of your exported information. The
Service may also contain links to third-party websites. Such linked websites are
not under our control, and we are not responsible for their content."</li>
<li>"Termination of Use; Discontinuation and Modification of the Service. If you
violate any provision of these Terms, your permission to use the Service will
terminate automatically. Additionally, Pol.is, in its sole discretion may terminate
your user account on the Service or suspend or terminate your access to the Service
at any time, with or without notice. We also reserve the right to modify or
discontinue the Service at any time (including, without limitation, by limiting or
discontinuing certain features of the Service) without notice to you. We will have
no liability whatsoever on account of any change to the Service or any suspension
or termination of your access to or use of the Service. You may terminate your
account at any time by contacting customer service at [email protected]. If you terminate
your account, you will remain obligated to pay all outstanding fees, if any,
relating to your use of the Service incurred prior to termination. To the extent
permitted by applicable laws and regulations, no unused portions of pre-paid fees
will be refunded following termination."</li>
<li>"Privacy Policy; Additional Terms"
<ol>
<li>"Privacy Policy. Please read the Pol.is Privacy Policy [<a href=
'https://pol.is/privacy'>https://pol.is/privacy</a>] carefully for information
relating to our collection, use, storage and disclosure of your personal
information. The Pol.is Privacy Policy is hereby incorporated by reference
into, and made a part of, these Terms."</li>
<li>"Additional Terms. Your use of the Service is subject to any and all
additional terms, policies, rules, or guidelines applicable to the Service or
certain features of the Service that we may post on or link to on the Service
(the 'Additional Terms'), such as end-user license agreements for any
downloadable applications that we may offer, or rules applicable to particular
features or content on the Service, subject to Section 9 below. All such
Additional Terms are hereby incorporated by reference into, and made a part of,
these Terms."</li>
</ol>
</li>
<li>"Modification of these Terms. We reserve the right, at our discretion, to
change these Terms on a going-forward basis at any time. Please check these Terms
periodically for changes. In the event that a change to these Terms materially
modifies your rights or obligations, you will be required to accept such modified
terms in order to continue to use the Service. Material modifications are effective
upon your acceptance of such the modified Terms. Immaterial modifications are
effective upon publication. For the avoidance of doubt, disputes arising under
these Terms will be resolved in accordance with these Terms in effect that the time
the dispute arose."</li>
<li>"Ownership; Proprietary Rights. The Service is owned and operated by Pol.is.
The visual interfaces, application programming interfaces, graphics, design,
compilation, information, data, computer code (including source code or object
code), products, software, services, and all other elements of the Service (the
'Materials') provided by Pol.is are protected by all relevant intellectual property
and proprietary rights and applicable laws. All Materials contained in the Service
are the property of Pol.is or our third-party licensors. Except as expressly
authorized by Pol.is, you may not make use of the Materials. Pol.is reserves all
rights to the Materials not granted expressly in these Terms."</li>
<li>"Indemnity. You agree that you will be responsible for your use of the Service,
and you agree to defend, indemnify, and hold harmless Pol.is and its officers,
directors, employees, consultants, affiliates, subsidiaries and agents
(collectively, the Pol.is Entities') from and against any and all claims,
liabilities, damages, losses, and expenses, including reasonable attorneys' fees
and costs, arising out of or in any way connected with (i) your access to, use of,
or alleged use of the Service; (ii) your violation of these Terms or any
representation, warranty, or agreements referenced herein, or any applicable law or
regulation; (iii) your violation of any third-party right, including without
limitation any intellectual property right, publicity, confidentiality, property or
privacy right; or (iv) any disputes or issues between you and any third party. We
reserve the right, at our own expense, to assume the exclusive defense and control
of any matter otherwise subject to indemnification by you (and without limiting
your indemnification obligations with respect to such matter), and in such case,
you agree to cooperate with our defense of such claim."</li>
<li>"Disclaimers; No Warranties THE SERVICE AND ALL MATERIALS AND CONTENT AVAILABLE
THROUGH THE SERVICE ARE PROVIDED 'AS IS' AND ON AN 'AS AVAILABLE' BASIS, WITHOUT
WARRANTY OR CONDITION OF ANY KIND, EITHER EXPRESS OR IMPLIED. THE POL.IS ENTITIES
SPECIFICALLY (BUT WITHOUT LIMITATION) DISCLAIM ALL WARRANTIES OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, RELATING TO THE SERVICE AND ALL MATERIALS AND CONTENT AVAILABLE
THROUGH THE SERVICE, INCLUDING BUT NOT LIMITED TO (i) ANY IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, QUIET ENJOYMENT, OR
NON-INFRINGEMENT; AND (ii) ANY WARRANTIES ARISING OUT OF COURSE OF DEALING, USAGE,
OR TRADE. THE POL.IS ENTITIES DO NOT WARRANT THAT THE SERVICE OR ANY PART THEREOF,
OR ANY MATERIALS OR CONTENT OFFERED THROUGH THE SERVICE, WILL BE UNINTERRUPTED,
SECURE, OR FREE OF ERRORS, VIRUSES, OR OTHER HARMFUL COMPONENTS, AND DO NOT WARRANT
THAT ANY OF THE FOREGOING WILL BE CORRECTED."</li>
</ol>
<p>"NO ADVICE OR INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM THE
SERVICE OR ANY MATERIALS OR CONTENT AVAILABLE ON OR THROUGH THE SERVICE WILL CREATE
ANY WARRANTY REGARDING ANY OF THE POL.IS ENTITIES OR THE SERVICE THAT IS NOT
EXPRESSLY STATED IN THESE TERMS. YOU ASSUME ALL RISK FOR ALL DAMAGES THAT MAY RESULT
FROM YOUR USE OF OR ACCESS TO THE SERVICE, YOUR DEALINGS WITH OTHER SERVICE USERS,
AND ANY MATERIALS OR CONTENT AVAILABLE THROUGH THE SERVICE. YOU UNDERSTAND AND AGREE
THAT YOU USE THE SERVICE AND USE, ACCESS, DOWNLOAD, OR OTHERWISE OBTAIN MATERIALS OR
CONTENT THROUGH THE SERVICE AND ANY ASSOCIATED SITES OR SERVICES AT YOUR OWN
DISCRETION AND RISK, AND YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR
PROPERTY (INCLUDING YOUR COMPUTER SYSTEM USED IN CONNECTION WITH THE SERVICE) OR LOSS
OF DATA THAT RESULTS FROM THE USE OF THE SERVICE OR THE DOWNLOAD OR USE OF SUCH
MATERIALS OR CONTENT.<br />
SOME JURISDICTIONS MAY PROHIBIT A DISCLAIMER OF WARRANTIES AND YOU MAY HAVE OTHER
RIGHTS THAT VARY FROM JURISDICTION TO JURISDICTION."</p>
<ol>
<li>"Limitation of Liability: IN NO EVENT WILL THE POL.IS ENTITIES BE LIABLE TO YOU
FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL OR PUNITIVE DAMAGES
(INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA,
OR OTHER INTANGIBLE LOSSES) ARISING OUT OF OR RELATING TO YOUR ACCESS TO OR USE OF,
OR YOUR INABILITY TO ACCESS OR USE, THE SERVICE OR ANY MATERIALS OR CONTENT ON THE
SERVICE, WHETHER BASED ON WARRANTY, CONTRACT, TORT (INCLUDING NEGLIGENCE), STATUTE
OR ANY OTHER LEGAL THEORY, WHETHER OR NOT THE POL.IS ENTITIES HAVE BEEN INFORMED OF
THE POSSIBILITY OF SUCH DAMAGE. YOU AGREE THAT THE AGGREGATE LIABILITY OF THE
POL.IS ENTITIES TO YOU FOR ANY AND ALL CLAIMS ARISING OUT OF RELATING TO THE USE OF
OR ANY INABILITY TO USE THE SERVICE (INCLUDING ANY MATERIALS OR CONTENT AVAILABLE
THROUGH THE SERVICE) OR OTHERWISE UNDER THESE TERMS, WHETHER IN CONTRACT, TORT, OR
OTHERWISE, IS LIMITED TO THE GREATER OF (i) THE AMOUNTS YOU HAVE PAID TO POL.IS FOR
ACCESS TO AND USE OF THE SERVICE IN THE 12 MONTHS PRIOR TO THE CLAIM OR (ii) $100.
SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR
CONSEQUENTIAL OR INCIDENTAL DAMAGES. ACCORDINGLY, THE ABOVE LIMITATION MAY NOT
APPLY TO YOU. EACH PROVISION OF THESE TERMS THAT PROVIDES FOR A LIMITATION OF
LIABILITY, DISCLAIMER OF WARRANTIES, OR EXCLUSION OF DAMAGES IS TO ALLOCATE THE
RISKS UNDER THESE TERMS BETWEEN THE PARTIES. THIS ALLOCATION IS AN ESSENTIAL
ELEMENT OF THE BASIS OF THE BARGAIN BETWEEN THE PARTIES. EACH OF THESE PROVISIONS
IS SEVERABLE AND INDEPENDENT OF ALL OTHER PROVISIONS OF THESE TERMS. THE
LIMITATIONS IN THIS SECTION 13 WILL APPLY EVEN IF ANY LIMITED REMEDY FAILS OF ITS
ESSENTIAL PURPOSE."</li>
<li>"Governing Law. These Terms shall be governed by the laws of the State of
Washington without regard to conflict of law principles. To the extent that any
lawsuit or court proceeding is permitted hereunder, you and Pol.is agree to submit
to the personal and exclusive jurisdiction of the state courts and federal courts
located within King County, Washington for the purpose of litigating all such
disputes. We operate the Service from our offices in Washington, and we make no
representation that Materials included in the Service are appropriate or available
for use in other locations."</li>
<li>"General. These Terms, together with the Privacy Policy and any other
agreements expressly incorporated by reference herein, constitute the entire and
exclusive understanding and agreement between you and Pol.is regarding your use of
and access to the Service, and except as expressly permitted above may be amended
only by a written agreement signed by authorized representatives of all parties to
these Terms. You may not assign or transfer these Terms or your rights hereunder,
in whole or in part, by operation of law or otherwise, without our prior written
consent. We may assign these Terms at any time without notice. The failure to
require performance of any provision will not affect our right to require
performance at any time thereafter, nor shall a waiver of any breach or default of
these Terms or any provision of these Terms constitute a waiver of any subsequent
breach or default or a waiver of the provision itself. Use of section headers in
these Terms is for convenience only and shall not have any impact on the
interpretation of particular provisions. In the event that any part of these Terms
is held to be invalid or unenforceable, the unenforceable part shall be given
effect to the greatest extent possible and the remaining parts will remain in full
force and effect. Upon termination of these Terms, any provision that by its nature
or express terms should survive will survive such termination or expiration,
including, but not limited to, Sections 1, 3, and Error! Reference source not
found. through 17."</li>
<li>"Dispute Resolution and Arbitration"
<ol>
<li>"Generally. In the interest of resolving disputes between you and Pol.is in
the most expedient and cost effective manner, you and Pol.is agree that any and
all disputes arising in connection with these Terms shall be resolved by
binding arbitration. Arbitration is more informal than a lawsuit in court.
Arbitration uses a neutral arbitrator instead of a judge or jury, may allow for
more limited discovery than in court, and can be subject to very limited review
by courts. Arbitrators can award the same damages and relief that a court can
award. Our agreement to arbitrate disputes includes, but is not limited to all
claims arising out of or relating to any aspect of these Terms, whether based
in contract, tort, statute, fraud, misrepresentation or any other legal theory,
and regardless of whether the claims arise during or after the termination of
these Terms. YOU UNDERSTAND AND AGREE THAT, BY ENTERING INTO THESE TERMS, YOU
AND POL.IS ARE EACH WAIVING THE RIGHT TO A TRIAL BY JURY OR TO PARTICIPATE IN A
CLASS ACTION."</li>
<li>"Exceptions. Notwithstanding subsection 16.1, we both agree that nothing
herein will be deemed to waive, preclude, or otherwise limit either of our
right to (i) bring an individual action in small claims court, (ii) pursue
enforcement actions through applicable federal, state, or local agencies where
such actions are available, (iii) seek injunctive relief in a court of law, or
(iv) to file suit in a court of law to address intellectual property
infringement claims."</li>
<li>"Arbitrator. Any arbitration between you and Pol.is will be governed by the
Commercial Dispute Resolution Procedures and the Supplementary Procedures for
Consumer Related Disputes (collectively, 'AAA Rules') of the American
Arbitration Association ('AAA'), as modified by these Terms, and will be
administered by the AAA. The AAA Rules and filing forms are available online at
www.adr.org, by calling the AAA at 1-800-778-7879, or by contacting
Pol.is."</li>
<li>"Notice; Process. A party who intends to seek arbitration must first send a
written notice of the dispute to the other, by certified mail or Federal
Express (signature required), or in the event that we do not have a physical
address on file for you, by electronic mail ('Notice'). The address of Pol.is
for Notice is: Polis Technology Inc 3601 Fremont Ave. N, Suite 300 Seattle, WA
98103. The Notice must (i) describe the nature and basis of the claim or
dispute; and (ii) set forth the specific relief sought ('Demand'). We agree to
use good faith efforts to resolve the claim directly, but if we do not reach an
agreement to do so within 30 days after the Notice is received, you or Pol.is
may commence an arbitration proceeding. During the arbitration, the amount of
any settlement offer made by you or Pol.is shall not be disclosed to the
arbitrator until after the arbitrator makes a final decision and award, if any.
In the event our dispute is finally resolved through arbitration in your favor,
Pol.is shall pay you (i) the amount awarded by the arbitrator, if any, (ii) the
last written settlement amount offered by Pol.is in settlement of the dispute
prior to the arbitrator's award; or (iii) $1,000.00, whichever is
greater."</li>
<li>"Fees. In the event that you commence arbitration in accordance with these
Terms, Pol.is will reimburse you for your payment of the filing fee, unless
your claim is for greater than $10,000, in which case the payment of any fees
shall be decided by the AAA Rules. Any arbitration hearings will take place at
a location to be agreed upon in King County, Washington, provided that if the
claim is for $10,000 or less, you may choose whether the arbitration will be
conducted (i) solely on the basis of documents submitted to the arbitrator;
(ii) through a non-appearance based telephonic hearing; or (iii) by an
in-person hearing as established by the AAA Rules in the county (or parish) of
your billing address. If the arbitrator finds that either the substance of your
claim or the relief sought in the Demand is frivolous or brought for an
improper purpose (as measured by the standards set forth in Federal Rule of
Civil Procedure 11(b)), then the payment of all fees will be governed by the
AAA Rules. In such case, you agree to reimburse Pol.is for all monies
previously disbursed by it that are otherwise your obligation to pay under the
AAA Rules. Regardless of the manner in which the arbitration is conducted, the
arbitrator shall issue a reasoned written decision sufficient to explain the
essential findings and conclusions on which the decision and award, if any, are
based. The arbitrator may make rulings and resolve disputes as to the payment
and reimbursement of fees or expenses at any time during the proceeding and
upon request from either party made within 14 days of the arbitrator's ruling
on the merits."</li>
<li>"No Class Actions. YOU AND POL.IS AGREE THAT EACH MAY BRING CLAIMS AGAINST
THE OTHER ONLY IN YOUR OR ITS INDIVIDUAL CAPACITY AND NOT AS A PLAINTIFF OR
CLASS MEMBER IN ANY PURPORTED CLASS OR REPRESENTATIVE PROCEEDING. Further,
unless both you and Pol.is agree otherwise, the arbitrator may not consolidate
more than one person's claims, and may not otherwise preside over any form of a
representative or class proceeding."</li>
<li>"Modifications. In the event that Pol.is makes any future change to this
arbitration provision (other than a change to the address of Pol.is for
Notice), you may reject any such change by sending us written notice within 30
days of the change to the address of Pol.is for Notice, in which case your
account with Pol.is shall be immediately terminated and this arbitration
provision, as in effect immediately prior to the amendments you reject shall
survive."</li>
<li>"Enforceability. If Subsection 16.6 is found to be unenforceable or if the
entirety of this Section 16 is found to be unenforceable, then the entirety of
this Section 16 shall be null and void and, in such case, the parties agree
that the exclusive jurisdiction and venue described in Section 14 shall govern
any action arising out of or related to these Terms."</li>
</ol>
</li>
<li>"Consent to Electronic Communications. By using the Service, you consent to
receiving certain electronic communications from us as further described in our
Privacy Policy. Please read our Privacy Policy to learn more about your choices
regarding our electronic communications practices. You agree that any notices,
agreements, disclosures, or other communications that we send to you electronically
will satisfy any legal communication requirements, including that such
communications be in writing. "</li>
<li>"Contact Information. The services hereunder are offered by Polis Technology
Inc located at 3601 Fremont Ave. N, Suite 300 Seattle, WA 98103. You may contact us
by sending correspondence to the foregoing address or by emailing us at
[email protected]. If you are a California resident, you may have these Terms mailed to
you electronically by sending a letter to the foregoing address with your
electronic mail address and a request for these Terms."</li>
</ol>
</div>
</StaticContentContainer>
);
}
}
export default TOS;
|
app/javascript/flavours/glitch/features/picture_in_picture/components/header.js | Kirishima21/mastodon | import React from 'react';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from 'flavours/glitch/components/icon_button';
import { Link } from 'react-router-dom';
import Avatar from 'flavours/glitch/components/avatar';
import DisplayName from 'flavours/glitch/components/display_name';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
});
const mapStateToProps = (state, { accountId }) => ({
account: state.getIn(['accounts', accountId]),
});
export default @connect(mapStateToProps)
@injectIntl
class Header extends ImmutablePureComponent {
static propTypes = {
accountId: PropTypes.string.isRequired,
statusId: PropTypes.string.isRequired,
account: ImmutablePropTypes.map.isRequired,
onClose: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
render () {
const { account, statusId, onClose, intl } = this.props;
return (
<div className='picture-in-picture__header'>
<Link to={`/@${account.get('acct')}/${statusId}`} className='picture-in-picture__header__account'>
<Avatar account={account} size={36} />
<DisplayName account={account} />
</Link>
<IconButton icon='times' onClick={onClose} title={intl.formatMessage(messages.close)} />
</div>
);
}
}
|
src/components/blocks/BlockSocial.js | m0sk1t/react_email_editor | import React from 'react';
const BlockSocial = ({ blockOptions }) => {
const imgLocation = '/';
return (
<table
width="550"
cellPadding="0"
cellSpacing="0"
role="presentation"
>
<tbody>
<tr>
<td
width="550"
style={blockOptions.elements[0]}
>
<a
target="_blank"
href={blockOptions.elements[0].ok_link}
title={blockOptions.elements[0].ok_link}
style={{
"display": blockOptions.elements[0].ok_display
}}
>
<img alt="OK link" src={`${imgLocation}${blockOptions.elements[0].ok_source}`} />
</a>
<a
target="_blank"
href={blockOptions.elements[0].vk_link}
title={blockOptions.elements[0].vk_link}
style={{
"display": blockOptions.elements[0].vk_display
}}
>
<img alt="VK link" src={`${imgLocation}${blockOptions.elements[0].vk_source}`} />
</a>
<a
target="_blank"
href={blockOptions.elements[0].youtube_link}
title={blockOptions.elements[0].youtube_link}
style={{
"display": blockOptions.elements[0].youtube_display
}}
>
<img alt="Facebook link" src={`${imgLocation}${blockOptions.elements[0].youtube_source}`} />
</a>
<a
target="_blank"
href={blockOptions.elements[0].facebook_link}
title={blockOptions.elements[0].facebook_link}
style={{
"display": blockOptions.elements[0].facebook_display
}}
>
<img alt="Youtube link" src={`${imgLocation}${blockOptions.elements[0].facebook_source}`} />
</a>
</td>
</tr>
</tbody>
</table>
);
};
export default BlockSocial;
|
src/js/components/Box/stories/OnClick.js | HewlettPackard/grommet | import React from 'react';
import { Attraction } from 'grommet-icons';
import { Grommet, Box, Text } from 'grommet';
import { grommet } from '../../../themes';
export const OnClickBox = () => (
<Grommet theme={grommet}>
<Box justify="center" align="center" pad="large">
{/* eslint-disable no-alert */}
<Box
border
pad="large"
align="center"
round
gap="small"
hoverIndicator={{
background: {
color: 'background-contrast',
},
elevation: 'medium',
}}
onClick={() => {
alert('clicked');
}}
>
<Attraction size="large" />
<Text>Party</Text>
</Box>
</Box>
</Grommet>
);
OnClickBox.storyName = 'onClick';
export default {
title: 'Layout/Box/onClick',
};
|
static/src/routes.js | PMA-2020/pma-translation-hub | /* eslint new-cap: 0 */
import React from 'react';
import { Route } from 'react-router';
/* containers */
import { App } from './containers/App';
import { HomeContainer } from './containers/HomeContainer';
import LoginView from './components/LoginView';
import RegisterView from './components/RegisterView';
import ProtectedView from './components/ProtectedView';
import Analytics from './components/Analytics';
import NotFound from './components/NotFound';
import { DetermineAuth } from './components/DetermineAuth';
import { requireAuthentication } from './components/AuthenticatedComponent';
import { requireNoAuthentication } from './components/notAuthenticatedComponent';
export default (
<Route path="/" component={App}>
<Route path="main" component={requireAuthentication(ProtectedView)} />
<Route path="login" component={requireNoAuthentication(LoginView)} />
<Route path="register" component={requireNoAuthentication(RegisterView)} />
<Route path="home" component={requireNoAuthentication(HomeContainer)} />
<Route path="analytics" component={requireAuthentication(Analytics)} />
<Route path="*" component={DetermineAuth(NotFound)} />
</Route>
);
|
src/containers/Asians/TabControls/BreakTeams/ViewBreaks/index.js | westoncolemanl/tabbr-web | import React from 'react'
import { connect } from 'react-redux'
import withStyles from 'material-ui/styles/withStyles'
import Card, {
CardContent,
CardActions
} from 'material-ui/Card'
import Button from 'material-ui/Button'
import Table, {
TableBody,
TableCell,
TableHead,
TableRow
} from 'material-ui/Table'
import BreakCategoryMatrix from 'containers/Asians/_components/BreakCategoryMatrix'
import onCancel from './onCancel'
const styles = theme => ({
body: {
marginTop: theme.spacing.unit * 2
}
})
export default connect(mapStateToProps)(withStyles(styles)(({
dispatch,
breakTeams,
breakCategory,
teamsById,
institutionsById,
classes,
breakRoundsById,
breakRooms
}) => {
const filterBreakTeams = breakTeamToMatch => breakTeamToMatch.breakCategory === breakCategory._id
const breakTeamsThisBreakCategory = breakTeams.filter(filterBreakTeams)
const filterBreakRooms = breakRoomToMatch => breakRoundsById[breakRoomToMatch.breakRound].breakCategory === breakCategory._id
const breakRoomsThisRound = breakRooms.filter(filterBreakRooms)
breakTeamsThisBreakCategory.sort((a, b) => a.rank - b.rank)
return (
<div>
<BreakCategoryMatrix
breakCategory={breakCategory}
/>
<Card
className={classes.body}
>
<CardContent>
<Table>
<TableHead>
<TableRow>
<TableCell>
{'Rank'}
</TableCell>
<TableCell>
{'Name'}
</TableCell>
<TableCell>
{'Institution'}
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{breakTeamsThisBreakCategory.map(breakTeam =>
<TableRow
key={breakTeam._id}
>
<TableCell>
{breakTeam.rank}
</TableCell>
<TableCell>
{teamsById[breakTeam.team].name}
</TableCell>
<TableCell>
{institutionsById[teamsById[breakTeam.team].institution].name}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
<CardActions
className={'flex flex-row justify-end'}
>
<Button
children={'CANCEL BREAKS'}
color={'secondary'}
disabled={breakRoomsThisRound.length > 0}
onClick={() => onCancel(
dispatch,
breakCategory
)}
/>
</CardActions>
</Card>
</div>
)
}))
function mapStateToProps (state, ownProps) {
return {
breakRooms: Object.values(state.breakRooms.data),
breakTeams: Object.values(state.breakTeams.data),
breakRoundsById: state.breakRounds.data,
teamsById: state.teams.data,
institutionsById: state.institutions.data
}
}
|
test/integration/client-navigation/pages/dynamic/[slug]/route.js | azukaru/next.js | import React from 'react'
export default class DynamicRoute extends React.Component {
static async getInitialProps({ query = { slug: 'default' } }) {
return {
query,
}
}
render() {
return <p id="dynamic-page">{this.props.query.slug}</p>
}
}
|
classic/src/scenes/mailboxes/src/Scenes/AppScene/ServiceTab/CoreServiceWebView/ServiceSearch.js | wavebox/waveboxapp | import PropTypes from 'prop-types'
import React from 'react'
import { Paper, TextField, IconButton } from '@material-ui/core'
import { accountStore, accountActions } from 'stores/account'
import shallowCompare from 'react-addons-shallow-compare'
import { WB_WINDOW_FIND_START } from 'shared/ipcEvents'
import { ipcRenderer } from 'electron'
import { withStyles } from '@material-ui/core/styles'
import classNames from 'classnames'
import grey from '@material-ui/core/colors/grey'
import CloseIcon from '@material-ui/icons/Close'
import SearchIcon from '@material-ui/icons/Search'
const SEARCH_HEIGHT = 48
const styles = {
container: {
display: 'flex',
alignItems: 'center',
position: 'absolute',
bottom: -SEARCH_HEIGHT - 5,
left: 0,
minWidth: 300,
height: SEARCH_HEIGHT,
backgroundColor: 'white',
transition: 'none !important',
zIndex: 10,
overflow: 'hidden',
'&.active': {
bottom: 0
}
},
icon: {
bottom: -7,
color: grey[600],
zIndex: 1
},
input: {
marginLeft: 15,
width: 200
}
}
@withStyles(styles)
class ServiceSearch extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
mailboxId: PropTypes.string.isRequired,
serviceId: PropTypes.string.isRequired
}
/* **************************************************************************/
// Lifecycle
/* **************************************************************************/
constructor (props) {
super(props)
this.inputRef = null
}
/* **************************************************************************/
// Component Lifecycle
/* **************************************************************************/
componentDidMount () {
accountStore.listen(this.accountChanged)
ipcRenderer.on(WB_WINDOW_FIND_START, this.handleIPCSearchStart)
}
componentWillUnmount () {
accountStore.unlisten(this.accountChanged)
ipcRenderer.removeListener(WB_WINDOW_FIND_START, this.handleIPCSearchStart)
}
componentWillReceiveProps (nextProps) {
if (this.props.mailboxId !== nextProps.mailboxId || this.props.serviceId !== nextProps.serviceId) {
this.setState(this.generateState(nextProps))
}
}
/* **************************************************************************/
// Data lifecycle
/* **************************************************************************/
state = this.generateState(this.props)
/**
* Generates the state from the given props
* @param props: the props to use
* @return state object
*/
generateState ({ mailboxId, serviceId }) {
const accountState = accountStore.getState()
return {
isActive: accountState.activeServiceId() === serviceId,
isSearching: accountState.isSearchingService(serviceId),
searchTerm: accountState.serviceSearchTerm(serviceId)
}
}
accountChanged = (accountState) => {
const { serviceId } = this.props
this.setState({
isActive: accountState.activeServiceId() === serviceId,
isSearching: accountState.isSearchingService(serviceId),
searchTerm: accountState.serviceSearchTerm(serviceId)
})
}
/* **************************************************************************/
// Events
/* **************************************************************************/
/**
* Handles the input string changing
*/
handleChange = (evt) => {
accountActions.setServiceSearchTerm(this.props.serviceId, evt.target.value)
}
/**
* Handles the find next command
*/
handleFindNext = () => {
accountActions.searchServiceNextTerm(this.props.serviceId)
}
/**
* Handles the search stopping
*/
handleStopSearch = () => {
accountActions.stopSearchingService(this.props.serviceId)
}
/**
* Handles a key being pressed
* @param evt: the event that fired
*/
handleKeyPress = (evt) => {
if (evt.keyCode === 13) {
evt.preventDefault()
this.handleFindNext()
} else if (evt.keyCode === 27) {
evt.preventDefault()
this.handleStopSearch()
}
}
/**
* Handles the input bluring
* @param evt: the event that fired
*/
handleBlur = (evt) => {
if (window.location.hash.indexOf('keyboardtarget?search=true') !== -1) {
window.location.hash = '/'
}
}
/**
* Handles the input focusing
* @param evt: the event that fired
*/
handleFocus = (evt) => {
window.location.hash = '/keyboardtarget?search=true'
}
/* **************************************************************************/
// IPC Events
/* **************************************************************************/
handleIPCSearchStart = () => {
if (this.state.isActive) {
this.inputRef.focus()
}
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
componentDidUpdate (prevProps, prevState) {
if (this.state.isActive) {
if (this.state.isSearching !== prevState.isSearching) {
if (this.state.isSearching) {
this.inputRef.focus()
} else {
this.inputRef.blur()
}
}
}
}
render () {
const { className, classes, mailboxId, serviceId, ...passProps } = this.props
const { isSearching, searchTerm } = this.state
// Use tabIndex to prevent focusing with tab§
return (
<Paper
{...passProps}
className={classNames(
classes.container,
isSearching ? 'active' : undefined
)}>
<TextField
inputRef={(n) => { this.inputRef = n }}
tabIndex={-1}
inputProps={{ tabIndex: -1 }}
placeholder='Search'
className={classes.input}
value={searchTerm}
onBlur={this.handleBlur}
onFocus={this.handleFocus}
onChange={this.handleChange}
onKeyDown={this.handleKeyPress} />
<IconButton tabIndex={-1} onClick={this.handleFindNext}>
<SearchIcon className={classes.icon} />
</IconButton>
<IconButton tabIndex={-1} onClick={this.handleStopSearch}>
<CloseIcon className={classes.icon} />
</IconButton>
</Paper>
)
}
}
export default ServiceSearch
|
src/app.js | flyingSprite/upperHot | // Styles - Public
import 'material-design-icons';
import './asserts/index.scss';
// Libraries
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
// Load Material UI
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
// Store
import configureStore from './store/reduxStore';
const store = configureStore();
injectTapEventPlugin();
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider muiTheme={muiTheme}>
<div className="wrapper vertical-sidebar cyan-scheme">
{this.props.children}
</div>
</MuiThemeProvider>
</Provider>,
document.getElementById('root')
);
|
app/components/common/notFoundPage.js | ongmin/batchtracker | 'use strict'
import React from 'react'
import { Link } from 'react-router'
var NotFoundPage = React.createClass({
render: function () {
return (
<div className='contentContainer'>
<h1>Page Not Found</h1>
<p>Sorry, there is nothing to see here.</p>
<p><Link to='/'>Back to Home</Link></p>
</div>
)
}
})
module.exports = NotFoundPage
|
src/main.js | drifterz28/drizzle-maker | import React from 'react';
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux';
import {configureStore} from './store';
import seasons from 'lib/seasons';
import App from './containers/app';
let state;
const store = configureStore(state);
//seasons();
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.querySelector('.container')
);
|
client/src/components/auth/Signup.js | NicholasAsimov/voting-app | import React from 'react';
import { reduxForm } from 'redux-form';
import * as actions from '../../actions';
class Signup extends React.Component {
handleFormSubmit = (formProps) => {
this.props.signupUser(formProps);
};
renderAlert() {
if (this.props.errorMessage) {
return (
<div className="alert alert-danger">
<strong>Oops!</strong> {this.props.errorMessage}
</div>
);
}
}
render() {
const { handleSubmit, fields: { email, password, passwordConfirm } } = this.props;
return (
<form onSubmit={handleSubmit(this.props.signupUser)} className="text-left">
<fieldset className="form-group">
<label>Email:</label>
<input className="form-control" {...email} />
{email.touched && email.error && <div className="error">{email.error}</div>}
</fieldset>
<fieldset className="form-group">
<label>Password:</label>
<input type="password" className="form-control" {...password} />
{password.touched && password.error && <div className="error">{password.error}</div>}
</fieldset>
<fieldset className="form-group">
<label>Confirm Password:</label>
<input type="password" className="form-control" {...passwordConfirm} />
{passwordConfirm.touched && passwordConfirm.error && <div className="error">{passwordConfirm.error}</div>}
</fieldset>
{this.renderAlert()}
<button action="submit" className="btn btn-primary">Sign Up</button>
</form>
);
}
}
function validate(values) {
const errors = {};
const requiredFields = ['email', 'password', 'passwordConfirm'];
requiredFields.forEach(field => {
if (!values[field] || values[field].trim() == '') {
errors[field] = 'Required'
}
});
if (values.email && !/[^\s@]+@[^\s@]+\.[^\s@]+/.test(values.email)) {
errors.email = 'Enter a correct email';
}
if (values.passwordConfirm !== values.password) {
errors.passwordConfirm = 'Passwords must match';
}
return errors;
}
function mapStateToProps(state) {
return { errorMessage: state.auth.error };
}
export default reduxForm({
form: 'signup',
fields: ['email', 'password', 'passwordConfirm'],
validate
}, mapStateToProps, actions)(Signup);
|
src/pages/fpv-news/index.js | jumpalottahigh/blog.georgi-yanev.com | import React from 'react'
import styled from 'styled-components'
import { graphql, Link } from 'gatsby'
import Layout from '../../components/structure/layout'
import TinyLetterSignup from '../../components/TinyLetterSignUp'
const StyledFpvNewsPage = styled.div`
h2 {
text-align: center;
}
.fpv-news-list {
display: flex;
flex-flow: column wrap;
.fpv-news-item {
box-shadow: none;
display: flex;
flex-flow: column wrap;
border: 1px solid #dedede;
padding: 1rem;
border-radius: 4px;
margin-bottom: 1rem;
time {
color: #757575;
}
}
.fpv-news-item:hover {
color: #0175d8;
opacity: 0.9;
box-shadow: rgba(0, 0, 0, 0.25) 0px 7px 18px,
rgba(0, 0, 0, 0.22) 0px 7px 10px;
}
}
`
const FpvNewsPage = ({ data }) => (
<Layout>
<StyledFpvNewsPage>
<h2>FPV News</h2>
<div className="fpv-news-list">
{data.fpvNews.edges.map(({ node: item }) => (
<Link
className="fpv-news-item"
to={item.frontmatter.path}
key={item.id}
>
<h4>{item.frontmatter.title}</h4>
<time datetime={item.frontmatter.date}>
{item.frontmatter.date}
</time>
</Link>
))}
</div>
</StyledFpvNewsPage>
<TinyLetterSignup />
</Layout>
)
export default FpvNewsPage
export const FpvNewsPageQuery = graphql`
query FpvNewsPageQuery {
fpvNews: allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
filter: { fileAbsolutePath: { regex: "/content/fpv-news/" } }
) {
edges {
node {
id
frontmatter {
date(formatString: "MMMM YYYY")
path
title
}
}
}
}
}
`
|
app/src/Frontend/libs/weui/components/mediabox/mediabox_desc.js | ptphp/ptphp | /**
* Created by n7best
*/
import React from 'react';
import classNames from 'classnames';
export default class MediaBoxDescription extends React.Component {
render() {
const {children, className, ...others} = this.props;
const cls = classNames({
weui_media_desc: true
}, className);
return (
<p className={cls} {...others}>{children}</p>
);
}
}; |
app/common/components/VocabSynonym/VocabSynonymList.js | Kaniwani/KW-Frontend | import React from 'react';
import PropTypes from 'prop-types';
import VocabSynonym from 'common/components/VocabSynonym/VocabSynonym';
import Element from 'common/components/Element';
VocabSynonymList.propTypes = {
ids: PropTypes.arrayOf(PropTypes.number).isRequired,
reviewId: PropTypes.number.isRequired,
};
export function VocabSynonymList({ ids, reviewId }) {
return (
ids.length > 0 && (
<Element flexRow>
{ids.map((id) => <VocabSynonym key={id} id={id} reviewId={reviewId} />)}
</Element>
)
);
}
export default VocabSynonymList;
|
packages/zensroom/lib/components/static/About.js | SachaG/Zensroom | /*
About page.
*/
import React from 'react';
import { Components, registerComponent } from 'meteor/vulcan:core';
const About = () =>
<div>
About
</div>
registerComponent('About', About);
export default About; |
node_modules/react-router/es/Router.js | raptor1989/MobileHeader | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import invariant from 'invariant';
import React from 'react';
import createReactClass from 'create-react-class';
import { func, object } from 'prop-types';
import _createTransitionManager from './createTransitionManager';
import { routes } from './InternalPropTypes';
import RouterContext from './RouterContext';
import { createRoutes } from './RouteUtils';
import { createRouterObject as _createRouterObject, assignRouterState } from './RouterUtils';
import warning from './routerWarning';
var propTypes = {
history: object,
children: routes,
routes: routes, // alias for children
render: func,
createElement: func,
onError: func,
onUpdate: func,
// PRIVATE: For client-side rehydration of server match.
matchContext: object
};
/**
* A <Router> is a high-level API for automatically setting up
* a router that renders a <RouterContext> with all the props
* it needs each time the URL changes.
*/
var Router = createReactClass({
displayName: 'Router',
propTypes: propTypes,
getDefaultProps: function getDefaultProps() {
return {
render: function render(props) {
return React.createElement(RouterContext, props);
}
};
},
getInitialState: function getInitialState() {
return {
location: null,
routes: null,
params: null,
components: null
};
},
handleError: function handleError(error) {
if (this.props.onError) {
this.props.onError.call(this, error);
} else {
// Throw errors by default so we don't silently swallow them!
throw error; // This error probably occurred in getChildRoutes or getComponents.
}
},
createRouterObject: function createRouterObject(state) {
var matchContext = this.props.matchContext;
if (matchContext) {
return matchContext.router;
}
var history = this.props.history;
return _createRouterObject(history, this.transitionManager, state);
},
createTransitionManager: function createTransitionManager() {
var matchContext = this.props.matchContext;
if (matchContext) {
return matchContext.transitionManager;
}
var history = this.props.history;
var _props = this.props,
routes = _props.routes,
children = _props.children;
!history.getCurrentLocation ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You have provided a history object created with history v4.x or v2.x ' + 'and earlier. This version of React Router is only compatible with v3 ' + 'history objects. Please change to history v3.x.') : invariant(false) : void 0;
return _createTransitionManager(history, createRoutes(routes || children));
},
componentWillMount: function componentWillMount() {
var _this = this;
this.transitionManager = this.createTransitionManager();
this.router = this.createRouterObject(this.state);
this._unlisten = this.transitionManager.listen(function (error, state) {
if (error) {
_this.handleError(error);
} else {
// Keep the identity of this.router because of a caveat in ContextUtils:
// they only work if the object identity is preserved.
assignRouterState(_this.router, state);
_this.setState(state, _this.props.onUpdate);
}
});
},
/* istanbul ignore next: sanity check */
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : void 0;
process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : void 0;
},
componentWillUnmount: function componentWillUnmount() {
if (this._unlisten) this._unlisten();
},
render: function render() {
var _state = this.state,
location = _state.location,
routes = _state.routes,
params = _state.params,
components = _state.components;
var _props2 = this.props,
createElement = _props2.createElement,
render = _props2.render,
props = _objectWithoutProperties(_props2, ['createElement', 'render']);
if (location == null) return null; // Async match
// Only forward non-Router-specific props to routing context, as those are
// the only ones that might be custom routing context props.
Object.keys(propTypes).forEach(function (propType) {
return delete props[propType];
});
return render(_extends({}, props, {
router: this.router,
location: location,
routes: routes,
params: params,
components: components,
createElement: createElement
}));
}
});
export default Router; |
app/containers/EnergiesPage/Input.js | mhoffman/CatAppBrowser |
/*
*
* EnergiesPageInput
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import styled from 'styled-components';
import ReactGA from 'react-ga';
import Button from 'material-ui/Button';
import { LinearProgress, CircularProgress } from 'material-ui/Progress';
import Paper from 'material-ui/Paper';
import { withStyles } from 'material-ui/styles';
import Grid from 'material-ui/Grid';
import { FormGroup } from 'material-ui/Form';
import * as Scroll from 'react-scroll';
import { MdSearch, MdWarning } from 'react-icons/lib/md';
import cachios from 'cachios';
import { newGraphQLRoot } from 'utils/constants';
import { withCommas } from 'utils/functions';
import * as actions from './actions';
import TermAutosuggest from './TermAutosuggest';
const MButton = styled(Button)`
margin: 25px;
marginLeft: 0;
`;
const styles = (theme) => ({
paper: {
padding: theme.spacing.unit * 2,
marginTop: theme.spacing.unit * 3,
},
button: {
margin: theme.spacing.unit,
textTransform: 'none',
},
progress: {
margin: theme.spacing.unit,
},
hint: {
color: '#aaa',
marginBottom: theme.spacing.unit,
},
});
const initialState = {
reactant_options: [],
product_options: [],
facet: '',
surfaceComposition: '',
reactants: { label: 'any', value: '' },
products: { label: 'any', value: '' },
loading: false,
suggestionsReady: false,
resultCount: '...',
};
class EnergiesPageInput extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = initialState;
// Workaround, instead of calling .bind in every render
this.submitForm = this.submitForm.bind(this);
this.resetForm = this.resetForm.bind(this);
this.setSubstate = this.setSubstate.bind(this);
this.getFilterString = this.getFilterString.bind(this);
this.getResultCount = this.getResultCount.bind(this);
this.getResultCount();
}
componentDidMount() {
this.updateOptions();
this.getResultCount();
}
setSubstate(key, value) {
const newSubstate = {};
newSubstate[key] = value;
this.setState(newSubstate);
}
getResultCount() {
this.setState({
resultCount: <CircularProgress size={25} />,
});
const filterString = this.getFilterString();
const query = {
ttl: 300,
query: `query{reactions ( first: 0, ${filterString} ) {
totalCount
edges {
node {
id
}
}
}}
` };
cachios.post(newGraphQLRoot, query).then((response) => {
const totalCount = response.data.data.reactions.totalCount;
let message;
if (totalCount === 0) {
message = <div>No entries <MdWarning /></div>;
} else if (totalCount === 1) {
message = '1 entry';
} else {
message = `${withCommas(response.data.data.reactions.totalCount)} entries`;
}
this.setState({
resultCount: message,
});
});
}
getFilterString() {
const filters = [];
if (typeof this.state.surfaceComposition.label !== 'undefined' && this.state.surfaceComposition.label) {
filters.push(`surfaceComposition: "${this.state.surfaceComposition.label.trim()}"`);
}
if (typeof this.state.facet.label !== 'undefined' && this.state.facet.label) {
filters.push(`facet: "~${this.state.facet.label.replace(/^\(([^)]*)\)$/, '$1').trim()}"`);
}
if (typeof this.state.reactants.label !== 'undefined' && this.state.reactants.label) {
filters.push(`reactants: "${this.state.reactants.label.replace(/\*/g, 'star').replace(/[ ]/g, '').replace('any', '').trim() || '~'}"`);
}
if (typeof this.state.products.label !== 'undefined' && this.state.products.label) {
filters.push(`products: "${this.state.products.label.replace(/\*/g, 'star').replace(/[ ]/g, '').replace('any', '').trim() || '~'}"`);
}
const filterString = filters.join(', ');
return filterString;
}
handleChange(name) {
return (event) => {
this.setState({
[name]: event.target.value,
});
this.updateOptions(name);
};
}
resetForm() {
this.setState(initialState);
this.updateOptions('');
this.props.receiveReactions([]);
this.props.clearSystems();
}
submitForm() {
this.props.clearSystems();
this.setState({ loading: true });
const filterString = this.getFilterString();
this.props.saveSearch(filterString);
ReactGA.event({
category: 'Search',
action: 'Search',
label: filterString,
});
const query = {
ttl: 300,
query: `query{reactions ( first: 200, ${filterString} ) {
totalCount
edges {
node {
Equation
sites
id
pubId
dftCode
dftFunctional
reactants
products
facet
chemicalComposition
facet
reactionEnergy
activationEnergy
surfaceComposition
chemicalComposition
reactionSystems {
name
energyCorrection
aseId
}
}
}
}}`,
};
cachios.post(newGraphQLRoot, query).then((response) => {
Scroll.animateScroll.scrollMore(500);
this.setState({
loading: false,
});
this.props.saveSearchQuery(query.query);
this.props.submitSearch({
reactants: this.state.reactants.label,
products: this.state.products.label,
surfaceComposition: this.state.surfaceComposition.label,
facet: this.state.facet.label,
});
this.props.receiveReactions(response.data.data.reactions.edges);
this.props.saveResultSize(response.data.data.reactions.totalCount);
}).catch(() => {
this.setState({
loading: false,
});
});
}
updateOptions(blocked = '') {
let query = '';
// Fetch Available Reactants
if (blocked !== 'reactants' && this.state.reactants.label === 'any') {
query = `{reactions(products: "~${this.state.products.value || ''}", reactants: "~", distinct: true) { edges { node { reactants } } }}`;
cachios.post(newGraphQLRoot, {
query,
ttl: 300,
}).then((response) => {
let reactants = [];
const reactant = (response.data.data.reactions.edges.map((elem) => JSON.parse(elem.node.reactants)));
reactants = reactant.map((r) => ({ key: Object.keys(r).join(' + '), value: Object.keys(r).join(' + ') }));
reactants.push({ label: 'any', value: '' });
this.setState({
reactant_options: [...new Set(reactants)],
suggestionsReady: true,
});
}).catch((error) => {
this.props.setDbError(error);
});
}
// Fetch Available Products
if (blocked !== 'products' && this.state.products.label === 'any') {
query = `{reactions(reactants: "~${this.state.reactants.value || ''}", products: "~", distinct: true) { edges { node { products } } }}`;
cachios.post(newGraphQLRoot, {
query,
ttl: 300,
}).then((response) => {
let products = [];
const product = (response.data.data.reactions.edges.map((elem) => JSON.parse(elem.node.products)));
products = products.concat([].concat(...product));
products = product.map((r) => ({ key: Object.keys(r).join(' + '), value: Object.keys(r).join(' + ') }));
/* products = products.map((r) => ({ value: r, label: r.replace('star', '*') }));*/
products.push({ label: 'any', value: '' });
this.setState({
product_options: [...new Set(products)],
suggestionsReady: true,
}).catch(() => {
this.props.setDbError();
});
});
}
}
render() {
return (
<Paper className={this.props.classes.paper}>
{this.props.dbError ? <div><MdWarning />Failed to contact database. </div> : null }
<h2>Surface Reactions</h2>
<h3>Search for chemical reactions across all publications and datasets!</h3>
<div style={{ width: '55%', textAlign: 'justify' }}>
<div> A quick guide: </div>
<ul>
<li> Leave fields blank if you {"don't"} want to impose any restrictions. </li>
<li> For the <b>Reactants</b> and <b>Products</b> fields, choose the chemical species taking part in the left- and/or right hand side of the chemical reaction respectively. The phase of the molecules and elements can also be specified, such that {"'CO2gas'"} refers to CO<sub>2</sub> in the gas phase, whereas {"'CO2*'"} refers to CO<sub>2</sub> adsorbed on the surface. </li>
<li> In the <b>Surface</b> field, enter the (reduced) chemical composition of the surface, or a sum of elements that must be present, such as {"'Ag+'"} or {"'Ag+Sr'"}. </li>
</ul>
</div>
<div className={this.props.classes.hint}>{this.state.resultCount}</div>
<FormGroup row>
<TermAutosuggest field="reactants" setSubstate={this.setSubstate} submitForm={this.submitForm} label="Reactants" placeholder="CO, CO*, COgas, ..." autofocus initialValue={this.props.filter.reactants} keyUp={this.getResultCount} />
<span style={{ flexGrow: 1, position: 'relative', float: 'left', display: 'inline-block', whiteSpace: 'nowrap', margin: 10 }} > {'→'} </span>
<TermAutosuggest field="products" submitForm={this.submitForm} setSubstate={this.setSubstate} label="Products" placeholder="" initialValue={this.props.filter.products} keyUp={this.getResultCount} />
<span style={{ flexGrow: 1, position: 'relative', float: 'left', display: 'inline-block', whiteSpace: 'nowrap', margin: 10 }} > {' '} </span>
<TermAutosuggest field="surfaceComposition" submitForm={this.submitForm} setSubstate={this.setSubstate} label="Surface" placeholder="Pt, CoO3, ..." initialValue={this.props.filter.surfaceComposition} keyUp={this.getResultCount} />
<span style={{ flexGrow: 1, position: 'relative', float: 'left', display: 'inline-block', whiteSpace: 'nowrap', margin: 10 }} > {' '} </span>
<TermAutosuggest field="facet" submitForm={this.submitForm} setSubstate={this.setSubstate} label="Facet" placeholder="100, 111-(4x4) 10-14, ..." initialValue={this.props.filter.facet} keyUp={this.getResultCount} />
<span style={{ flexGrow: 1, position: 'relative', float: 'left', display: 'inline-block', whiteSpace: 'nowrap', margin: 10 }} > {' '} </span>
<br />
<br />
<Grid container justify="flex-end" direction="row">
<Grid item>
<MButton raised onClick={this.submitForm} color="primary" className={this.props.classes.button}><MdSearch /> Search </MButton>
</Grid>
</Grid>
</FormGroup>
{this.state.loading ? <LinearProgress color="primary" className={this.props.classes.progress} /> :
null
}
</Paper>
);
}
}
EnergiesPageInput.propTypes = {
classes: PropTypes.object,
clearSystems: PropTypes.func.isRequired,
dbError: PropTypes.bool,
filter: PropTypes.object,
receiveReactions: PropTypes.func.isRequired,
saveResultSize: PropTypes.func,
saveSearch: PropTypes.func,
submitSearch: PropTypes.func.isRequired,
setDbError: PropTypes.func,
saveSearchQuery: PropTypes.func,
};
EnergiesPageInput.defaultProps = {
};
const mapStateToProps = (state) => ({
filter: state.get('energiesPageReducer').filter,
search: state.get('energiesPageReducer').search,
simpleSearch: state.get('energiesPageReducer').simpleSearch,
dbError: state.get('energiesPageReducer').dbError,
});
const mapDispatchToProps = (dispatch) => ({
receiveReactions: (reactions) => {
dispatch(actions.receiveReactions(reactions));
},
saveSearch: (search) => {
dispatch(actions.saveSearch(search));
},
saveResultSize: (resultSize) => {
dispatch(actions.saveResultSize(resultSize));
},
toggleSimpleSearch: () => {
dispatch(actions.toggleSimpleSearch());
},
setDbError: () => {
dispatch(actions.setDbError());
},
saveSearchQuery: (searchQuery) => {
dispatch(actions.saveSearchQuery(searchQuery));
},
});
export default withStyles(styles, { withTheme: true })(
connect(mapStateToProps, mapDispatchToProps)(EnergiesPageInput)
);
|
src/containers/AreaViewer.js | rodrigo-puente/poke-nostalgia | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { AreaViewer } from '../components/AreaViewer';
import ControlsContainer from './Controls';
import { setScreenFocus } from '../actions/Controls';
import { fetchPokedex } from '../actions/Pokedex';
import styles from '../styles/PokemonList';
import pokemonNames from '../data/PokemonNames';
class AreaViewerContainer extends Component {
componentWillMount() {
this.props.setScreenFocus("VIEWER");
}
getPokemonName = (pokemonId) => {
return pokemonNames[this.props.pokemonId - 1].toUpperCase();
}
render() {
return (
<div className="container" style={ styles.container }>
<div className="gbScreen" style={ styles.gbScreen }>
<AreaViewer pokemonName={ this.getPokemonName() }/>
</div>
<ControlsContainer/>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
let { pokemonId } = ownProps.params;
return {
pokemonId: parseInt(pokemonId, 10)
}
}
const mapDispatchToProps = (dispatch) => {
return {
setScreenFocus: (screen) =>
dispatch(setScreenFocus(screen)),
fetchPokedex: (pokedexId) =>
dispatch(fetchPokedex(pokedexId))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AreaViewerContainer);
|
client/modules/Wizard/Steps/StepNumber1.js | zivkaziv/MazorTech | 'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import MedicalDiagnosticItem from '../componenets/MedicalDiagnosticItem/MedicalDiagnosticItem';
import SearchInput, {createFilter} from 'react-search-input'
// Material
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import Dialog from 'material-ui/Dialog';
import TextField from 'material-ui/TextField';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import lightTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
// Import Selectors
import { getMedicalRights } from '../WizardReducer';
// Styles
import searchInputStyles from './StepNumber1.css';
const styles = {
wizardStepPageStyle: {
maxHeight: 350,
// maxWidth: 679,
// overflow:'auto',
},
medicalDiagnosticsContainer:{
display:'flex'
},
searchContainer:{
height:383,
overflow:'auto'
},
cantFindContainer:{
textAlign:'center',
width:'100%'
},
dialogContentStyle:{
width: '50%',
maxWidth: 'none',
}
};
const KEYS_TO_FILTERS = ['condition'];
class StepNumber1 extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm : '',
dialogOpen : false,
cantFindDialogOpen : false
};
this.searchUpdated = this.searchUpdated.bind(this);
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleCantFindDialogOpen = this.handleCantFindDialogOpen.bind(this);
this.handleCantFindDialogClose = this.handleCantFindDialogClose.bind(this);
this.isValidated = this.isValidated.bind(this);
}
isValidated() {
console.log('check is validate');
let isValid = false;
for(let index = 0; index < this.props.medicalRights.length; index++){
if(this.props.medicalRights[index].isSelected){
isValid = true;
break;
}
}
if(!isValid){
this.handleOpen();
}
return isValid;
}
searchUpdated (term) {
console.log(term);
this.setState({searchTerm: term})
}
componentDidMount() {
this.context.mixpanel.track('Wizard step open',{'ab_version':'v1','step':'1'});
}
handleOpen = () => {
this.setState({dialogOpen: true});
};
handleClose = () => {
this.setState({dialogOpen: false});
};
handleCantFindDialogOpen = () => {
this.context.mixpanel.track('Wizard step button',{'ab_version':'v1','step':'1','button':"can't find"});
this.setState({cantFindDialogOpen: true});
};
handleCantFindDialogClose = () => {
this.setState({cantFindDialogOpen: false});
};
getChildContext() {
return {
muiTheme: getMuiTheme(lightTheme),
};
}
render() {
const filteredMedicalDiagnostics = this.props.medicalRights.filter(createFilter(this.state.searchTerm, KEYS_TO_FILTERS));
const actions = [
<FlatButton
label="Ok"
primary={true}
keyboardFocused={true}
onTouchTap={this.handleClose}
/>,
];
const actionsCantFind = [
<FlatButton
label="OK"
primary={true}
keyboardFocused={true}
onTouchTap={this.handleCantFindDialogClose}
/>,
];
return (
<div className="step step1" style={styles.wizardStepPageStyle}>
<div className="row">
<div className="row" style={styles.searchContainer}>
<SearchInput placeholder='Search for your medical diagnostic'
className={searchInputStyles['search-input']}
onChange={this.searchUpdated} />
{filteredMedicalDiagnostics.map((medicalRight,i) => {
return (
<MedicalDiagnosticItem key={i} medicalRight={medicalRight}/>
)
})}
</div>
<div className="row" style={styles.cantFindContainer}>
<FlatButton
label="Can't find proper diagnostic"
primary={true}
fullWidth={true}
keyboardFocused={false}
contentStyle={styles.dialogContentStyle}
onTouchTap={this.handleCantFindDialogOpen}
/>
</div>
{/*Can't find dialog*/}
<Dialog
title="Can't find"
actions={actionsCantFind}
modal={true}
open={this.state.cantFindDialogOpen}
contentStyle={styles.dialogContentStyle}
onRequestClose={this.handleCantFindDialogClose}>
Sorry, but we aren't support it yet...
{/*<TextField hintText="Write here in your words the medical diagnostic"/>*/}
</Dialog>
{/*You must choose dialog*/}
<Dialog
title="Please choose"
actions={actions}
modal={true}
open={this.state.dialogOpen}
onRequestClose={this.handleClose}
>
You must select at least one medical diagnostic
</Dialog>
</div>
</div>
)
}
}
function mapStateToProps(state) {
return {
medicalRights: getMedicalRights(state)
};
}
StepNumber1.propTypes = {
medicalRight: PropTypes.any
};
StepNumber1.childContextTypes = {
muiTheme: React.PropTypes.object,
};
StepNumber1.contextTypes = {
router: React.PropTypes.object,
mixpanel: PropTypes.any
};
export default connect(mapStateToProps, null, null, { withRef: true })(StepNumber1);
|
src/components/app.js | samlawrencejones/react-starter | import React from 'react'
import Paper from 'material-ui/lib/paper'
import AppBar from 'material-ui/lib/app-bar'
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList'
import Footer from '../components/Footer'
export default class App extends React.Component {
render() {
return (
<div className="container">
<div className="body">
<AppBar
title="Todo List"
showMenuIconButton={false}
/>
<Paper style={{
width: '100%',
padding: 50,
textAlign: 'center'
}} zDepth={1}
rounded={false}>
<AddTodo />
<Footer />
<VisibleTodoList />
</Paper>
</div>
</div>
)
}
}
|
blueocean-material-icons/src/js/components/svg-icons/action/explore.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionExplore = (props) => (
<SvgIcon {...props}>
<path d="M12 10.9c-.61 0-1.1.49-1.1 1.1s.49 1.1 1.1 1.1c.61 0 1.1-.49 1.1-1.1s-.49-1.1-1.1-1.1zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2.19 12.19L6 18l3.81-8.19L18 6l-3.81 8.19z"/>
</SvgIcon>
);
ActionExplore.displayName = 'ActionExplore';
ActionExplore.muiName = 'SvgIcon';
export default ActionExplore;
|
index.android.js | jefflanzi/rn-app-template | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class appTemplate extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('appTemplate', () => appTemplate);
|
assets/jqwidgets/demos/react/app/formattedinput/exponentialnotation/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxFormattedInput from '../../../jqwidgets-react/react_jqxformattedinput.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
class App extends React.Component {
componentDidMount() {
this.refs.getDecimal.on('click', () => {
let decimalValue = this.refs.myFormattedInput.val('decimal');
alert('Decimal Value: ' + decimalValue);
});
this.refs.getExponential.on('click', () => {
let exponentialValue = this.refs.myFormattedInput.val('exponential');
alert('Exponential Notation: ' + exponentialValue);
});
this.refs.getScientific.on('click', () => {
let scientificValue = this.refs.myFormattedInput.val('scientific');
alert('Scientific Notation: ' + scientificValue);
});
this.refs.getEngineering.on('click', () => {
let engineeringValue = this.refs.myFormattedInput.val('engineering');
alert('Engineering Notation: ' + engineeringValue);
});
}
render() {
return (
<div>
<JqxFormattedInput ref='myFormattedInput'
width={200} height={25} radix={'decimal'}
value={330000} decimalNotation={'exponential'}
/>
<div style={{ marginTop: 20 }}>
<JqxButton ref='getDecimal' value='Get Decimal Value' style={{ float: 'left' }} width={175} />
<JqxButton ref='getExponential' value='Get Exponential Notation' style={{ marginLeft: 5, float: 'left' }} width={175} />
<br />
<br />
<JqxButton ref='getScientific' value='Get Scientific Notation' style={{ float: 'left' }} width={175} />
<JqxButton ref='getEngineering' value='Get Engineering Notation' style={{ marginLeft: 5, float: 'left' }} width={175} />
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/image/blur-circular.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBlurCircular = (props) => (
<SvgIcon {...props}>
<path d="M10 9c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0 4c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zM7 9.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm3 7c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm-3-3c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm3-6c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM14 9c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0-1.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm3 6c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm0-4c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm2-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm0-3.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z"/>
</SvgIcon>
);
ImageBlurCircular = pure(ImageBlurCircular);
ImageBlurCircular.displayName = 'ImageBlurCircular';
ImageBlurCircular.muiName = 'SvgIcon';
export default ImageBlurCircular;
|
src/components/PastEvents.js | Outfitio/breakfast-series-landing | import React, { Component } from 'react';
import Link from 'gatsby-link';
export default class PastEvents extends Component {
render() {
const { events, currentPath } = this.props;
const sortedEvents = events.map(event => event.node.id).sort();
return(
<div>
{sortedEvents.map(id => (
<Link
key={id}
to={id}>
<span
style={{
...styles.calendarItem,
borderColor: id === currentPath ? 'white' : 'transparent'
}}
>
{id}
</span>
</Link>
))}
</div>
)
}
}
const styles = {
calendarItem: {
fontWeight: 'bold',
marginRight: '0.5em',
padding: '0.5em',
borderRadius: '3em',
border: '3px solid transparent'
}
}
|
src/Form.js | jsummer/react-ui | 'use strict'
import React from 'react'
import classnames from 'classnames'
import { forEach } from './utils/objects'
import FormControl from './FormControl'
import FormSubmit from './FormSubmit'
import { requireCss } from './themes'
requireCss('form')
export default class Form extends React.Component {
static displayName = 'Form'
static propTypes = {
beforeSubmit: React.PropTypes.func,
children: React.PropTypes.any,
className: React.PropTypes.string,
data: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.func
]).isRequired,
hintType: React.PropTypes.oneOf(['block', 'none', 'pop', 'inline']),
layout: React.PropTypes.oneOf(['aligned', 'stacked', 'inline']),
onSubmit: React.PropTypes.func,
style: React.PropTypes.object
}
static defaultProps = {
data: {},
layout: 'inline'
}
componentWillMount () {
this.fetchData(this.props.data)
}
componentWillReceiveProps (nextProps) {
if (this.props.data !== this.props.data) {
this.fetchData(nextProps.data)
}
}
state = {
locked: false,
data: {}
}
fetchData (data) {
if (typeof data === 'function') {
data.then(res => {
this.fetchData(res)
})()
return
}
this.setState({ data })
this.setData(data)
}
getValue () {
let data = this.state.data
forEach(this.refs, (ref, k) => {
if (!ref.props.ignore) {
data[k] = ref.getValue()
}
})
return data
}
setValue (key, value) {
let data = this.state.data
data[key] = value
this.setState({ data })
}
setData (data) {
forEach(this.refs, (ref, k) => {
ref.setValue(data[k])
})
}
equalValidate (targetRef, equalRef) {
let self = this
return function () {
let target = self.refs[targetRef]
if (!target) {
console.warn(`equal target '${targetRef}' not existed`)
return false
}
let equal = self.refs[equalRef]
return target.getValue() === equal.getValue()
}
}
renderChildren () {
return React.Children.map(this.props.children, child => {
let props = {
hintType: child.props.hintType || this.props.hintType,
readOnly: child.props.readOnly || this.state.locked,
layout: this.props.layout
}
if (child.type === FormControl) {
if (!child.props.name) {
console.warn('FormControl must have a name!')
return null
}
props.ref = child.props.name
if (this.state.data[child.props.name] !== undefined) {
props.value = this.state.data[child.props.name]
}
if (child.props.equal) {
props.onValidate = this.equalValidate(child.props.equal, child.props.name)
}
} else if (child.type === FormSubmit) {
props.locked = this.state.locked
}
child = React.cloneElement(child, props)
return child
})
}
getReference (name) {
return this.refs[name]
}
validate () {
let success = true
forEach(this.refs, function (child) {
if (child.props.ignore) {
return
}
let suc = child.validate()
success = success && suc
})
return success
}
handleSubmit (event) {
if (this.state.locked) {
return
}
event.preventDefault()
this.onSubmit()
}
onSubmit () {
this.setState({ locked: true })
let success = this.validate()
if (success && this.props.beforeSubmit) {
success = this.props.beforeSubmit()
}
if (!success) {
this.setState({ locked: false })
return
}
if (this.props.onSubmit) {
this.props.onSubmit(this.getValue())
this.setState({ locked: false })
}
}
render () {
let className = classnames(
this.props.className,
'rct-form',
{
'rct-form-aligned': this.props.layout === 'aligned',
'rct-form-inline': this.props.layout === 'inline',
'rct-form-stacked': this.props.layout === 'stacked'
}
)
return (
<form onSubmit={this.handleSubmit.bind(this)} style={this.props.style} className={className}>
{this.renderChildren()}
</form>
)
}
}
|
src/components/Divider.js | henrytao-me/react-native-mdcore | import React from 'react'
import { View } from 'react-native'
import PropTypes from './PropTypes'
import PureComponent from './PureComponent'
import StyleSheet from './StyleSheet'
export default class Divider extends PureComponent {
static contextTypes = {
theme: PropTypes.any
}
static propTypes = {
largePadding: PropTypes.bool
}
render() {
const { theme } = this.context
const styles = Styles.get(theme, this.props)
return (
<View style={[styles.container, this.props.style]} />
)
}
}
const Styles = StyleSheet.create((theme, opts = {}) => {
let { largePadding } = opts
const container = {
backgroundColor: theme.divider.color,
height: theme.divider.size,
marginLeft: largePadding ? (2 * theme.list.paddingLeft + theme.list.avatarSize) : 0
}
return { container }
})
|
app/src/components/content/Problems/ProblemDetail/problemdes/index.js | ouxu/NEUQ-OJ | /**
* Created by out_xu on 17/1/8.
*/
import React from 'react'
import { Card, Collapse } from 'antd'
import './index.less'
import Markdown from 'components/plugins/Markdown'
const Panel = Collapse.Panel
const createMarkup = html => ({__html: html})
const return2Br = (str) => {
str = str || ''
return str.replace(/\r?\n/g, '<br/>')
}
const customPanelStyle = {}
const ProblemDes = ({data = {}}) => (
<Collapse
defaultActiveKey={['problem-des', 'problem-sampleinput', 'problem-sampleoutput']}
bordered={false}
className='problem-detail-main'
>
<Panel header='描述' key='problem-des' style={customPanelStyle}>
<Card bodyStyle={{fontSize: 14}} className='problem-detail-main-desc'>
<h4>题目描述:</h4>
<Markdown content={data.description} />
<h4>输入:</h4>
<Markdown content={data.input} />
<h4>输出:</h4>
<Markdown content={data.output} />
</Card>
</Panel>
<Panel header='样例输入' key='problem-sampleinput'>
<Card >
<pre dangerouslySetInnerHTML={createMarkup(return2Br(data.sample_input))} />
</Card>
</Panel>
<Panel header='样例输出' key='problem-sampleoutput'>
<Card>
<pre dangerouslySetInnerHTML={createMarkup(return2Br(data.sample_output))} />
</Card>
</Panel>
{
data.hint &&
<Panel header='提示' key='problem-hint'>
<Card>
<Markdown content={data.hint} />
</Card>
</Panel>
}
</Collapse>
)
export default ProblemDes
|
src/Well.js | nickuraltsev/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Well = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'well'
};
},
render() {
let classes = this.getBsClassSet();
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
});
export default Well;
|
app/javascript/mastodon/features/account/components/account_note.js | imas/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Textarea from 'react-textarea-autosize';
import { is } from 'immutable';
const messages = defineMessages({
placeholder: { id: 'account_note.placeholder', defaultMessage: 'Click to add a note' },
});
class InlineAlert extends React.PureComponent {
static propTypes = {
show: PropTypes.bool,
};
state = {
mountMessage: false,
};
static TRANSITION_DELAY = 200;
componentWillReceiveProps (nextProps) {
if (!this.props.show && nextProps.show) {
this.setState({ mountMessage: true });
} else if (this.props.show && !nextProps.show) {
setTimeout(() => this.setState({ mountMessage: false }), InlineAlert.TRANSITION_DELAY);
}
}
render () {
const { show } = this.props;
const { mountMessage } = this.state;
return (
<span aria-live='polite' role='status' className='inline-alert' style={{ opacity: show ? 1 : 0 }}>
{mountMessage && <FormattedMessage id='generic.saved' defaultMessage='Saved' />}
</span>
);
}
}
export default @injectIntl
class AccountNote extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
value: PropTypes.string,
onSave: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
state = {
value: null,
saving: false,
saved: false,
};
componentWillMount () {
this._reset();
}
componentWillReceiveProps (nextProps) {
const accountWillChange = !is(this.props.account, nextProps.account);
const newState = {};
if (accountWillChange && this._isDirty()) {
this._save(false);
}
if (accountWillChange || nextProps.value === this.state.value) {
newState.saving = false;
}
if (this.props.value !== nextProps.value) {
newState.value = nextProps.value;
}
this.setState(newState);
}
componentWillUnmount () {
if (this._isDirty()) {
this._save(false);
}
}
setTextareaRef = c => {
this.textarea = c;
}
handleChange = e => {
this.setState({ value: e.target.value, saving: false });
};
handleKeyDown = e => {
if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
this._save();
if (this.textarea) {
this.textarea.blur();
}
} else if (e.keyCode === 27) {
e.preventDefault();
this._reset(() => {
if (this.textarea) {
this.textarea.blur();
}
});
}
}
handleBlur = () => {
if (this._isDirty()) {
this._save();
}
}
_save (showMessage = true) {
this.setState({ saving: true }, () => this.props.onSave(this.state.value));
if (showMessage) {
this.setState({ saved: true }, () => setTimeout(() => this.setState({ saved: false }), 2000));
}
}
_reset (callback) {
this.setState({ value: this.props.value }, callback);
}
_isDirty () {
return !this.state.saving && this.props.value !== null && this.state.value !== null && this.state.value !== this.props.value;
}
render () {
const { account, intl } = this.props;
const { value, saved } = this.state;
if (!account) {
return null;
}
return (
<div className='account__header__account-note'>
<label htmlFor={`account-note-${account.get('id')}`}>
<FormattedMessage id='account.account_note_header' defaultMessage='Note' /> <InlineAlert show={saved} />
</label>
<Textarea
id={`account-note-${account.get('id')}`}
className='account__header__account-note__content'
disabled={this.props.value === null || value === null}
placeholder={intl.formatMessage(messages.placeholder)}
value={value || ''}
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
onBlur={this.handleBlur}
ref={this.setTextareaRef}
/>
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.