path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/javascript/mastodon/features/picture_in_picture/index.js
imas/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import Video from 'mastodon/features/video'; import Audio from 'mastodon/features/audio'; import { removePictureInPicture } from 'mastodon/actions/picture_in_picture'; import Header from './components/header'; import Footer from './components/footer'; const mapStateToProps = state => ({ ...state.get('picture_in_picture'), }); export default @connect(mapStateToProps) class PictureInPicture extends React.Component { static propTypes = { statusId: PropTypes.string, accountId: PropTypes.string, type: PropTypes.string, src: PropTypes.string, muted: PropTypes.bool, volume: PropTypes.number, currentTime: PropTypes.number, poster: PropTypes.string, backgroundColor: PropTypes.string, foregroundColor: PropTypes.string, accentColor: PropTypes.string, dispatch: PropTypes.func.isRequired, }; handleClose = () => { const { dispatch } = this.props; dispatch(removePictureInPicture()); } render () { const { type, src, currentTime, accountId, statusId } = this.props; if (!currentTime) { return null; } let player; if (type === 'video') { player = ( <Video src={src} currentTime={this.props.currentTime} volume={this.props.volume} muted={this.props.muted} autoPlay inline alwaysVisible /> ); } else if (type === 'audio') { player = ( <Audio src={src} currentTime={this.props.currentTime} volume={this.props.volume} muted={this.props.muted} poster={this.props.poster} backgroundColor={this.props.backgroundColor} foregroundColor={this.props.foregroundColor} accentColor={this.props.accentColor} autoPlay /> ); } return ( <div className='picture-in-picture'> <Header accountId={accountId} statusId={statusId} onClose={this.handleClose} /> {player} <Footer statusId={statusId} /> </div> ); } }
app/static/src/performer/TestTypeResultForm_modules/VisualTestForm.js
vsilent/Vision
import React from 'react'; import Form from 'react-bootstrap/lib/Form'; import Panel from 'react-bootstrap/lib/Panel'; import Button from 'react-bootstrap/lib/Button'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import Checkbox from 'react-bootstrap/lib/Checkbox'; import HelpBlock from 'react-bootstrap/lib/HelpBlock'; import {NotificationContainer, NotificationManager} from 'react-notifications'; var SelectField = React.createClass({ handleChange: function(event, index, value){ this.setState({ value: event.target.value }); }, getInitialState: function () { return { items: [], isVisible: false, value: -1 }; }, isVisible: function(){ return this.state.isVisible; }, componentDidMount: function(){ var source = '/api/v1.0/' + this.props.source + '/'; this.serverRequest = $.authorizedGet(source, function (result){ this.setState({ items: (result['result']) }); }.bind(this), 'json'); }, componentWillUnmount: function() { this.serverRequest.abort(); }, setVisible: function(){ this.state.isVisible = true; }, render: function() { var label = (this.props.label != null) ? this.props.label: ""; var name = (this.props.name != null) ? this.props.name: ""; var value = (this.props.value != null) ? this.props.value: ""; var validationState = (this.props.errors[name]) ? 'error' : null; var error = this.props.errors[name]; var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <FormGroup validationState={validationState}> <ControlLabel>{label}</ControlLabel> <FormControl componentClass="select" onChange={this.handleChange} name={name} value={value} > {menuItems} </FormControl> <HelpBlock className="warning">{error}</HelpBlock> </FormGroup> ); } }); const TextField = React.createClass({ render: function() { var label = (this.props.label != null) ? this.props.label: ""; var name = (this.props.name != null) ? this.props.name: ""; var value = (this.props.value != null) ? this.props.value: ""; var type = (this.props["data-type"] != null) ? this.props["data-type"]: undefined; var len = (this.props["data-len"] != null) ? this.props["data-len"]: undefined; var validationState = (this.props.errors[name]) ? 'error' : null; var error = this.props.errors[name]; return ( <FormGroup validationState={validationState}> <ControlLabel>{label}</ControlLabel> <FormControl type="text" placeholder={label} name={name} value={value} data-type={type} data-len={len} /> <HelpBlock className="warning">{error}</HelpBlock> <FormControl.Feedback /> </FormGroup> ); } }); const CheckBox = React.createClass({ render: function () { var name = (this.props.name != null) ? this.props.name: ""; var checked = (this.props.value != null) ? this.props.value: false; var is_checked = (checked) ? 'checked': ''; return ( <Checkbox checked={is_checked} name={name}> <span className="glyphicon glyphicon-menu-left"> </span> </Checkbox> ); } }); var VisualTestForm = React.createClass({ getInitialState: function () { return { loading: false, errors: {}, fields: ["tank_cover_gasket_id", "tank_pressure_unit_id", "tank_pressure", "tank_manhole_gasket_id", "tank_overpressure_valve_id", "tank_gas_relay_id", "tank_sampling_valve_id", "tank_oil_level_id", "tank_oil_pump_id", "tank_winding_temp_max", "tank_winding_temp_actual", "tank_gas_analyser", "tank_oil_temp_max", "tank_oil_temp_actual", "tank_overall_condition_id", "tank_oil_flag", "tank_winding_flag", "misc_foundation_id", "misc_temp_ambiant", "misc_load", "grounding_value", "grounding_connection_id", "tap_changer_gasket_id", "tap_changer_overpressure_valve_id", "tap_changer_oil_level_id", "tap_changer_sampling_valve_id", "tap_changer_operation_counter", "tap_changer_temp_max", "tap_changer_temp_actual", "tap_changer_counter_id", "tap_changer_pressure_unit_id", "tap_changer_pressure_max", "tap_changer_pressure_actual", "tap_changer_filter_id", "tap_changer_tap_position", "tap_changer_overall_condition_id", "exp_tank_pipe_gasket_id", "exp_tank_oil_level_id", "exp_tank_paint_id", "exp_tank_overall_condition_id", "radiator_fan_id", "radiator_gasket_id", "radiator_overall_condition_id", "control_cab_connection_id", "control_cab_heating_id", "control_cab_overall_condition_id", "bushing_gasket_id", "bushing_oil_level_id", "bushing_overall_condition_id", "notes" ] } }, componentDidMount: function () { var source = '/api/v1.0/' + this.props.tableName + '/?test_result_id=' + this.props.testResultId; this.serverRequest = $.authorizedGet(source, function (result) { var res = (result['result']); if (res.length > 0) { var fields = this.state.fields; fields.push('id'); var data = res[0]; var state = {}; for (var i = 0; i < fields.length; i++) { var key = fields[i]; if (data.hasOwnProperty(key)) { state[key] = data[key]; } } this.setState(state); } }.bind(this), 'json'); }, _create: function () { var fields = this.state.fields; var data = {test_result_id: this.props.testResultId}; var url = '/api/v1.0/' + this.props.tableName + '/'; for (var i = 0; i < fields.length; i++) { var key = fields[i]; data[key] = this.state[key]; } if ('id' in this.state) { url += this.state['id']; } return $.authorizedAjax({ url: url, type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), beforeSend: function () { this.setState({loading: true}); }.bind(this) }) }, _onSubmit: function (e) { e.preventDefault(); // Do not propagate the submit event of the main form e.stopPropagation(); if (!this.is_valid()){ NotificationManager.error('Please correct the errors'); e.stopPropagation(); return false; } var xhr = this._create(); xhr.done(this._onSuccess) .fail(this._onError) .always(this.hideLoading) }, hideLoading: function () { this.setState({loading: false}); }, _onSuccess: function (data) { // this.setState(this.getInitialState()); NotificationManager.success('Test values have been saved successfully.'); }, _onError: function (data) { var message = "Failed to create"; var res = data.responseJSON; if (res.message) { message = data.responseJSON.message; } if (res.error) { // We get list of errors if (data.status >= 500) { message = res.error.join(". "); } else if (res.error instanceof Object){ // We get object of errors with field names as key for (var field in res.error) { var errorMessage = res.error[field]; if (Array.isArray(errorMessage)) { errorMessage = errorMessage.join(". "); } res.error[field] = errorMessage; } this.setState({ errors: res.error }); } else { message = res.error; } } NotificationManager.error(message); }, _onChange: function (e) { var state = {}; state[e.target.name] = $.trim(e.target.value); var errors = this._validate(e); state = this._updateFieldErrors(e.target.name, state, errors); this.setState(state); }, _validate: function (e) { var errors = []; var error; error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type")); if (error){ errors.push(error); } error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len")); if (error){ errors.push(error); } return errors; }, _validateFieldType: function (value, type){ var error = ""; if (type != undefined && value){ var typePatterns = { "float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/, "int": /^(-|\+)?(0|[1-9]\d*)$/ }; if (!typePatterns[type].test(value)){ error = "Invalid " + type + " value"; } } return error; }, _validateFieldLength: function (value, length){ var error = ""; if (value && length){ if (value.length > length){ error = "Value should be maximum " + length + " characters long" } } return error; }, _updateFieldErrors: function (fieldName, state, errors){ // Clear existing errors related to the current field as it has been edited state.errors = this.state.errors; delete state.errors[fieldName]; // Update errors with new ones, if present if (Object.keys(errors).length){ state.errors[fieldName] = errors.join(". "); } return state; }, is_valid: function () { return (Object.keys(this.state.errors).length <= 0); }, render: function() { return ( <div className="form-container"> <h3>Visual inspection</h3> <form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}> <div className="tab_row text-center"> <div className="row"> <div className="col-md-8 "> <div className="row"> <div > <Panel header="Tank"> </Panel> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tank_cover_gasket_id" source="gasket_condition" label="Cover gasket" value={this.state.tank_cover_gasket_id} errors={this.state.errors}/> </div> <div className="col-md-2"> <b>Pressure</b> </div> <div className="col-md-2"> <SelectField name="tank_pressure_unit_id" source="pressure_unit" label="" value={this.state.tank_pressure_unit_id} errors={this.state.errors}/> </div> <div className="col-md-2"> <TextField name="tank_pressure" label="" value={this.state.tank_pressure} data-type="float" errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tank_manhole_gasket_id" source="gasket_condition" label="Manhole gasket" value={this.state.tank_manhole_gasket_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tank_overpressure_valve_id" source="valve_condition" label="Sud.Pres.Valve" value={this.state.tank_overpressure_valve_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tank_gas_relay_id" source="gas_relay" label="Gas relay" value={this.state.tank_gas_relay_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tank_sampling_valve_id" source="valve_condition" label="Sampling Valves" value={this.state.tank_sampling_valve_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tank_oil_level_id" source="fluid_level" label="Oil level" value={this.state.tank_oil_level_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tank_oil_pump_id" source="pump_condition" label="Oil Pump" value={this.state.tank_oil_pump_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-2"><b>Winding Temp.</b></div> <div className="col-md-2"> <TextField name="tank_winding_temp_max" label="Max" value={this.state.tank_winding_temp_max} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <TextField name="tank_winding_temp_actual" label="Actual" value={this.state.tank_winding_temp_actual} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <b>Ctc</b><CheckBox name="tank_winding_flag" value={this.state.tank_winding_flag}/> </div> <div className="col-md-3 nopadding"> <TextField name="tank_gas_analyser" label="Diss. Gas Analyzer" value={this.state.tank_gas_analyser} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-1 nopadding"> <b>ppm</b> </div> </div> <div className="row"> <div className="col-md-2"><b>Oil Temp.</b></div> <div className="col-md-2"> <TextField name="tank_oil_temp_max" label="Max" value={this.state.tank_oil_temp_max} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <TextField name="tank_oil_temp_actual" label="Actual" value={this.state.tank_oil_temp_actual} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <b>Ctc</b><CheckBox name="tank_oil_flag" value={this.state.tank_oil_flag}/> </div> <div className="col-md-4"> <SelectField name="tank_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.tank_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> <div className="col-md-4 "> <div className="row"> <div className="col-md-11 col-md-offset-1"> <Panel header="Miscelaneous"> </Panel> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="misc_foundation_id" source="foundation_condition" label="Foundation" value={this.state.misc_foundation_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <TextField name="misc_temp_ambiant" label="Ambient temp.(C)" value={this.state.misc_temp_ambiant} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <TextField name="misc_load" label="Load(MVA)" value={this.state.misc_load} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <Panel header="Grounding"> </Panel> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <TextField name="grounding_value" label="Value" value={this.state.grounding_value} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="grounding_connection_id" source="connection_condition" label="Connection" value={this.state.grounding_connection_id} errors={this.state.errors}/> </div> </div> </div> </div> <div className="row"> <div className="col-md-8 "> <div className="row"> <div > <Panel header="Tap Charger"> </Panel> </div> </div> <div className="row"> <div className="col-md-6"> <SelectField name="tap_changer_gasket_id" source="gasket_condition" label="Gasket" value={this.state.tap_changer_gasket_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tap_changer_overpressure_valve_id" source="valve_condition" label="Sud Pres. Valve" value={this.state.tap_changer_overpressure_valve_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tap_changer_oil_level_id" source="fluid_level" label="Oil Level" value={this.state.tap_changer_oil_level_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tap_changer_sampling_valve_id" source="valve_condition" label="Sampling Valves" value={this.state.tap_changer_sampling_valve_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 col-md-offset-6"> <TextField name="tap_changer_operation_counter" label="No. of Operations" value={this.state.tap_changer_operation_counter} errors={this.state.errors} data-type="int"/> </div> </div> <div className="row"> <div className="col-md-2"><b>Temperature(C)</b></div> <div className="col-md-2 col-md-offset-2"> <TextField name="tap_changer_temp_max" label="Max" value={this.state.tap_changer_temp_max} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <TextField name="tap_changer_temp_actual" label="Actual" value={this.state.tap_changer_temp_actual} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-4 "> <SelectField name="tap_changer_counter_id" source="tap_counter_status" label="Counter" value={this.state.tap_changer_counter_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-2"><b>Pressure</b></div> <div className="col-md-2 "> <SelectField name="tap_changer_pressure_unit_id" source="pressure_unit" label="Counter" value={this.state.tap_changer_pressure_unit_id} errors={this.state.errors}/> </div> <div className="col-md-2"> <TextField name="tap_changer_pressure_max" label="Max" value={this.state.tap_changer_pressure_max} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <TextField name="tap_changer_pressure_actual" label="Actual" value={this.state.tap_changer_pressure_actual} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-4"> <SelectField name="tap_changer_filter_id" source="tap_filter_condition" label="Filter" value={this.state.tap_changer_filter_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-2"><b>Position of NLTC</b></div> <div className="col-md-2 col-md-offset-4"> <TextField name="tap_changer_tap_position" label="Actual" value={this.state.tap_changer_tap_position} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-4"> <SelectField name="tap_changer_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.tap_changer_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> <div className="col-md-4 "> <div className="row"> <div className="col-md-11 col-md-offset-1"> <Panel header="Expansion Conservation Tank"> </Panel> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="exp_tank_pipe_gasket_id" source="gasket_condition" label="Pipe Tightness" value={this.state.exp_tank_pipe_gasket_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="exp_tank_oil_level_id" source="fluid_level" label="Oil Level" value={this.state.exp_tank_oil_level_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="exp_tank_paint_id" source="paint_types" label="Silica Gel Breather" value={this.state.exp_tank_paint_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="exp_tank_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.exp_tank_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> </div> <div className="row"> <div className="col-md-4"> <div className="row"> <div className="col-md-12 "> <Panel header="Radiator"> </Panel> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="radiator_fan_id" source="fan_condition" label="Fan" value={this.state.radiator_fan_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="radiator_gasket_id" source="gasket_condition" label="Gasket" value={this.state.radiator_gasket_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="radiator_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.radiator_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> <div className="col-md-4"> <div className="row"> <div className="col-md-12 "> <Panel header="Control Cabinet"> </Panel> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="control_cab_connection_id" source="connection_condition" label="Connection" value={this.state.control_cab_connection_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="control_cab_heating_id" source="heating_condition" label="Heating" value={this.state.control_cab_heating_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="control_cab_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.control_cab_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> <div className="col-md-4"> <div className="row"> <div className="col-md-12 "> <Panel header="Bushing+arrester"> </Panel> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="bushing_gasket_id" source="gasket_condition" label="Gasket" value={this.state.bushing_gasket_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="bushing_oil_level_id" source="fluid_level" label="Oil Level" value={this.state.bushing_oil_level_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="bushing_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.bushing_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.notes ? 'error' : null}> <FormControl componentClass="textarea" placeholder="Notes" multiple name="notes" value={this.state.notes} data-len="1000"/> <HelpBlock className="warning">{this.state.errors.notes}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> </div> <div className="row"> <div className="col-md-12 "> <Button bsStyle="success" className="pull-right" type="submit">Save</Button> &nbsp; <Button bsStyle="danger" className="pull-right margin-right-xs" onClick={this.props.handleClose} >Cancel</Button> </div> </div> </form> </div> ); } }); export default VisualTestForm;
packages/bootstrap-shell/src/providers/Modal/Context.js
TarikHuber/react-most-wanted
import React from 'react' export const Context = React.createContext(null) export default Context
src/svg-icons/av/call-to-action.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvCallToAction = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3v-3h18v3z"/> </SvgIcon> ); AvCallToAction = pure(AvCallToAction); AvCallToAction.displayName = 'AvCallToAction'; AvCallToAction.muiName = 'SvgIcon'; export default AvCallToAction;
lib/components/IndexPage.js
kern/puddin
import DraftActions from '../actions/DraftActions' import DraftStore from '../stores/DraftStore' import OrderSelect from './OrderSelect' import Quote from './Quote' import QuoteEditor from './QuoteEditor' import QuotesActions from '../actions/QuotesActions' import QuotesStore from '../stores/QuotesStore' import React from 'react' function getState() { return { ordering: QuotesStore.getOrdering(), quotes: QuotesStore.getQuotes(), draft: DraftStore.getDraft() } } export default class IndexPage extends React.Component { constructor() { this.state = getState() this._onChange = () => this.setState(getState()) } componentDidMount() { DraftStore.listen(this._onChange) QuotesStore.listen(this._onChange) } componentDidUnmount() { DraftStore.unlisten(this._onChange) QuotesStore.unlisten(this._onChange) } onChangeDraft(newDraft) { DraftActions.change(newDraft) } onSubmit() { DraftActions.submit(DraftStore.getDraft()) } onReorder(ordering) { QuotesActions.reorder({ ordering: ordering }) } render() { return <div className="page"> <h1>pudd.in</h1> <QuoteEditor {...this.state.draft} onChange={this.onChangeDraft.bind(this)} onSubmit={this.onSubmit} /> <OrderSelect value={this.state.ordering} onChange={this.onReorder.bind(this)} /> {this.state.quotes.map((q) => <Quote key={q.id} {...q} />)} </div> } }
packages/material-ui-icons/src/FilterNone.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><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 16H7V3h14v14z" /></g> , 'FilterNone');
bai/src/components/PartnershipBody/index.js
blackinai/blackinai.github.io
import { Button, Container, ListItem } from '@material-ui/core/'; import Grid from '@material-ui/core/Grid'; import { withStyles } from '@material-ui/core/styles'; import PropTypes from 'prop-types'; import React from 'react'; import Typography from '../Typography'; const styles = (theme) => ({ root: { display: 'flex', overflow: 'hidden', backgroundColor: theme.palette.secondary.main, }, container: { marginTop: theme.spacing(10), marginBottom: theme.spacing(10), display: 'flex', position: 'relative', flexDirection: 'column', alignItems: 'center', }, item: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: theme.spacing(0, 5), }, image: { height: 60, }, title: { marginTop: theme.spacing(5), marginBottom: theme.spacing(5), color: theme.palette.primary.light, }, chip: { margin: theme.spacing(1), size: 'large', borderRadius: "40px", }, divider: { backgroundColor: theme.palette.primary.light, margin: theme.spacing(2, 2), width:"140vh", height: "1px", } }); const ColorButton = withStyles((theme) => ({ root: { color: theme.palette.getContrastText(theme.palette.primary.dark), backgroundColor: theme.palette.primary.dark, '&:hover': { backgroundColor: theme.palette.primary.dark, }, }, secundary: { color: theme.palette.getContrastText(theme.palette.primary.light), backgroundColor: theme.palette.primary.light, '&:hover': { backgroundColor: theme.palette.primary.light, }, }, }))(Button); function PartnershipBody(props) { const { classes } = props; return ( <section className={classes.root}> <Container className={classes.container}> <Grid container spacing={12}> <Grid container spacing={3}> <Grid item xs={12} md={6}> <Typography variant="h2" color="secondary" className={classes.title}> Be part of our network </Typography> <ColorButton className={classes.chip} variant="contained" href="https://docs.google.com/presentation/d/1wzh9uggU_pW7X0XJ2bVPonimAprbAwNtFTvsq5hy2w8/edit"> PARTNER WITH US </ColorButton> </Grid> <Grid item xs={12} md={6}> <Typography variant="h4" className={classes.title}> Diamond & Platinum Sponsors </Typography> <Typography variant="body1" className={classes.title}> <ListItem>Recruitment booth at the workshop.</ListItem> <ListItem>Access to attendees opt-in resume booklet.</ListItem> <ListItem>Promotional materials of your organization shown during our workshop proceedings.</ListItem> <ListItem>Logo displayed on our website.</ListItem> </Typography> <Typography variant="h4" className={classes.title}> Gold & Silver Sponsors </Typography> <Typography variant="body1" className={classes.title}> <ListItem>Access to attendees opt-in resume booklet.</ListItem> <ListItem>Swags and promotional materials of your organization.</ListItem> <ListItem>Logo displayed on our website.</ListItem> </Typography> <Typography variant="h4" className={classes.title}> Bronze Sponsor </Typography> <Typography variant="body1" className={classes.title}> <ListItem>Access to attendees opt-in resume booklet.</ListItem> <ListItem>Logo displayed on our website.</ListItem> </Typography> </Grid> </Grid> </Grid> </Container> </section> ); } PartnershipBody.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(PartnershipBody);
src/client/views/compass/compass.js
ghemingway/cad.js
/* Copyright G. Hemingway, 2015 - All rights reserved */ 'use strict'; import React from 'react'; require('./compass.scss'); /*************************************************************************/ function setStyleTransform (element, value) { let style = element.style, styleNames = setStyleTransform._transformPropertyNames, i; for (i=0;i<styleNames.length;++i) { if (typeof(style[styleNames[i]]) !== 'undefined') { style[styleNames[i]] = value; } } } setStyleTransform._transformPropertyNames = [ 'transform', 'webkitTransform', 'MozTransform' ]; export default class CompassView extends React.Component { /* compassParentId, camera, controls */ constructor(props) { super(props); this.compassParent = $('#' + this.props.compassParentId); this.controls = this.props.controls; this.camera = this.props.camera; this.update = this.update.bind(this); } bindEvents() { let self = this, defaultUpVector = new THREE.Vector3(0,1,0); this.$cubeButtons.on('mouseenter', function () { self.$cubeButtons .removeClass('hover') .filter('[data-group="' + $(this).attr('data-group') + '"]') .addClass('hover'); }).on('mouseleave', function () { self.$cubeButtons.removeClass('hover'); }).on('click', function () { let upVector, upValues, eulerOrder; if (typeof(this.dataset.up) !== 'undefined') { upValues = this.dataset.up.split(',').map(parseFloat); upVector = new THREE.Vector3(upValues[0],upValues[1],upValues[2]); } else { upVector = defaultUpVector; } eulerOrder = typeof(this.dataset.order) === 'undefined' ? 'XYZ' : this.dataset.order; let conversionFactor = Math.PI / 180.0; let viewAngles = new THREE.Euler(parseFloat(this.dataset.x)*conversionFactor, parseFloat(this.dataset.y)*conversionFactor, parseFloat(this.dataset.z)*conversionFactor, eulerOrder); self.controls.setRotationFromEuler(viewAngles, upVector /* allowed to be undefined */); }); } componentDidMount() { this.compassCube = document.getElementById('compass-cube'); this.compassCubeMatrix = new THREE.Matrix4(); this.props.dispatcher.addEventListener("render:update", this.update); this.$cubeButtons = $('.cube-button'); this.bindEvents(); } componentWillUnmount() { this.props.dispatcher.removeEventListener("render:update", this.update); } update() { let up = this.camera.up, lookFrom = this.camera.position, lookTarget = this.controls.target, matrix = new THREE.Matrix4(), roundedMatrix; matrix.lookAt(lookTarget, lookFrom, up); this.compassCubeMatrix.getInverse(matrix); roundedMatrix = Array.prototype.map.call(this.compassCubeMatrix.elements, function (v) { return v.toFixed(3); }); setStyleTransform(this.compassCube, 'perspective(300px) matrix3d(' + roundedMatrix.join() + ')'); } render() { return <div id="compass-cube" className="cube"> <div className="cube-face cube-face-front"> <span className="cube-face-label">Front</span> <div className="cube-button cube-face-button" data-x="0" data-y="0" data-z="0"></div> <div className="cube-face-edge cube-face-edge-top cube-button cube-button-face-edge" data-group="front-top" data-x="45" data-y="0" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-right cube-button cube-button-face-edge" data-group="front-right" data-x="0" data-y="45" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-bottom cube-button cube-button-face-edge" data-group="front-bottom" data-x="-45" data-y="0" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-left cube-button cube-button-face-edge" data-group="front-left" data-x="0" data-y="-45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-right cube-button cube-button-face-corner" data-group="front-top-right" data-x="45" data-y="45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-right cube-button cube-button-face-corner" data-group="front-bottom-right" data-x="-45" data-y="45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-left cube-button cube-button-face-corner" data-group="front-bottom-left" data-x="-45" data-y="-45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-left cube-button cube-button-face-corner" data-group="front-top-left" data-x="45" data-y="-45" data-z="0" data-order="YXZ"></div> </div> <div className="cube-face cube-face-back"> <span className="cube-face-label">Back</span> <div className="cube-button cube-face-button" data-x="0" data-y="180" data-z="0"></div> <div className="cube-face-edge cube-face-edge-top cube-button cube-button-face-edge" data-group="back-top" data-x="45" data-y="180" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-right cube-button cube-button-face-edge" data-group="back-left" data-x="0" data-y="225" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-bottom cube-button cube-button-face-edge" data-group="back-bottom" data-x="-45" data-y="180" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-left cube-button cube-button-face-edge" data-group="back-right" data-x="0" data-y="135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-right cube-button cube-button-face-corner" data-group="back-top-left" data-x="45" data-y="225" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-right cube-button cube-button-face-corner" data-group="back-bottom-left" data-x="-45" data-y="225" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-left cube-button cube-button-face-corner" data-group="back-bottom-right" data-x="-45" data-y="135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-left cube-button cube-button-face-corner" data-group="back-top-right" data-x="45" data-y="135" data-z="0" data-order="YXZ"></div> </div> <div className="cube-face cube-face-right"> <span className="cube-face-label">Right</span> <div className="cube-button cube-face-button" data-x="0" data-y="90" data-z="0"></div> <div className="cube-face-edge cube-face-edge-top cube-button cube-button-face-edge" data-group="top-right" data-x="45" data-y="90" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-right cube-button cube-button-face-edge" data-group="back-right" data-x="0" data-y="135" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-bottom cube-button cube-button-face-edge" data-group="bottom-right" data-x="-45" data-y="90" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-left cube-button cube-button-face-edge" data-group="front-right" data-x="0" data-y="45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-right cube-button cube-button-face-corner" data-group="back-top-right" data-x="45" data-y="135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-right cube-button cube-button-face-corner" data-group="back-bottom-right" data-x="-45" data-y="135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-left cube-button cube-button-face-corner" data-group="front-bottom-right" data-x="-45" data-y="45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-left cube-button cube-button-face-corner" data-group="front-top-right" data-x="45" data-y="45" data-z="0" data-order="YXZ"></div> </div> <div className="cube-face cube-face-left"> <span className="cube-face-label">Left</span> <div className="cube-button cube-face-button" data-x="0" data-y="-90" data-z="0"></div> <div className="cube-face-edge cube-face-edge-top cube-button cube-button-face-edge" data-group="top-left" data-x="45" data-y="-90" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-right cube-button cube-button-face-edge" data-group="front-left" data-x="0" data-y="-45" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-bottom cube-button cube-button-face-edge" data-group="bottom-left" data-x="-45" data-y="-90" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-left cube-button cube-button-face-edge" data-group="back-left" data-x="0" data-y="-135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-right cube-button cube-button-face-corner" data-group="front-top-left" data-x="45" data-y="-45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-right cube-button cube-button-face-corner" data-group="front-bottom-left" data-x="-45" data-y="-45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-left cube-button cube-button-face-corner" data-group="back-bottom-left" data-x="-45" data-y="-135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-left cube-button cube-button-face-corner" data-group="back-top-left" data-x="45" data-y="-135" data-z="0" data-order="YXZ"></div> </div> <div className="cube-face cube-face-top"> <span className="cube-face-label">Top</span> <div className="cube-button cube-face-button" data-x="90" data-y="0" data-z="0" data-up="0,0,1"></div> <div className="cube-face-edge cube-face-edge-top cube-button cube-button-face-edge" data-group="back-top" data-x="45" data-y="180" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-right cube-button cube-button-face-edge" data-group="top-right" data-x="45" data-y="90" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-bottom cube-button cube-button-face-edge" data-group="front-top" data-x="45" data-y="0" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-left cube-button cube-button-face-edge" data-group="top-left" data-x="45" data-y="-90" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-right cube-button cube-button-face-corner" data-group="back-top-right" data-x="45" data-y="135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-right cube-button cube-button-face-corner" data-group="front-top-right" data-x="45" data-y="45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-left cube-button cube-button-face-corner" data-group="front-top-left" data-x="45" data-y="-45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-left cube-button cube-button-face-corner" data-group="back-top-left" data-x="45" data-y="-135" data-z="0" data-order="YXZ"></div> </div> <div className="cube-face cube-face-bottom"> <span className="cube-face-label">Bottom</span> <div className="cube-button cube-face-button" data-x="-90" data-y="0" data-z="0" data-up="0,0,-1"></div> <div className="cube-face-edge cube-face-edge-top cube-button cube-button-face-edge" data-group="front-bottom" data-x="-45" data-y="0" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-right cube-button cube-button-face-edge" data-group="bottom-right" data-x="-45" data-y="90" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-bottom cube-button cube-button-face-edge" data-group="back-bottom" data-x="-45" data-y="180" data-z="0" data-order="YXZ"></div> <div className="cube-face-edge cube-face-edge-left cube-button cube-button-face-edge" data-group="bottom-left" data-x="-45" data-y="-90" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-right cube-button cube-button-face-corner" data-group="front-bottom-right" data-x="-45" data-y="45" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-right cube-button cube-button-face-corner" data-group="back-bottom-right" data-x="-45" data-y="135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-bottom-left cube-button cube-button-face-corner" data-group="back-bottom-left" data-x="-45" data-y="-135" data-z="0" data-order="YXZ"></div> <div className="cube-face-corner cube-face-corner-top-left cube-button cube-button-face-corner" data-group="front-bottom-left" data-x="-45" data-y="-45" data-z="0" data-order="YXZ"></div> </div> </div>; } } CompassView.propTypes = { compassParentId: React.PropTypes.string.isRequired, dispatcher: React.PropTypes.object.isRequired };
src/main/resources/public/js/components/autosuggests/tax-reg-activity-autosuggest.js
SICTIAM/ozwillo-portal
import React from 'react'; import PropTypes from 'prop-types'; import debounce from 'debounce'; import Autosuggest from 'react-autosuggest'; import Config from '../../config/config'; const sizeQueryBeforeFetch = Config.sizeQueryBeforeFetch; class TaxRegActivityAutosuggest extends React.Component { static propTypes = { name: PropTypes.string.isRequired, value: PropTypes.string, placeholder: PropTypes.string, countryUri: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, onTaxRegActivitySelected: PropTypes.func.isRequired, required: PropTypes.bool }; static defaultProps = { value: '', placeholder: '', required: false }; constructor(props) { super(props); this.state = { suggestions: [] }; //bind methods this.searchTaxRegActivities = this.searchTaxRegActivities.bind(this); this.renderSuggestion = this.renderSuggestion.bind(this); this.onSuggestionsFetchRequested = this.onSuggestionsFetchRequested.bind(this); this.onSuggestionsClearRequested = this.onSuggestionsClearRequested.bind(this); this.onSuggestionSelected = this.onSuggestionSelected.bind(this); this.getSuggestionValue = this.getSuggestionValue.bind(this); this.shouldRenderSuggestions = this.shouldRenderSuggestions.bind(this); } componentWillReceiveProps(nextProps) { this.setState({value: nextProps.initialValue}); } searchTaxRegActivities(query) { $.ajax({ url: "/api/store/dc-taxRegActivity", dataType: "json", data: {country_uri: this.props.countryUri, q: query}, type: 'get', success: function (data) { this.setState({suggestions: data.areas}); }.bind(this), error: function (xhr, status, err) { console.error("Error while searching for tax reg activities with query " + query, status, err.toString()) } }) } renderSuggestion(data) { return ( <div> <p className="main-info">{data.name} - {data.label}</p> </div> ) } onSuggestionsFetchRequested({value, reason}) { if (reason !== 'enter' && reason !== 'click') debounce(this.searchTaxRegActivities(value), 500); } onSuggestionsClearRequested() { this.setState({suggestions: []}) } onSuggestionSelected(event, {suggestion}) { this.props.onTaxRegActivitySelected(suggestion); } getSuggestionValue(suggestion) { return suggestion.name || TaxRegActivityAutosuggest.defaultProps.value; } shouldRenderSuggestions(input) { return input && (input.trim().length >= sizeQueryBeforeFetch); } render() { const inputProps = { name: this.props.name, value: this.props.value || TaxRegActivityAutosuggest.defaultProps.value, onChange: this.props.onChange, type: 'search', placeholder: this.props.placeholder || TaxRegActivityAutosuggest.defaultProps.placeholder, className: `form-control ${this.props.className}`, required: this.props.required }; return <Autosuggest suggestions={this.state.suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} renderSuggestion={this.renderSuggestion} getSuggestionValue={this.getSuggestionValue} inputProps={inputProps} shouldRenderSuggestions={this.shouldRenderSuggestions}/> } } export default TaxRegActivityAutosuggest;
frontend/app/components/SearchDialect/SearchDialectMessage.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' import { SEARCH_PART_OF_SPEECH_ANY, SEARCH_DATA_TYPE_PHRASE, SEARCH_DATA_TYPE_WORD, SEARCH_TYPE_DEFAULT_SEARCH, SEARCH_TYPE_APPROXIMATE_SEARCH, SEARCH_TYPE_EXACT_SEARCH, SEARCH_TYPE_CONTAINS_SEARCH, SEARCH_TYPE_STARTS_WITH_SEARCH, SEARCH_TYPE_ENDS_WITH_SEARCH, SEARCH_TYPE_WILDCARD_SEARCH, } from 'common/Constants' /** * @summary SearchDialectPresentation * @version 1.0.1 * @component * * @param {object} props * * @returns {node} jsx markup */ // Generates the 'You are searching ...' message // ------------------------------------------------------------ export const SearchDialectMessage = ({ category, dialectClassName, letter, partOfSpeech, phraseBook, searchDialectDataType, searchStyle, searchTerm, shouldSearchCulturalNotes, shouldSearchDefinitions, shouldSearchLiteralTranslations, shouldSearchTitle, }) => { const cols = [] if (shouldSearchTitle) { switch (searchDialectDataType) { case SEARCH_DATA_TYPE_WORD: cols.push('Word') break case SEARCH_DATA_TYPE_PHRASE: cols.push('Phrase') break default: cols.push('Item') } } if (shouldSearchDefinitions) { cols.push('Definitions') } if (shouldSearchCulturalNotes) { cols.push('Cultural notes') } if (shouldSearchLiteralTranslations) { cols.push('Literal translations') } let dataType switch (searchDialectDataType) { case SEARCH_DATA_TYPE_WORD: dataType = 'words' break case SEARCH_DATA_TYPE_PHRASE: dataType = 'phrases' break default: dataType = 'items' } let searchStyleLabel switch (searchStyle) { case SEARCH_TYPE_DEFAULT_SEARCH: searchStyleLabel = ' match ' break case SEARCH_TYPE_APPROXIMATE_SEARCH: searchStyleLabel = ' approximately match ' break case SEARCH_TYPE_EXACT_SEARCH: searchStyleLabel = ' exactly match ' break case SEARCH_TYPE_CONTAINS_SEARCH: searchStyleLabel = ' contain ' break case SEARCH_TYPE_STARTS_WITH_SEARCH: searchStyleLabel = ' start with ' break case SEARCH_TYPE_ENDS_WITH_SEARCH: searchStyleLabel = ' end with ' break case SEARCH_TYPE_WILDCARD_SEARCH: searchStyleLabel = ' pattern match ' break default: searchStyleLabel = ' contain ' } const searchTermTag = <strong className={dialectClassName}>{searchTerm}</strong> const searchStyleTag = <strong>{searchStyleLabel}</strong> const messagePartsOfSpeech = partOfSpeech && partOfSpeech !== SEARCH_PART_OF_SPEECH_ANY ? ", filtered by the selected 'Parts of speech'" : '' const messages = { // `all` is defined later byCategory: <span>{`Showing all ${dataType} in the selected category${messagePartsOfSpeech}`}</span>, byPhraseBook: <span>{`Showing all ${dataType} from the selected Phrase Book${messagePartsOfSpeech}`}</span>, startWith: ( <span> {`Showing ${dataType} that start with the letter '`} <strong className={dialectClassName}>{letter}</strong> {`'${messagePartsOfSpeech}`} </span> ), contain: ( <span> {`Showing ${dataType} that contain the search term '`} {searchTermTag} {`'${messagePartsOfSpeech}`} </span> ), containColOne: ( <span> {`Showing ${dataType} that `} {searchStyleTag} {" the search term '"} {searchTermTag} {`' in the '${cols[0]}' column${messagePartsOfSpeech}`} </span> ), containColsTwo: ( <span> {`Showing ${dataType} that `} {searchStyleTag} {" the search term '"} {searchTermTag} {`' in the '${cols[0]}' and '${cols[1]}' columns${messagePartsOfSpeech}`} </span> ), containColsThree: ( <span> {`Showing ${dataType} that `} {searchStyleTag} {" the search term '"} {searchTermTag} {`' in the '${cols[0]}', '${cols[1]}', and '${cols[2]}' columns${messagePartsOfSpeech}`} </span> ), } switch (searchDialectDataType) { case SEARCH_DATA_TYPE_WORD: messages.all = ( <span>{`Showing all ${dataType} in the dictionary listed alphabetically${messagePartsOfSpeech}`}</span> ) break case SEARCH_DATA_TYPE_PHRASE: messages.all = <span>{`Showing all ${dataType} listed alphabetically${messagePartsOfSpeech}`}</span> break default: messages.all = <span>{`Showing all ${dataType} listed alphabetically${messagePartsOfSpeech}`}</span> } let msg = messages.all if ( partOfSpeech !== true && shouldSearchTitle !== true && shouldSearchDefinitions !== true && shouldSearchCulturalNotes !== true && shouldSearchLiteralTranslations !== true ) { return <div className="SearchDialectSearchFeedback alert alert-info">{msg}</div> } if (letter) { msg = messages.startWith } else if (category) { msg = messages.byCategory } else if (phraseBook) { msg = messages.byPhraseBook } else if (!searchTerm || searchTerm === '') { msg = messages.all } else { msg = messages.contain if (cols.length === 1) { msg = messages.containColOne } if (cols.length === 2) { msg = messages.containColsTwo } if (cols.length >= 3) { msg = messages.containColsThree } } return <div className="SearchDialectSearchFeedback alert alert-info">{msg}</div> } // PROPTYPES const { bool, number, string } = PropTypes SearchDialectMessage.propTypes = { category: string, dialectClassName: string, letter: string, partOfSpeech: string, phraseBook: string, searchDialectDataType: number, searchStyle: string, searchTerm: string, shouldSearchCulturalNotes: bool, shouldSearchDefinitions: bool, shouldSearchLiteralTranslations: bool, shouldSearchTitle: bool, } export default SearchDialectMessage
src/svg-icons/action/open-in-browser.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionOpenInBrowser = (props) => ( <SvgIcon {...props}> <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z"/> </SvgIcon> ); ActionOpenInBrowser = pure(ActionOpenInBrowser); ActionOpenInBrowser.displayName = 'ActionOpenInBrowser'; export default ActionOpenInBrowser;
src/docs/Navigation.js
StudentOfJS/ps-react-rod
import React from 'react'; import PropTypes from 'prop-types'; const Navigation = ({components}) => { return ( <ul className="navigation"> { components.map( name => { return ( <li key={name}> <a href={`#${name}`}>{name}</a> </li> ) }) } </ul> ) } Navigation.propTypes = { components: PropTypes.array.isRequired }; export default Navigation;
ajax/libs/react-instantsearch/4.0.0-beta.3/Dom.js
him2him2/cdnjs
/*! ReactInstantSearch 4.0.0-beta.3 | © Algolia, inc. | https://community.algolia.com/react-instantsearch/ */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["Dom"] = factory(require("react"), require("react-dom")); else root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Dom"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_429__) { 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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // 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 = 432); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (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; /***/ }), /* 1 */ /***/ (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__(208)(); } /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEqual2 = __webpack_require__(104); var _isEqual3 = _interopRequireDefault(_isEqual2); var _has2 = __webpack_require__(57); 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__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); 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; var store = _context$ais.store; var widgetsManager = _context$ais.widgetsManager; var multiIndexContext = context.multiIndexContext; _this.state = { props: _this.getProvidedProps(props) }; _this.unsubscribe = store.subscribe(function () { _this.setState({ props: _this.getProvidedProps(_this.props) }); }); 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: '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(); var results = _store$getState.results; var searching = _store$getState.searching; var error = _store$getState.error; var widgets = _store$getState.widgets; var metadata = _store$getState.metadata; var resultsFacetValues = _store$getState.resultsFacetValues; var searchState = { results: results, searching: searching, error: error }; 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__(78); /** 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__(73); var _get3 = _interopRequireDefault(_get2); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); var _has2 = __webpack_require__(57); 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 (hasMultipleIndex(context)) { return searchResults.results && 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); } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) { var index = getIndex(context); var refinements = hasMultipleIndex(context) && (0, _has3.default)(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && (0, _has3.default)(searchState, id); if (refinements) { var currentRefinement = hasMultipleIndex(context) ? (0, _get3.default)(searchState.indices[index], id) : (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); return hasMultipleIndex(context) ? (0, _omit3.default)(searchState, 'indices.' + index + '.' + id) : (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__(15), getRawTag = __webpack_require__(157), objectToString = __webpack_require__(184); /** `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__(88), baseKeys = __webpack_require__(76), 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__(136), getValue = __webpack_require__(159); /** * 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__(48); /** * 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__(265), baseMatchesProperty = __webpack_require__(266), identity = __webpack_require__(24), isArray = __webpack_require__(0), property = __webpack_require__(335); /** * 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__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = classNames; var _classnames = __webpack_require__(418); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var prefix = 'ais'; function classNames(block) { return function () { for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) { elements[_key] = arguments[_key]; } return { className: (0, _classnames2.default)(elements.filter(function (element) { return element !== undefined && element !== false; }).map(function (element) { return prefix + '-' + block + '__' + element; })) }; }; } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { var baseKeys = __webpack_require__(76), getTag = __webpack_require__(56), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isArrayLike = __webpack_require__(11), isBuffer = __webpack_require__(26), isPrototype = __webpack_require__(37), isTypedArray = __webpack_require__(36); /** `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; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), baseMap = __webpack_require__(138), isArray = __webpack_require__(0); /** * 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 identity = __webpack_require__(24), overRest = __webpack_require__(185), setToString = __webpack_require__(100); /** * 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; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(0), isKey = __webpack_require__(72), stringToPath = __webpack_require__(196), toString = __webpack_require__(75); /** * 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; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(90), baseAssignValue = __webpack_require__(42); /** * 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; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(27); /** 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; /***/ }), /* 24 */ /***/ (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; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(134), 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; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3), stubFalse = __webpack_require__(206); /** 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__(55)(module))) /***/ }), /* 27 */ /***/ (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; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(169), listCacheDelete = __webpack_require__(170), listCacheGet = __webpack_require__(171), listCacheHas = __webpack_require__(172), listCacheSet = __webpack_require__(173); /** * 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 isKeyable = __webpack_require__(166); /** * 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; /***/ }), /* 31 */ /***/ (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; /***/ }), /* 32 */ /***/ (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; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); 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.default = translatable; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); var _propTypes = __webpack_require__(403); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; } function translatable(defaultTranslations) { return function (Composed) { function Translatable(props) { var translations = props.translations; var otherProps = _objectWithoutProperties(props, ['translations']); var translate = function translate(key) { for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } var translation = translations && (0, _has3.default)(translations, key) ? translations[key] : defaultTranslations[key]; if (typeof translation === 'function') { return translation.apply(undefined, params); } return translation; }; return _react2.default.createElement(Composed, _extends({ translate: translate }, otherProps)); } Translatable.displayName = 'Translatable(' + (0, _utils.getDisplayName)(Composed) + ')'; Translatable.propTypes = { translations: (0, _propTypes.withKeysPropType)(Object.keys(defaultTranslations)) }; return Translatable; }; } /***/ }), /* 34 */ /***/ (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; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(85), baseEach = __webpack_require__(63), castFunction = __webpack_require__(143), isArray = __webpack_require__(0); /** * 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; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(137), baseUnary = __webpack_require__(45), nodeUtil = __webpack_require__(183); /* 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; /***/ }), /* 37 */ /***/ (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; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseClone = __webpack_require__(256), baseUnset = __webpack_require__(278), castPath = __webpack_require__(21), copyObject = __webpack_require__(22), customOmitClone = __webpack_require__(302), flatRest = __webpack_require__(155), getAllKeysIn = __webpack_require__(96); /** 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; /***/ }), /* 39 */ /***/ (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; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(174), mapCacheDelete = __webpack_require__(175), mapCacheGet = __webpack_require__(176), mapCacheHas = __webpack_require__(177), mapCacheSet = __webpack_require__(178); /** * 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; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28), stackClear = __webpack_require__(191), stackDelete = __webpack_require__(192), stackGet = __webpack_require__(193), stackHas = __webpack_require__(194), stackSet = __webpack_require__(195); /** * 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; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(152); /** * 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; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(132), 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; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(130), baseIsNaN = __webpack_require__(263), strictIndexOf = __webpack_require__(317); /** * 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; /***/ }), /* 45 */ /***/ (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; /***/ }), /* 46 */ /***/ (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; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { var createFind = __webpack_require__(298), findIndex = __webpack_require__(198); /** * 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; /***/ }), /* 48 */ /***/ (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; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), getPrototype = __webpack_require__(70), 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; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isArray = __webpack_require__(0), 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; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(88), baseKeysIn = __webpack_require__(264), 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; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { var arrayReduce = __webpack_require__(89), baseEach = __webpack_require__(63), baseIteratee = __webpack_require__(13), baseReduce = __webpack_require__(273), isArray = __webpack_require__(0); /** * 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; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(219); /** * 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; /***/ }), /* 54 */ /***/ (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; /***/ }), /* 55 */ /***/ (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; }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { var DataView = __webpack_require__(122), Map = __webpack_require__(39), Promise = __webpack_require__(125), Set = __webpack_require__(126), WeakMap = __webpack_require__(84), baseGetTag = __webpack_require__(8), toSource = __webpack_require__(80); /** `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; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(133), hasPath = __webpack_require__(97); /** * 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; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defer = undefined; var _isPlainObject2 = __webpack_require__(49); var _isPlainObject3 = _interopRequireDefault(_isPlainObject2); var _isEmpty2 = __webpack_require__(16); 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; } /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(40), setCacheAdd = __webpack_require__(186), setCacheHas = __webpack_require__(187); /** * * 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; /***/ }), /* 60 */ /***/ (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; /***/ }), /* 61 */ /***/ (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; /***/ }), /* 62 */ /***/ (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; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43), createBaseEach = __webpack_require__(294); /** * 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; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), toKey = __webpack_require__(23); /** * 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; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(135), 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; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), arrayMap = __webpack_require__(12), isArray = __webpack_require__(0), isSymbol = __webpack_require__(27); /** 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) { /** * 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; /***/ }), /* 68 */ /***/ (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; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), 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; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(79); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(86), stubArray = __webpack_require__(107); /** 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; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(0), isSymbol = __webpack_require__(27); /** 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; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64); /** * 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; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44), toInteger = __webpack_require__(53); /* 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 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; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(37), nativeKeys = __webpack_require__(182); /** 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; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arraySome = __webpack_require__(128), cacheHas = __webpack_require__(67); /** 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; /***/ }), /* 78 */ /***/ (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__(54))) /***/ }), /* 79 */ /***/ (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; /***/ }), /* 80 */ /***/ (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; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var keys = __webpack_require__(9); var intersection = __webpack_require__(328); var forOwn = __webpack_require__(326); var forEach = __webpack_require__(35); var filter = __webpack_require__(102); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var omit = __webpack_require__(38); var indexOf = __webpack_require__(74); var isNaN = __webpack_require__(218); var isArray = __webpack_require__(0); var isEmpty = __webpack_require__(16); var isEqual = __webpack_require__(104); var isUndefined = __webpack_require__(203); var isString = __webpack_require__(50); var isFunction = __webpack_require__(19); var find = __webpack_require__(47); var trim = __webpack_require__(207); var defaults = __webpack_require__(101); var merge = __webpack_require__(105); var valToNumber = __webpack_require__(246); var filterState = __webpack_require__(242); var RefinementList = __webpack_require__(241); /** * 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 `facetFiters` 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 `facetFiters` 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 `facetFiters` 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 * seperated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` 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 facetted 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] optionnal 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) facetting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive facetting * @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 facetting * @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 facetting * @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 facetting * @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 facetting * @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 facetting * @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 facetting * @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] optionnal 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 facetting 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 facetting 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 facetted attribute. * @method * @param {string} facet name of the attribute used for facetting * @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 facetting * @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 facetting * @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 facetting * @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 facetting * @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 facetting * @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 facetting * @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 facetting * @param {string} value, optionnal 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 facetting * @param {string} [value] optionnal 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 facetting * @param {string} value optionnal, 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 facetting * @param {string} value optionnal, 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 facetting * @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 facetting * @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; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), baseLodash = __webpack_require__(92); /** 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; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }), /* 84 */ /***/ (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; /***/ }), /* 85 */ /***/ (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; /***/ }), /* 86 */ /***/ (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; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * 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; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(142), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isIndex = __webpack_require__(31), isTypedArray = __webpack_require__(36); /** 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; /***/ }), /* 89 */ /***/ (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; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), 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; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), isArray = __webpack_require__(0); /** * 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; /***/ }), /* 92 */ /***/ (function(module, exports) { /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } module.exports = baseLodash; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { var Uint8Array = __webpack_require__(83); /** * 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; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(140), createBind = __webpack_require__(296), createCurry = __webpack_require__(297), createHybrid = __webpack_require__(150), createPartial = __webpack_require__(300), getData = __webpack_require__(156), mergeData = __webpack_require__(312), setData = __webpack_require__(188), setWrapToString = __webpack_require__(189), toInteger = __webpack_require__(53); /** 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; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(91), getSymbols = __webpack_require__(71), 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; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(91), getSymbolsIn = __webpack_require__(158), keysIn = __webpack_require__(51); /** * 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; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isIndex = __webpack_require__(31), isLength = __webpack_require__(48), toKey = __webpack_require__(23); /** * 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; /***/ }), /* 98 */ /***/ (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; /***/ }), /* 99 */ /***/ (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; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(275), shortOut = __webpack_require__(190); /** * 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; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), assignInWith = __webpack_require__(322), baseRest = __webpack_require__(20), customDefaultsAssignIn = __webpack_require__(301); /** * 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; /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(86), baseFilter = __webpack_require__(258), baseIteratee = __webpack_require__(13), isArray = __webpack_require__(0); /** * 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; /***/ }), /* 103 */ /***/ (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; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(65); /** * 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; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { var baseMerge = __webpack_require__(267), createAssigner = __webpack_require__(149); /** * 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; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { var baseOrderBy = __webpack_require__(269), isArray = __webpack_require__(0); /** * 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; /***/ }), /* 107 */ /***/ (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; /***/ }), /* 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') { 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 (Object.prototype.hasOwnProperty.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; 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.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) { var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { var basePick = __webpack_require__(270), flatRest = __webpack_require__(155); /** * 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; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); 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; var 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; var max = props.max; var hasMin = typeof min !== 'undefined'; var hasMax = typeof max !== 'undefined'; var index = (0, _indexUtils.getIndex)(this.context); 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); var _getCurrentRefinement2 = _getCurrentRefinement.min; var valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2; var _getCurrentRefinement3 = _getCurrentRefinement.max; var 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; var 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] : [] }; } }); /***/ }), /* 113 */ /***/ (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; } /***/ }), /* 114 */ /***/ (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__(239); 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__(238); 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__(54), __webpack_require__(109))) /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var compact = __webpack_require__(324); var indexOf = __webpack_require__(74); var findIndex = __webpack_require__(198); var get = __webpack_require__(73); var sumBy = __webpack_require__(337); var find = __webpack_require__(47); var includes = __webpack_require__(327); var map = __webpack_require__(17); var orderBy = __webpack_require__(106); var defaults = __webpack_require__(101); var merge = __webpack_require__(105); var isArray = __webpack_require__(0); var isFunction = __webpack_require__(19); var partial = __webpack_require__(332); var partialRight = __webpack_require__(333); var formatSort = __webpack_require__(116); var generateHierarchicalTree = __webpack_require__(244); /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the facetting 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 objets 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 fitlers. * @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. * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * 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 attribute facetted * @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 facetted 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 facetted 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; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var reduce = __webpack_require__(52); var find = __webpack_require__(47); var startsWith = __webpack_require__(336); /** * 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; }, [[], []]); }; /***/ }), /* 117 */ /***/ (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__(243); var SearchParameters = __webpack_require__(81); var qs = __webpack_require__(342); var bind = __webpack_require__(323); var forEach = __webpack_require__(35); var pick = __webpack_require__(111); var map = __webpack_require__(17); var mapKeys = __webpack_require__(329); var mapValues = __webpack_require__(330); var isString = __webpack_require__(50); var isPlainObject = __webpack_require__(49); var isArray = __webpack_require__(0); var invert = __webpack_require__(201); 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 (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}); }; /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = '2.19.0'; /***/ }), /* 119 */ /***/ (function(module, exports) { module.exports = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; /***/ }), /* 120 */ /***/ (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; /***/ }), /* 121 */ /***/ (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; /***/ }), /* 122 */ /***/ (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; /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(160), hashDelete = __webpack_require__(161), hashGet = __webpack_require__(162), hashHas = __webpack_require__(163), hashSet = __webpack_require__(164); /** * 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; /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), baseLodash = __webpack_require__(92); /** * 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; /***/ }), /* 125 */ /***/ (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; /***/ }), /* 126 */ /***/ (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; /***/ }), /* 127 */ /***/ (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; /***/ }), /* 128 */ /***/ (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; /***/ }), /* 129 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), 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; /***/ }), /* 130 */ /***/ (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; /***/ }), /* 131 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), isFlattenable = __webpack_require__(310); /** * 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; /***/ }), /* 132 */ /***/ (function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(295); /** * 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; /***/ }), /* 133 */ /***/ (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; /***/ }), /* 134 */ /***/ (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; /***/ }), /* 135 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), equalArrays = __webpack_require__(77), equalByTag = __webpack_require__(153), equalObjects = __webpack_require__(154), getTag = __webpack_require__(56), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isTypedArray = __webpack_require__(36); /** 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; /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isMasked = __webpack_require__(167), isObject = __webpack_require__(6), toSource = __webpack_require__(80); /** * 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; /***/ }), /* 137 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isLength = __webpack_require__(48), 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; /***/ }), /* 138 */ /***/ (function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(63), 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; /***/ }), /* 139 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64), baseSet = __webpack_require__(274), castPath = __webpack_require__(21); /** * 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; /***/ }), /* 140 */ /***/ (function(module, exports, __webpack_require__) { var identity = __webpack_require__(24), metaMap = __webpack_require__(181); /** * 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; /***/ }), /* 141 */ /***/ (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; /***/ }), /* 142 */ /***/ (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; /***/ }), /* 143 */ /***/ (function(module, exports, __webpack_require__) { var identity = __webpack_require__(24); /** * 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; /***/ }), /* 144 */ /***/ (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__(55)(module))) /***/ }), /* 145 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93); /** * 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; /***/ }), /* 146 */ /***/ (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; /***/ }), /* 147 */ /***/ (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; /***/ }), /* 148 */ /***/ (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; /***/ }), /* 149 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), isIterateeCall = __webpack_require__(217); /** * 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; /***/ }), /* 150 */ /***/ (function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(146), composeArgsRight = __webpack_require__(147), countHolders = __webpack_require__(293), createCtor = __webpack_require__(69), createRecurry = __webpack_require__(151), getHolder = __webpack_require__(46), reorder = __webpack_require__(316), replaceHolders = __webpack_require__(34), 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; /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { var isLaziable = __webpack_require__(311), setData = __webpack_require__(188), setWrapToString = __webpack_require__(189); /** 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; /***/ }), /* 152 */ /***/ (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; /***/ }), /* 153 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), Uint8Array = __webpack_require__(83), eq = __webpack_require__(18), equalArrays = __webpack_require__(77), mapToArray = __webpack_require__(98), setToArray = __webpack_require__(99); /** 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; /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { var getAllKeys = __webpack_require__(95); /** 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; /***/ }), /* 155 */ /***/ (function(module, exports, __webpack_require__) { var flatten = __webpack_require__(199), overRest = __webpack_require__(185), setToString = __webpack_require__(100); /** * 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; /***/ }), /* 156 */ /***/ (function(module, exports, __webpack_require__) { var metaMap = __webpack_require__(181), noop = __webpack_require__(331); /** * 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; /***/ }), /* 157 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** 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; /***/ }), /* 158 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), getPrototype = __webpack_require__(70), getSymbols = __webpack_require__(71), stubArray = __webpack_require__(107); /* 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; /***/ }), /* 159 */ /***/ (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; /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** * 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; /***/ }), /* 161 */ /***/ (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; /***/ }), /* 162 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 164 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 165 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), getPrototype = __webpack_require__(70), isPrototype = __webpack_require__(37); /** * 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; /***/ }), /* 166 */ /***/ (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; /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(148); /** 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; /***/ }), /* 168 */ /***/ (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; /***/ }), /* 169 */ /***/ (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; /***/ }), /* 170 */ /***/ (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; /***/ }), /* 171 */ /***/ (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; /***/ }), /* 172 */ /***/ (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; /***/ }), /* 173 */ /***/ (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; /***/ }), /* 174 */ /***/ (function(module, exports, __webpack_require__) { var Hash = __webpack_require__(123), ListCache = __webpack_require__(28), Map = __webpack_require__(39); /** * 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; /***/ }), /* 175 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 177 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 178 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 179 */ /***/ (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; /***/ }), /* 180 */ /***/ (function(module, exports, __webpack_require__) { var memoize = __webpack_require__(205); /** 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; /***/ }), /* 181 */ /***/ (function(module, exports, __webpack_require__) { var WeakMap = __webpack_require__(84); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; module.exports = metaMap; /***/ }), /* 182 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(79); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }), /* 183 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(78); /** 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__(55)(module))) /***/ }), /* 184 */ /***/ (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; /***/ }), /* 185 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60); /* 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; /***/ }), /* 186 */ /***/ (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; /***/ }), /* 187 */ /***/ (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; /***/ }), /* 188 */ /***/ (function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(140), shortOut = __webpack_require__(190); /** * 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; /***/ }), /* 189 */ /***/ (function(module, exports, __webpack_require__) { var getWrapDetails = __webpack_require__(305), insertWrapDetails = __webpack_require__(309), setToString = __webpack_require__(100), updateWrapDetails = __webpack_require__(320); /** * 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; /***/ }), /* 190 */ /***/ (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; /***/ }), /* 191 */ /***/ (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; /***/ }), /* 192 */ /***/ (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; /***/ }), /* 193 */ /***/ (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; /***/ }), /* 194 */ /***/ (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; /***/ }), /* 195 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28), Map = __webpack_require__(39), MapCache = __webpack_require__(40); /** 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; /***/ }), /* 196 */ /***/ (function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(180); /** 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; /***/ }), /* 197 */ /***/ (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; /***/ }), /* 198 */ /***/ (function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(130), baseIteratee = __webpack_require__(13), toInteger = __webpack_require__(53); /* 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; /***/ }), /* 199 */ /***/ (function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(131); /** * 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; /***/ }), /* 200 */ /***/ (function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(259), hasPath = __webpack_require__(97); /** * 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; /***/ }), /* 201 */ /***/ (function(module, exports, __webpack_require__) { var constant = __webpack_require__(197), createInverter = __webpack_require__(299), identity = __webpack_require__(24); /** * 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; /***/ }), /* 202 */ /***/ (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; /***/ }), /* 203 */ /***/ (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; /***/ }), /* 204 */ /***/ (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; /***/ }), /* 205 */ /***/ (function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(40); /** 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; /***/ }), /* 206 */ /***/ (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; /***/ }), /* 207 */ /***/ (function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(66), castSlice = __webpack_require__(281), charsEndIndex = __webpack_require__(282), charsStartIndex = __webpack_require__(283), stringToArray = __webpack_require__(318), toString = __webpack_require__(75); /** 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; /***/ }), /* 208 */ /***/ (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__(120); var invariant = __webpack_require__(121); module.exports = function() { // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. function shim() { 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; }; 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; }; /***/ }), /* 209 */ /***/ (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' }; /***/ }), /* 210 */ /***/ (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__(1); 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); } }); /***/ }), /* 211 */ /***/ (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__(237); var _highlight2 = _interopRequireDefault(_highlight); var _highlightTags = __webpack_require__(213); var _highlightTags2 = _interopRequireDefault(_highlightTags); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var highlight = function highlight(_ref) { var attributeName = _ref.attributeName; var hit = _ref.hit; var 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 * const CustomHighlight = connectHighlight(({highlight, attributeName, hit, highlightProperty) => { * const parsedHit = highlight({attributeName, hit, highlightProperty}); * return parsedHit.map(part => { * if(part.isHighlighted) return <em>{part.value}</em>; * return part.value: * }); * }); */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /***/ }), /* 212 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _SearchBox = __webpack_require__(346); var _SearchBox2 = _interopRequireDefault(_SearchBox); 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; } var itemsPropType = _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.any, label: _propTypes2.default.string.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var List = function (_Component) { _inherits(List, _Component); function List() { _classCallCheck(this, List); var _this = _possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this)); _this.defaultProps = { isFromSearch: false }; _this.onShowMoreClick = function () { _this.setState(function (state) { return { extended: !state.extended }; }); }; _this.getLimit = function () { var _this$props = _this.props; var limitMin = _this$props.limitMin; var limitMax = _this$props.limitMax; var extended = _this.state.extended; return extended ? limitMax : limitMin; }; _this.resetQuery = function () { _this.setState({ query: '' }); }; _this.renderItem = function (item, resetQuery) { var items = item.items && _react2.default.createElement( 'div', _this.props.cx('itemItems'), item.items.slice(0, _this.getLimit()).map(function (child) { return _this.renderItem(child, item); }) ); return _react2.default.createElement( 'div', _extends({ key: item.key || item.label }, _this.props.cx('item', item.isRefined && 'itemSelected', item.noRefinement && 'itemNoRefinement', items && 'itemParent', items && item.isRefined && 'itemSelectedParent')), _this.props.renderItem(item, resetQuery), items ); }; _this.state = { extended: false, query: '' }; return _this; } _createClass(List, [{ key: 'renderShowMore', value: function renderShowMore() { var _props = this.props; var showMore = _props.showMore; var translate = _props.translate; var cx = _props.cx; var extended = this.state.extended; var disabled = this.props.limitMin >= this.props.items.length; if (!showMore) { return null; } return _react2.default.createElement( 'button', _extends({ disabled: disabled }, cx('showMore', disabled && 'showMoreDisabled'), { onClick: this.onShowMoreClick }), translate('showMore', extended) ); } }, { key: 'renderSearchBox', value: function renderSearchBox() { var _this2 = this; var _props2 = this.props; var cx = _props2.cx; var searchForItems = _props2.searchForItems; var isFromSearch = _props2.isFromSearch; var translate = _props2.translate; var items = _props2.items; var selectItem = _props2.selectItem; var noResults = items.length === 0 && this.state.query !== '' ? _react2.default.createElement( 'div', cx('noResults'), translate('noResults') ) : null; return _react2.default.createElement( 'div', cx('SearchBox'), _react2.default.createElement(_SearchBox2.default, { currentRefinement: this.state.query, refine: function refine(value) { _this2.setState({ query: value }); searchForItems(value); }, focusShortcuts: [], translate: translate, onSubmit: function onSubmit(e) { e.preventDefault(); e.stopPropagation(); if (isFromSearch) { selectItem(items[0], _this2.resetQuery); } } }), noResults ); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props; var cx = _props3.cx; var items = _props3.items; var withSearchBox = _props3.withSearchBox; var canRefine = _props3.canRefine; var searchBox = withSearchBox ? this.renderSearchBox() : null; if (items.length === 0) { return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), searchBox ); } // Always limit the number of items we show on screen, since the actual // number of retrieved items might vary with the `maxValuesPerFacet` config // option. var limit = this.getLimit(); return _react2.default.createElement( 'div', cx('root', !this.props.canRefine && 'noRefinement'), searchBox, _react2.default.createElement( 'div', cx('items'), items.slice(0, limit).map(function (item) { return _this3.renderItem(item, _this3.resetQuery); }) ), this.renderShowMore() ); } }]); return List; }(_react.Component); List.propTypes = { cx: _propTypes2.default.func.isRequired, // Only required with showMore. translate: _propTypes2.default.func, items: itemsPropType, renderItem: _propTypes2.default.func.isRequired, selectItem: _propTypes2.default.func, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, limit: _propTypes2.default.number, show: _propTypes2.default.func, searchForItems: _propTypes2.default.func, withSearchBox: _propTypes2.default.bool, isFromSearch: _propTypes2.default.bool, canRefine: _propTypes2.default.bool }; exports.default = List; /***/ }), /* 213 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var timestamp = Date.now().toString(); exports.default = { highlightPreTag: "<ais-highlight-" + timestamp + ">", highlightPostTag: "</ais-highlight-" + timestamp + ">" }; /***/ }), /* 214 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var AlgoliaSearchHelper = __webpack_require__(245); var SearchParameters = __webpack_require__(81); var SearchResults = __webpack_require__(115); /** * 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__(118); /** * 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__(117); module.exports = algoliasearchHelper; /***/ }), /* 215 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // This file hosts our error definitions // We use custom error "types" so that we can act on them when we need it // e.g.: if error instanceof errors.UnparsableJSON then.. var inherits = __webpack_require__(349); function AlgoliaSearchError(message, extraProperties) { var forEach = __webpack_require__(110); var error = this; // try to get a stacktrace if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old'; } this.name = 'AlgoliaSearchError'; this.message = message || 'Unknown error'; if (extraProperties) { forEach(extraProperties, function addToErrorObject(value, key) { error[key] = value; }); } } inherits(AlgoliaSearchError, Error); function createCustomError(name, message) { function AlgoliaSearchCustomError() { var args = Array.prototype.slice.call(arguments, 0); // custom message not set, use default if (typeof args[0] !== 'string') { args.unshift(message); } AlgoliaSearchError.apply(this, args); this.name = 'AlgoliaSearch' + name + 'Error'; } inherits(AlgoliaSearchCustomError, AlgoliaSearchError); return AlgoliaSearchCustomError; } // late exports to let various fn defs and inherits take place module.exports = { AlgoliaSearchError: AlgoliaSearchError, UnparsableJSON: createCustomError( 'UnparsableJSON', 'Could not parse the incoming response as JSON, see err.more for details' ), RequestTimeout: createCustomError( 'RequestTimeout', 'Request timedout before getting a response' ), Network: createCustomError( 'Network', 'Network issue, see err.more for details' ), JSONPScriptFail: createCustomError( 'JSONPScriptFail', '<script> was loaded but did not call our provided callback' ), JSONPScriptError: createCustomError( 'JSONPScriptError', '<script> unable to load due to an `error` event on it' ), Unknown: createCustomError( 'Unknown', 'Unknown error occured' ) }; /***/ }), /* 216 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __webpack_require__(419); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109))) /***/ }), /* 217 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(18), isArrayLike = __webpack_require__(11), isIndex = __webpack_require__(31), 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; /***/ }), /* 218 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(202); /** * 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; /***/ }), /* 219 */ /***/ (function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(338); /** 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; /***/ }), /* 220 */ /***/ (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__(325); var _difference3 = _interopRequireDefault(_difference2); var _omit2 = __webpack_require__(38); 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[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); } }); /***/ }), /* 221 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getId = undefined; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _algoliasearchHelper = __webpack_require__(214); 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; var attributes = props.attributes; var separator = props.separator; var rootPath = props.rootPath; var 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; var limitMin = props.limitMin; var limitMax = props.limitMax; var id = getId(props); var index = (0, _indexUtils.getIndex)(this.context); 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; var separator = props.separator; var rootPath = props.rootPath; var showParentLevel = props.showParentLevel; var showMore = props.showMore; var limitMin = props.limitMin; var 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 }] }; } }); /***/ }), /* 222 */ /***/ (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 index = (0, _indexUtils.getIndex)(this.context); 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; } }); /***/ }), /* 223 */ /***/ (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__(1); 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() }; } }); /***/ }), /* 224 */ /***/ (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 index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!results) { this._allResults = []; return { hits: this._allResults, hasMore: false }; } var hits = results.hits; var page = results.page; var nbPages = results.nbPages; var hitsPerPage = results.hitsPerPage; if (page === 0) { this._allResults = hits; } else { var previousPage = this._allResults.length / hitsPerPage - 1; if (page > previousPage) { this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hits)); } else if (page < previousPage) { this._allResults = hits; } // If it is the same page we do not touch the page result list } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; 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); } }); /***/ }), /* 225 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _orderBy2 = __webpack_require__(106); var _orderBy3 = _interopRequireDefault(_orderBy2); var _propTypes = __webpack_require__(1); 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 tha 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 }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var index = (0, _indexUtils.getIndex)(this.context); 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; var showMore = props.showMore; var limitMin = props.limitMin; var 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 }] }; } }); /***/ }), /* 226 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _find3 = __webpack_require__(47); 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__(1); 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(':'); var _value$split2 = _slicedToArray(_value$split, 2); var startStr = _value$split2[0]; var 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 index = (0, _indexUtils.getIndex)(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)); var start = _parseItem.start; var 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; }); var 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 }; } }); /***/ }), /* 227 */ /***/ (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 index = (0, _indexUtils.getIndex)(this.context); 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() }; } }); /***/ }), /* 228 */ /***/ (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() { var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + location.hostname + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); /***/ }), /* 229 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); 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; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var index = (0, _indexUtils.getIndex)(this.context); 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; var operator = props.operator; var showMore = props.showMore; var limitMin = props.limitMin; var 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); } }; }) }] : [] }; } }); /***/ }), /* 230 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); 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 }; } /** * 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 */ 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; }); return { value: value }; } }); /***/ }), /* 231 */ /***/ (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__(1); 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 }] }; } }); /***/ }), /* 232 */ /***/ (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__(1); 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; }); } /** * connectSortBy connector provides the logic to build a widget that will * displays a list of indexes allowing a user to change the hits are sorting. * @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() }; } }); /***/ }), /* 233 */ /***/ (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 index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); /***/ }), /* 234 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); 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 null; }); } 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} [defaultChecked=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; var value = props.value; var 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 }; } }); /***/ }), /* 235 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(211); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Highlight = __webpack_require__(380); var _Highlight2 = _interopRequireDefault(_Highlight); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Renders any attribute from an hit into its highlighted form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Highlight * @kind widget * @propType {string} attributeName - the location of the highlighted attribute in the hit * @propType {object} hit - the hit object containing the highlighted attribute * @propType {string} [tagName='em'] - the tag to be used for highlighted parts of the hit * @example * import React from 'react'; * * import {InstantSearch, connectHits, Highlight} from 'InstantSearch'; * * const CustomHits = connectHits(hits => { * return hits.map((hit) => <p><Highlight attributeName="description" hit={hit}/></p>); * }); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHighlight2.default)(_Highlight2.default); /***/ }), /* 236 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(38); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); 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; } var Link = function (_Component) { _inherits(Link, _Component); function Link() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) { if ((0, _utils.isSpecialClick)(e)) { return; } _this.props.onClick(); e.preventDefault(); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Link, [{ key: 'render', value: function render() { return _react2.default.createElement('a', _extends({}, (0, _omit3.default)(this.props, 'onClick'), { onClick: this.onClick })); } }]); return Link; }(_react.Component); Link.propTypes = { onClick: _propTypes2.default.func.isRequired }; exports.default = Link; /***/ }), /* 237 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _get2 = __webpack_require__(73); 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; var preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag; var _ref$postTag = _ref.postTag; var postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag; var highlightProperty = _ref.highlightProperty; var attributeName = _ref.attributeName; var 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; var postTag = _ref2.postTag; var 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; } /***/ }), /* 238 */ /***/ (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 } } /***/ }), /* 239 */ /***/ (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'; } /***/ }), /* 240 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util = __webpack_require__(114); var events = __webpack_require__(113); /** * 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; /***/ }), /* 241 */ /***/ (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__(203); var isString = __webpack_require__(50); var isFunction = __webpack_require__(19); var isEmpty = __webpack_require__(16); var defaults = __webpack_require__(101); var reduce = __webpack_require__(52); var filter = __webpack_require__(102); var omit = __webpack_require__(38); 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 prefinement 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 * behaviors 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] optionnal 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; /***/ }), /* 242 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var filter = __webpack_require__(102); var map = __webpack_require__(17); var isEmpty = __webpack_require__(16); 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; /***/ }), /* 243 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var invert = __webpack_require__(201); 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]; } }; /***/ }), /* 244 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = generateTrees; var last = __webpack_require__(204); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var orderBy = __webpack_require__(106); var trim = __webpack_require__(207); var find = __webpack_require__(47); var pickBy = __webpack_require__(334); var prepareHierarchicalFacetSortBy = __webpack_require__(116); 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 }; }; } /***/ }), /* 245 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var SearchParameters = __webpack_require__(81); var SearchResults = __webpack_require__(115); var DerivedHelper = __webpack_require__(240); var requestBuilder = __webpack_require__(247); var util = __webpack_require__(114); var events = __webpack_require__(113); var flatten = __webpack_require__(199); var forEach = __webpack_require__(35); var isEmpty = __webpack_require__(16); var map = __webpack_require__(17); var url = __webpack_require__(117); var version = __webpack_require__(118); /** * 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 the 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 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.'); * }); */ /** * 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 = []; } 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 occcurs, 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 occured 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); if (cb) { return this.client.search( queries, function(err, content) { if (err) cb(err, null, tempState); else cb(err, new SearchResults(tempState, content.results), tempState); } ); } return this.client.search(queries).then(function(content) { return { content: new SearchResults(tempState, content.results), state: tempState, _originalResponse: content }; }); }; /** * 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 occurence 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 {objet} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query insde the engine */ /** * Search for facet values based on an query and the name of a facetted attribute. This * triggers a search and will retrun a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} query the string query for the search * @param {string} facet the name of the facetted attribute * @return {promise<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query) { var state = this.state; var index = this.client.initIndex(this.state.index); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, this.state); return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) { content.facetHits = forEach(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }); }; /** * 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 facetted 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 facetted 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 facetted 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 optionnals, triggering different behaviors: * - 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 facetted 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 facetted 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 facetted 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 facetted 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 facetted 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 facetted 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] optionnal 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 optionnal 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 facetted 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 facetting * @param {string} [value] optionnal 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 facetting * @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.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId)); }; /** * Transform the responses as sent by the server and transform them into a user * usable objet 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) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._lastQueryIdReceived = queryId; if (err) { this.emit('error', err); return; } 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); }; /** * @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 facetting 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; /***/ }), /* 246 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var map = __webpack_require__(17); var isArray = __webpack_require__(0); var isNumber = __webpack_require__(202); var isString = __webpack_require__(50); 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; /***/ }), /* 247 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var merge = __webpack_require__(105); var isArray = __webpack_require__(0); 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, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var queries = merge(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), { facetQuery: query, facetName: facetName }); return queries; } }; module.exports = requestBuilder; /***/ }), /* 248 */ /***/ (function(module, exports, __webpack_require__) { var foreach = __webpack_require__(110); module.exports = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; /***/ }), /* 249 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /* 250 */ /***/ (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; /***/ }), /* 251 */ /***/ (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; /***/ }), /* 252 */ /***/ (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; /***/ }), /* 253 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), 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; /***/ }), /* 254 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), keysIn = __webpack_require__(51); /** * 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; /***/ }), /* 255 */ /***/ (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; /***/ }), /* 256 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), arrayEach = __webpack_require__(85), assignValue = __webpack_require__(90), baseAssign = __webpack_require__(253), baseAssignIn = __webpack_require__(254), cloneBuffer = __webpack_require__(144), copyArray = __webpack_require__(68), copySymbols = __webpack_require__(291), copySymbolsIn = __webpack_require__(292), getAllKeys = __webpack_require__(95), getAllKeysIn = __webpack_require__(96), getTag = __webpack_require__(56), initCloneArray = __webpack_require__(307), initCloneByTag = __webpack_require__(308), initCloneObject = __webpack_require__(165), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), 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; /***/ }), /* 257 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arrayIncludes = __webpack_require__(87), arrayIncludesWith = __webpack_require__(127), arrayMap = __webpack_require__(12), baseUnary = __webpack_require__(45), cacheHas = __webpack_require__(67); /** 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; /***/ }), /* 258 */ /***/ (function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(63); /** * 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; /***/ }), /* 259 */ /***/ (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; /***/ }), /* 260 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arrayIncludes = __webpack_require__(87), arrayIncludesWith = __webpack_require__(127), arrayMap = __webpack_require__(12), baseUnary = __webpack_require__(45), cacheHas = __webpack_require__(67); /* 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; /***/ }), /* 261 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43); /** * 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; /***/ }), /* 262 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), baseIsEqual = __webpack_require__(65); /** 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; /***/ }), /* 263 */ /***/ (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; /***/ }), /* 264 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6), isPrototype = __webpack_require__(37), nativeKeysIn = __webpack_require__(313); /** 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; /***/ }), /* 265 */ /***/ (function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(262), getMatchData = __webpack_require__(304), matchesStrictComparable = __webpack_require__(179); /** * 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; /***/ }), /* 266 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(65), get = __webpack_require__(73), hasIn = __webpack_require__(200), isKey = __webpack_require__(72), isStrictComparable = __webpack_require__(168), matchesStrictComparable = __webpack_require__(179), toKey = __webpack_require__(23); /** 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; /***/ }), /* 267 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), assignMergeValue = __webpack_require__(129), baseFor = __webpack_require__(132), baseMergeDeep = __webpack_require__(268), isObject = __webpack_require__(6), keysIn = __webpack_require__(51); /** * 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; /***/ }), /* 268 */ /***/ (function(module, exports, __webpack_require__) { var assignMergeValue = __webpack_require__(129), cloneBuffer = __webpack_require__(144), cloneTypedArray = __webpack_require__(145), copyArray = __webpack_require__(68), initCloneObject = __webpack_require__(165), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isArrayLikeObject = __webpack_require__(103), isBuffer = __webpack_require__(26), isFunction = __webpack_require__(19), isObject = __webpack_require__(6), isPlainObject = __webpack_require__(49), isTypedArray = __webpack_require__(36), toPlainObject = __webpack_require__(339); /** * 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; /***/ }), /* 269 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), baseMap = __webpack_require__(138), baseSortBy = __webpack_require__(276), baseUnary = __webpack_require__(45), compareMultiple = __webpack_require__(290), identity = __webpack_require__(24); /** * 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; /***/ }), /* 270 */ /***/ (function(module, exports, __webpack_require__) { var basePickBy = __webpack_require__(139), hasIn = __webpack_require__(200); /** * 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; /***/ }), /* 271 */ /***/ (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; /***/ }), /* 272 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64); /** * 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; /***/ }), /* 273 */ /***/ (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; /***/ }), /* 274 */ /***/ (function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(90), castPath = __webpack_require__(21), isIndex = __webpack_require__(31), isObject = __webpack_require__(6), toKey = __webpack_require__(23); /** * 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; /***/ }), /* 275 */ /***/ (function(module, exports, __webpack_require__) { var constant = __webpack_require__(197), defineProperty = __webpack_require__(152), identity = __webpack_require__(24); /** * 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; /***/ }), /* 276 */ /***/ (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; /***/ }), /* 277 */ /***/ (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; /***/ }), /* 278 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), last = __webpack_require__(204), parent = __webpack_require__(314), toKey = __webpack_require__(23); /** * 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; /***/ }), /* 279 */ /***/ (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; /***/ }), /* 280 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(103); /** * 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; /***/ }), /* 281 */ /***/ (function(module, exports, __webpack_require__) { var baseSlice = __webpack_require__(141); /** * 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; /***/ }), /* 282 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * 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; /***/ }), /* 283 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * 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; /***/ }), /* 284 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93); /** * 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; /***/ }), /* 285 */ /***/ (function(module, exports, __webpack_require__) { var addMapEntry = __webpack_require__(250), arrayReduce = __webpack_require__(89), mapToArray = __webpack_require__(98); /** 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; /***/ }), /* 286 */ /***/ (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; /***/ }), /* 287 */ /***/ (function(module, exports, __webpack_require__) { var addSetEntry = __webpack_require__(251), arrayReduce = __webpack_require__(89), setToArray = __webpack_require__(99); /** 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; /***/ }), /* 288 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** 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; /***/ }), /* 289 */ /***/ (function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(27); /** * 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; /***/ }), /* 290 */ /***/ (function(module, exports, __webpack_require__) { var compareAscending = __webpack_require__(289); /** * 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; /***/ }), /* 291 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), getSymbols = __webpack_require__(71); /** * 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; /***/ }), /* 292 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), getSymbolsIn = __webpack_require__(158); /** * 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; /***/ }), /* 293 */ /***/ (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; /***/ }), /* 294 */ /***/ (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; /***/ }), /* 295 */ /***/ (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; /***/ }), /* 296 */ /***/ (function(module, exports, __webpack_require__) { var createCtor = __webpack_require__(69), 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; /***/ }), /* 297 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), createCtor = __webpack_require__(69), createHybrid = __webpack_require__(150), createRecurry = __webpack_require__(151), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34), 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; /***/ }), /* 298 */ /***/ (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; /***/ }), /* 299 */ /***/ (function(module, exports, __webpack_require__) { var baseInverter = __webpack_require__(261); /** * 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; /***/ }), /* 300 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), createCtor = __webpack_require__(69), 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; /***/ }), /* 301 */ /***/ (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; /***/ }), /* 302 */ /***/ (function(module, exports, __webpack_require__) { var isPlainObject = __webpack_require__(49); /** * 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; /***/ }), /* 303 */ /***/ (function(module, exports, __webpack_require__) { var realNames = __webpack_require__(315); /** 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; /***/ }), /* 304 */ /***/ (function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(168), 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; /***/ }), /* 305 */ /***/ (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; /***/ }), /* 306 */ /***/ (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; /***/ }), /* 307 */ /***/ (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; /***/ }), /* 308 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93), cloneDataView = __webpack_require__(284), cloneMap = __webpack_require__(285), cloneRegExp = __webpack_require__(286), cloneSet = __webpack_require__(287), cloneSymbol = __webpack_require__(288), cloneTypedArray = __webpack_require__(145); /** `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; /***/ }), /* 309 */ /***/ (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; /***/ }), /* 310 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), isArguments = __webpack_require__(25), isArray = __webpack_require__(0); /** 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; /***/ }), /* 311 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), getData = __webpack_require__(156), getFuncName = __webpack_require__(303), lodash = __webpack_require__(341); /** * 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; /***/ }), /* 312 */ /***/ (function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(146), composeArgsRight = __webpack_require__(147), replaceHolders = __webpack_require__(34); /** 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; /***/ }), /* 313 */ /***/ (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; /***/ }), /* 314 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64), baseSlice = __webpack_require__(141); /** * 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; /***/ }), /* 315 */ /***/ (function(module, exports) { /** Used to lookup unminified function names. */ var realNames = {}; module.exports = realNames; /***/ }), /* 316 */ /***/ (function(module, exports, __webpack_require__) { var copyArray = __webpack_require__(68), isIndex = __webpack_require__(31); /* 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; /***/ }), /* 317 */ /***/ (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; /***/ }), /* 318 */ /***/ (function(module, exports, __webpack_require__) { var asciiToArray = __webpack_require__(252), hasUnicode = __webpack_require__(306), unicodeToArray = __webpack_require__(319); /** * 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; /***/ }), /* 319 */ /***/ (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; /***/ }), /* 320 */ /***/ (function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(85), arrayIncludes = __webpack_require__(87); /** 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; /***/ }), /* 321 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), LodashWrapper = __webpack_require__(124), copyArray = __webpack_require__(68); /** * 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; /***/ }), /* 322 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), createAssigner = __webpack_require__(149), keysIn = __webpack_require__(51); /** * 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; /***/ }), /* 323 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** 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; /***/ }), /* 324 */ /***/ (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; /***/ }), /* 325 */ /***/ (function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(257), baseFlatten = __webpack_require__(131), baseRest = __webpack_require__(20), isArrayLikeObject = __webpack_require__(103); /** * 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; /***/ }), /* 326 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43), castFunction = __webpack_require__(143); /** * 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; /***/ }), /* 327 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44), isArrayLike = __webpack_require__(11), isString = __webpack_require__(50), toInteger = __webpack_require__(53), values = __webpack_require__(340); /* 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; /***/ }), /* 328 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIntersection = __webpack_require__(260), baseRest = __webpack_require__(20), castArrayLikeObject = __webpack_require__(280); /** * 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; /***/ }), /* 329 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), baseForOwn = __webpack_require__(43), 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; /***/ }), /* 330 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), baseForOwn = __webpack_require__(43), 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; /***/ }), /* 331 */ /***/ (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; /***/ }), /* 332 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** 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; /***/ }), /* 333 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** 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; /***/ }), /* 334 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), basePickBy = __webpack_require__(139), getAllKeysIn = __webpack_require__(96); /** * 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; /***/ }), /* 335 */ /***/ (function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(271), basePropertyDeep = __webpack_require__(272), isKey = __webpack_require__(72), toKey = __webpack_require__(23); /** * 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; /***/ }), /* 336 */ /***/ (function(module, exports, __webpack_require__) { var baseClamp = __webpack_require__(255), baseToString = __webpack_require__(66), toInteger = __webpack_require__(53), toString = __webpack_require__(75); /** * 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; /***/ }), /* 337 */ /***/ (function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(13), baseSum = __webpack_require__(277); /** * 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; /***/ }), /* 338 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6), isSymbol = __webpack_require__(27); /** 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; /***/ }), /* 339 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), keysIn = __webpack_require__(51); /** * 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; /***/ }), /* 340 */ /***/ (function(module, exports, __webpack_require__) { var baseValues = __webpack_require__(279), 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; /***/ }), /* 341 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), LodashWrapper = __webpack_require__(124), baseLodash = __webpack_require__(92), isArray = __webpack_require__(0), isObjectLike = __webpack_require__(7), wrapperClone = __webpack_require__(321); /** 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; /***/ }), /* 342 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var stringify = __webpack_require__(344); var parse = __webpack_require__(343); var formats = __webpack_require__(209); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }), /* 343 */ /***/ (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 parseValues(str, options) { var obj = {}; var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; var key, val; if (pos === -1) { key = options.decoder(part); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos)); val = options.decoder(part.slice(pos + 1)); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function parseObject(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[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 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 parseKeys(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 parent = /^([^\[\]]*)/; var child = /(\[[^\[\]]*\])/g; // Get the parent var segment = parent.exec(key); // Stash the parent if it exists var keys = []; if (segment[1]) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, segment[1])) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // 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].replace(/\[|\]/g, ''))) { if (!options.allowPrototypes) { continue; } } 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 || {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } 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); }; /***/ }), /* 344 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(108); var formats = __webpack_require__(209); var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var toISO = Date.prototype.toISOString; var defaults = { delimiter: '&', encode: true, encoder: utils.encode, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter) { 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 ? encoder(prefix) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { return [formatter(encoder(prefix)) + '=' + formatter(encoder(obj))]; } 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 )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } } return values; }; module.exports = function (object, opts) { var obj = object; var options = opts || {}; 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 = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null; 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; 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 (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } 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, encoder, filter, sort, allowDots, serializeDate, formatter )); } return keys.join(delimiter); }; /***/ }), /* 345 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Highlighter; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlighter(_ref) { var hit = _ref.hit; var attributeName = _ref.attributeName; var highlight = _ref.highlight; var highlightProperty = _ref.highlightProperty; var tagName = _ref.tagName; var parsedHighlightedValue = highlight({ hit: hit, attributeName: attributeName, highlightProperty: highlightProperty }); var reactHighlighted = parsedHighlightedValue.map(function (v, i) { var key = 'split-' + i + '-' + v.value; if (!v.isHighlighted) { return _react2.default.createElement( 'span', { key: key, className: 'ais-Highlight__nonHighlighted' }, v.value ); } var HighlightedTag = tagName ? tagName : 'em'; return _react2.default.createElement( HighlightedTag, { key: key, className: 'ais-Highlight__highlighted' }, v.value ); }); return _react2.default.createElement( 'span', { className: 'ais-Highlight' }, reactHighlighted ); } Highlighter.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, highlightProperty: _propTypes2.default.string.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 346 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 _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; } var cx = (0, _classNames2.default)('SearchBox'); var SearchBox = function (_Component) { _inherits(SearchBox, _Component); function SearchBox(props) { _classCallCheck(this, SearchBox); var _this = _possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this)); _this.getQuery = function () { return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query; }; _this.setQuery = function (val) { var _this$props = _this.props; var refine = _this$props.refine; var searchAsYouType = _this$props.searchAsYouType; if (searchAsYouType) { refine(val); } else { _this.setState({ query: val }); } }; _this.onInputMount = function (input) { _this.input = input; if (_this.props.__inputRef) { _this.props.__inputRef(input); } }; _this.onKeyDown = function (e) { if (!_this.props.focusShortcuts) { return; } var shortcuts = _this.props.focusShortcuts.map(function (key) { return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key; }); var elt = e.target || e.srcElement; var tagName = elt.tagName; if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') { // already in an input return; } var which = e.which || e.keyCode; if (shortcuts.indexOf(which) === -1) { // not the right shortcut return; } _this.input.focus(); e.stopPropagation(); e.preventDefault(); }; _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); _this.input.blur(); var _this$props2 = _this.props; var refine = _this$props2.refine; var searchAsYouType = _this$props2.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }; _this.onChange = function (e) { _this.setQuery(e.target.value); if (_this.props.onChange) { _this.props.onChange(e); } }; _this.onReset = function () { _this.setQuery(''); _this.input.focus(); if (_this.props.onReset) { _this.props.onReset(); } }; _this.state = { query: props.searchAsYouType ? null : props.currentRefinement }; return _this; } _createClass(SearchBox, [{ key: 'componentDidMount', value: function componentDidMount() { document.addEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { document.removeEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // Reset query when the searchParameters query has changed. // This is kind of an anti-pattern (props in state), but it works here // since we know for sure that searchParameters having changed means a // new search has been triggered. if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) { this.setState({ query: nextProps.currentRefinement }); } } // From https://github.com/algolia/autocomplete.js/pull/86 }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var autoFocus = _props.autoFocus; var query = this.getQuery(); var submitComponent = this.props.submitComponent ? this.props.submitComponent : _react2.default.createElement( 'svg', { role: 'img', width: '1em', height: '1em' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-search-13' }) ); var resetComponent = this.props.resetComponent ? this.props.resetComponent : _react2.default.createElement( 'svg', { role: 'img', width: '1em', height: '1em' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' }) ); var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) { if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) { return _extends({}, props, _defineProperty({}, prop, _this2.props[prop])); } return props; }, {}); /* eslint-disable max-len */ return _react2.default.createElement( 'form', _extends({ noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset }, cx('root'), { action: '', role: 'search' }), _react2.default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } }, _react2.default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-search-13', viewBox: '0 0 40 40' }, _react2.default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z', fillRule: 'evenodd' }) ), _react2.default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-clear-3', viewBox: '0 0 20 20' }, _react2.default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z', fillRule: 'evenodd' }) ) ), _react2.default.createElement( 'div', _extends({ role: 'search' }, cx('wrapper')), _react2.default.createElement('input', _extends({ ref: this.onInputMount, type: 'search', placeholder: translate('placeholder'), autoFocus: autoFocus, autoComplete: 'off', autoCorrect: 'off', autoCapitalize: 'off', spellCheck: 'false', required: true, value: query, onChange: this.onChange }, searchInputEvents, cx('input'))), _react2.default.createElement( 'button', _extends({ type: 'submit', title: translate('submitTitle') }, cx('submit')), submitComponent ), _react2.default.createElement( 'button', _extends({ type: 'reset', title: translate('resetTitle') }, cx('reset'), { onClick: this.onReset }), resetComponent ) ) ); /* eslint-enable */ } }]); return SearchBox; }(_react.Component); SearchBox.propTypes = { currentRefinement: _propTypes2.default.string, refine: _propTypes2.default.func.isRequired, translate: _propTypes2.default.func.isRequired, resetComponent: _propTypes2.default.element, submitComponent: _propTypes2.default.element, focusShortcuts: _propTypes2.default.arrayOf(_propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number])), autoFocus: _propTypes2.default.bool, searchAsYouType: _propTypes2.default.bool, onSubmit: _propTypes2.default.func, onReset: _propTypes2.default.func, onChange: _propTypes2.default.func, // For testing purposes __inputRef: _propTypes2.default.func }; SearchBox.defaultProps = { currentRefinement: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true }; exports.default = (0, _translatable2.default)({ resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); /***/ }), /* 347 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); 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; } var Select = function (_Component) { _inherits(Select, _Component); function Select() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Select); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.onSelect(e.target.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Select, [{ key: 'render', value: function render() { var _props = this.props; var cx = _props.cx; var items = _props.items; var selectedItem = _props.selectedItem; return _react2.default.createElement( 'select', _extends({}, cx('root'), { value: selectedItem, onChange: this.onChange }), items.map(function (item) { return _react2.default.createElement( 'option', { key: (0, _has3.default)(item, 'key') ? item.key : item.value, disabled: item.disabled, value: item.value }, (0, _has3.default)(item, 'label') ? item.label : item.value ); }) ); } }]); return Select; }(_react.Component); Select.propTypes = { cx: _propTypes2.default.func.isRequired, onSelect: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]).isRequired, key: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), label: _propTypes2.default.string, disabled: _propTypes2.default.bool })).isRequired, selectedItem: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]).isRequired }; exports.default = Select; /***/ }), /* 348 */ /***/ (function(module, exports, __webpack_require__) { module.exports = buildSearchMethod; var errors = __webpack_require__(215); /** * Creates a search method to be used in clients * @param {string} queryParam the name of the attribute used for the query * @param {string} url the url * @return {function} the search method */ function buildSearchMethod(queryParam, url) { /** * The search method. Prepares the data and send the query to Algolia. * @param {string} query the string used for query search * @param {object} args additional parameters to send with the search * @param {function} [callback] the callback to be called with the client gets the answer * @return {undefined|Promise} If the callback is not provided then this methods returns a Promise */ return function search(query, args, callback) { // warn V2 users on how to search if (typeof query === 'function' && typeof args === 'object' || typeof callback === 'object') { // .search(query, params, cb) // .search(cb, params) throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)'); } // Normalizing the function signature if (arguments.length === 0 || typeof query === 'function') { // Usage : .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // Usage : .search(query/args), .search(query, cb) callback = args; args = undefined; } // At this point we have 3 arguments with values // Usage : .search(args) // careful: typeof null === 'object' if (typeof query === 'object' && query !== null) { args = query; query = undefined; } else if (query === undefined || query === null) { // .search(undefined/null) query = ''; } var params = ''; if (query !== undefined) { params += queryParam + '=' + encodeURIComponent(query); } var additionalUA; if (args !== undefined) { if (args.additionalUA) { additionalUA = args.additionalUA; delete args.additionalUA; } // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if params = this.as._getSearchParams(args, params); } return this._search(params, url, callback, additionalUA); }; } /***/ }), /* 349 */ /***/ (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 } } /***/ }), /* 350 */, /* 351 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 = createIndex; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Index = __webpack_require__(398); var _Index2 = _interopRequireDefault(_Index); 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; } /** * Creates a specialized root Index component. It accepts * a specification of the root Element. * @param {object} root - the defininition of the root of an Index sub tree. * @returns {object} a Index root */ function createIndex(root) { var _class, _temp; return _temp = _class = function (_Component) { _inherits(CreateIndex, _Component); function CreateIndex() { _classCallCheck(this, CreateIndex); return _possibleConstructorReturn(this, (CreateIndex.__proto__ || Object.getPrototypeOf(CreateIndex)).apply(this, arguments)); } _createClass(CreateIndex, [{ key: 'render', value: function render() { return _react2.default.createElement(_Index2.default, { indexName: this.props.indexName, root: root, children: this.props.children }); } }]); return CreateIndex; }(_react.Component), _class.propTypes = { children: _propTypes2.default.oneOfType([_propTypes2.default.arrayOf(_propTypes2.default.node), _propTypes2.default.node]), indexName: _propTypes2.default.string.isRequired }, _temp; } /***/ }), /* 352 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 = createInstantSearch; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _InstantSearch = __webpack_require__(399); var _InstantSearch2 = _interopRequireDefault(_InstantSearch); 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; } var _name$author$descript = { name: 'react-instantsearch', author: { name: 'Algolia, Inc.', url: 'https://www.algolia.com' }, description: '\u26A1 Lightning-fast search for React and React Native apps', version: '4.0.0-beta.3', scripts: { build: './scripts/build.sh', 'build-and-publish': './scripts/build-and-publish.sh' }, homepage: 'https://community.algolia.com/react-instantsearch/', repository: { type: 'git', url: 'https://github.com/algolia/react-instantsearch/' }, dependencies: { algoliasearch: '^3.21.1', 'algoliasearch-helper': '2.19.0', classnames: '^2.2.5', lodash: '^4.17.4', 'prop-types': '^15.5.8' }, license: 'MIT', devDependencies: { enzyme: '^2.8.1', react: '^15.5.4', 'react-dom': '^15.5.4', 'react-native': '^0.41.2', 'react-test-renderer': '^15.5.4' } }; var version = _name$author$descript.version; /** * Creates a specialized root InstantSearch component. It accepts * an algolia client and a specification of the root Element. * @param {function} defaultAlgoliaClient - a function that builds an Algolia client * @param {object} root - the defininition of the root of an InstantSearch sub tree. * @returns {object} an InstantSearch root */ function createInstantSearch(defaultAlgoliaClient, root) { var _class, _temp; return _temp = _class = function (_Component) { _inherits(CreateInstantSearch, _Component); function CreateInstantSearch(props) { _classCallCheck(this, CreateInstantSearch); var _this = _possibleConstructorReturn(this, (CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call(this)); _this.client = props.algoliaClient || defaultAlgoliaClient(props.appId, props.apiKey); _this.client.addAlgoliaAgent('react-instantsearch ' + version); return _this; } _createClass(CreateInstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var props = this.props; if (nextProps.algoliaClient) { this.client = nextProps.algoliaClient; } else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) { this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey); } this.client.addAlgoliaAgent('react-instantsearch ' + version); } }, { key: 'render', value: function render() { return _react2.default.createElement(_InstantSearch2.default, { createURL: this.props.createURL, indexName: this.props.indexName, searchParameters: this.props.searchParameters, searchState: this.props.searchState, onSearchStateChange: this.props.onSearchStateChange, root: root, algoliaClient: this.client, children: this.props.children }); } }]); return CreateInstantSearch; }(_react.Component), _class.propTypes = { algoliaClient: _propTypes2.default.object, appId: _propTypes2.default.string, apiKey: _propTypes2.default.string, children: _propTypes2.default.oneOfType([_propTypes2.default.arrayOf(_propTypes2.default.node), _propTypes2.default.node]), indexName: _propTypes2.default.string.isRequired, searchParameters: _propTypes2.default.object, createURL: _propTypes2.default.func, searchState: _propTypes2.default.object, onSearchStateChange: _propTypes2.default.func }, _temp; } /***/ }), /* 353 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(210); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _ClearAll = __webpack_require__(376); var _ClearAll2 = _interopRequireDefault(_ClearAll); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The ClearAll widget displays a button that lets the user clean every refinement applied * to the search. * @name ClearAll * @kind widget * @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 {boolean} [clearsQuery=false] - Pass true to also clear the search query * @themeKey ais-ClearAll__root - the widget button * @translationKey reset - the clear all button value * @example * import React from 'react'; * * import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ClearAll /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectCurrentRefinements2.default)(_ClearAll2.default); /***/ }), /* 354 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectConfigure = __webpack_require__(220); var _connectConfigure2 = _interopRequireDefault(_connectConfigure); var _Configure = __webpack_require__(377); var _Configure2 = _interopRequireDefault(_Configure); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * * import {Configure} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure distinct={1} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectConfigure2.default)(_Configure2.default); /***/ }), /* 355 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(210); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _CurrentRefinements = __webpack_require__(378); var _CurrentRefinements2 = _interopRequireDefault(_CurrentRefinements); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The CurrentRefinements widget displays the list of currently applied filters. * * It allows the user to selectively remove them. * @name CurrentRefinements * @kind widget * @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. * @themeKey ais-CurrentRefinements__root - the root div of the widget * @themeKey ais-CurrentRefinements__items - the container of the filters * @themeKey ais-CurrentRefinements__item - a single filter * @themeKey ais-CurrentRefinements__itemLabel - the label of a filter * @themeKey ais-CurrentRefinements__itemClear - the trigger to remove the filter * @themeKey ais-CurrentRefinements__noRefinement - present when there is no refinement * @translationKey clearFilter - the remove filter button label * @example * import React from 'react'; * * import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CurrentRefinements /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectCurrentRefinements2.default)(_CurrentRefinements2.default); /***/ }), /* 356 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHierarchicalMenu = __webpack_require__(221); var _connectHierarchicalMenu2 = _interopRequireDefault(_connectHierarchicalMenu); var _HierarchicalMenu = __webpack_require__(379); var _HierarchicalMenu2 = _interopRequireDefault(_HierarchicalMenu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The hierarchical menu lets the user browse attributes using 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 HierarchicalMenu * @kind widget * @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. * * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @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 {string} [defaultRefinement] - the item value selected by default * @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. * @themeKey ais-HierarchicalMenu__root - Container of the widget * @themeKey ais-HierarchicalMenu__items - Container of the items * @themeKey ais-HierarchicalMenu__item - Id for a single list item * @themeKey ais-HierarchicalMenu__itemSelected - Id for the selected items in the list * @themeKey ais-HierarchicalMenu__itemParent - Id for the elements that have a sub list displayed * @themeKey HierarchicalMenu__itemSelectedParent - Id for parents that have currently a child selected * @themeKey ais-HierarchicalMenu__itemLink - the link containing the label and the count * @themeKey ais-HierarchicalMenu__itemLabel - the label of the entry * @themeKey ais-HierarchicalMenu__itemCount - the count of the entry * @themeKey ais-HierarchicalMenu__itemItems - id representing a children * @themeKey ais-HierarchicalMenu__showMore - container for the show more button * @themeKey ais-HierarchicalMenu__noRefinement - present when there is no refinement * @translationKey showMore - Label value of the button which toggles the number of items * @example * import React from 'react'; * import { * InstantSearch, * HierarchicalMenu, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HierarchicalMenu * id="categories" * key="categories" * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHierarchicalMenu2.default)(_HierarchicalMenu2.default); /***/ }), /* 357 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHits = __webpack_require__(222); var _connectHits2 = _interopRequireDefault(_connectHits); var _Hits = __webpack_require__(381); var _Hits2 = _interopRequireDefault(_Hits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Displays a list of hits. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name Hits * @kind widget * @propType {Component} [hitComponent] - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey ais-Hits__root - the root of the component * @example * import React from 'react'; * import { * InstantSearch, * Hits, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Hits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHits2.default)(_Hits2.default); /***/ }), /* 358 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHitsPerPage = __webpack_require__(223); var _connectHitsPerPage2 = _interopRequireDefault(_connectHitsPerPage); var _HitsPerPage = __webpack_require__(382); var _HitsPerPage2 = _interopRequireDefault(_HitsPerPage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The HitsPerPage widget displays a dropdown menu to let the user change the number * of displayed hits. * * If you only want to configure the number of hits per page without * displaying a widget, you should use the `<Configure hitsPerPage={20} />` widget. See [`<Configure /> documentation`](widgets/Configure.html) * * @name HitsPerPage * @kind widget * @propType {{value: number, label: string}[]} items - List of available options. * @propType {number} defaultRefinement - The number of items selected by default * @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. * @themeKey ais-HitsPerPage__root - the root of the component. * @example * import React from 'react'; * import { * InstantSearch, * HitsPerPage, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HitsPerPage * defaultRefinement={20} * items={[{value: '30', label: 'Show 20 hits'}, {value: '50', label: 'Show 50 hits'}]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHitsPerPage2.default)(_HitsPerPage2.default); /***/ }), /* 359 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectInfiniteHits = __webpack_require__(224); var _connectInfiniteHits2 = _interopRequireDefault(_connectInfiniteHits); var _InfiniteHits = __webpack_require__(383); var _InfiniteHits2 = _interopRequireDefault(_InfiniteHits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Displays an infinite list of hits along with a **load more** button. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name InfiniteHits * @kind widget * @propType {Component} hitComponent - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey root - the root of the component * @translationKey loadMore - the label of load more button * @example * import React from 'react'; * import { * InstantSearch, * Hits, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <InfiniteHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectInfiniteHits2.default)(_InfiniteHits2.default); /***/ }), /* 360 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMenu = __webpack_require__(225); var _connectMenu2 = _interopRequireDefault(_connectMenu); var _Menu = __webpack_require__(385); var _Menu2 = _interopRequireDefault(_Menu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Menu component displays a menu that lets the user choose a single value for a specific attribute. * @name Menu * @kind widget * @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} [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 {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 {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values * @themeKey ais-Menu__root - the root of the component * @themeKey ais-Menu__items - the container of all items in the menu * @themeKey ais-Menu__item - a single item * @themeKey ais-Menu__itemLinkSelected - the selected menu item * @themeKey ais-Menu__itemLink - the item link * @themeKey ais-Menu__itemLabelSelected - the selected item label * @themeKey ais-Menu__itemLabel - the item label * @themeKey ais-Menu__itemCount - the item count * @themeKey ais-Menu__itemCountSelected - the selected item count * @themeKey ais-Menu__noRefinement - present when there is no refinement * @themeKey ais-Menu__showMore - the button that let the user toggle more results * @themeKey ais-Menu__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @example * import React from 'react'; * * import {Menu, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Menu * attributeName="category" * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectMenu2.default)(_Menu2.default); /***/ }), /* 361 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMultiRange = __webpack_require__(226); var _connectMultiRange2 = _interopRequireDefault(_connectMultiRange); var _MultiRange = __webpack_require__(386); var _MultiRange2 = _interopRequireDefault(_MultiRange); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * MultiRange is a widget used for selecting the range value of a numeric attribute. * @name MultiRange * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @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 format "min:max". * @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. * @themeKey ais-MultiRange__root - The root component of the widget * @themeKey ais-MultiRange__items - The container of the items * @themeKey ais-MultiRange__item - A single item * @themeKey ais-MultiRange__itemSelected - The selected item * @themeKey ais-MultiRange__itemLabel - The label of an item * @themeKey ais-MultiRange__itemLabelSelected - The selected label item * @themeKey ais-MultiRange__itemRadio - The radio of an item * @themeKey ais-MultiRange__itemRadioSelected - The selected radio item * @themeKey ais-MultiRange__noRefinement - present when there is no refinement for all ranges * @themeKey ais-MultiRange__itemNoRefinement - present when there is no refinement for one range * @themeKey ais-MultiRange__itemAll - indicate the range that will contain all the results * @translationkey all - The label of the largest range added automatically by react instantsearch * @example * import React from 'react'; * * import {InstantSearch, MultiRange} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <MultiRange attributeName="price" * items={[ * {end: 10, label: '<$10'}, * {start: 10, end: 100, label: '$10-$100'}, * {start: 100, end: 500, label: '$100-$500'}, * {start: 500, label: '>$500'}, * ]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectMultiRange2.default)(_MultiRange2.default); /***/ }), /* 362 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPagination = __webpack_require__(227); var _connectPagination2 = _interopRequireDefault(_connectPagination); var _Pagination = __webpack_require__(387); var _Pagination2 = _interopRequireDefault(_Pagination); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Pagination widget displays a simple pagination system allowing the user to * change the current page. * @name Pagination * @kind widget * @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. * @themeKey ais-Pagination__root - The root component of the widget * @themeKey ais-Pagination__itemFirst - The first page link item * @themeKey ais-Pagination__itemPrevious - The previous page link item * @themeKey ais-Pagination__itemPage - The page link item * @themeKey ais-Pagination__itemNext - The next page link item * @themeKey ais-Pagination__itemLast - The last page link item * @themeKey ais-Pagination__itemDisabled - a disabled item * @themeKey ais-Pagination__itemSelected - a selected item * @themeKey ais-Pagination__itemLink - The link of an item * @themeKey ais-Pagination__noRefinement - present when there is no refinement * @translationKey previous - Label value for the previous page link * @translationKey next - Label value for the next page link * @translationKey first - Label value for the first page link * @translationKey last - Label value for the last page link * @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string * @translationKey ariaPrevious - Accessibility label value for the previous page link * @translationKey ariaNext - Accessibility label value for the next page link * @translationKey ariaFirst - Accessibility label value for the first page link * @translationKey ariaLast - Accessibility label value for the last page link * @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string * @example * import React from 'react'; * * import {Pagination, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Pagination/> * </InstantSearch> * ); * } */ exports.default = (0, _connectPagination2.default)(_Pagination2.default); /***/ }), /* 363 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _Panel = __webpack_require__(388); var _Panel2 = _interopRequireDefault(_Panel); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Panel widget wraps other widgets in a consistent panel design. * * It also reacts, indicates and set CSS classes when widgets are no more * relevant for refining. E.g. when a RefinementList becomes empty because of * the current search results. * @name Panel * @kind widget * @propType {string} title - The panel title * @themeKey ais-Panel__root - Container of the widget * @themeKey ais-Panel__title - The panel title * @themeKey ais-Panel__noRefinement - Present if the panel content is empty * @example * import React from 'react'; * * import {Panel, RefinementList, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Panel title="category"> * <RefinementList attributeName="category" /> * </Panel> * </InstantSearch> * ); * } */ exports.default = _Panel2.default; /***/ }), /* 364 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPoweredBy = __webpack_require__(228); var _connectPoweredBy2 = _interopRequireDefault(_connectPoweredBy); var _PoweredBy = __webpack_require__(389); var _PoweredBy2 = _interopRequireDefault(_PoweredBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * PoweredBy displays an Algolia logo. * * Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing). * @name PoweredBy * @kind widget * @themeKey ais-PoweredBy__root - The root component of the widget * @themeKey ais-PoweredBy__searchBy - The powered by label * @themeKey ais-PoweredBy__algoliaLink - The algolia logo link * @translationKey searchBy - Label value for the powered by * @example * import React from 'react'; * * import {PoweredBy, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <PoweredBy /> * </InstantSearch> * ); * } */ exports.default = (0, _connectPoweredBy2.default)(_PoweredBy2.default); /***/ }), /* 365 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _RangeInput = __webpack_require__(390); var _RangeInput2 = _interopRequireDefault(_RangeInput); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * RangeInput allows a user to select a numeric range using a minimum and maximum input. * @name RangeInput * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the record * @propType {{min: number, max: number}} [defaultRefinement] - Default state 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. * @themeKey ais-RangeInput__root - The root component of the widget * @themeKey ais-RangeInput__labelMin - The label for the min input * @themeKey ais-RangeInput__inputMin - The min input * @themeKey ais-RangeInput__separator - The separator between input * @themeKey ais-RangeInput__labelMax - The label for the max input * @themeKey ais-RangeInput__inputMax - The max input * @themeKey ais-RangeInput__submit - The submit button * @themeKey ais-RangeInput__noRefinement - present when there is no refinement * @translationKey submit - Label value for the submit button * @translationKey separator - Label value for the input separator * @example * import React from 'react'; * * import {RangeInput, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RangeInput attributeName="price"/> * </InstantSearch> * ); * } */ exports.default = (0, _connectRange2.default)(_RangeInput2.default); /***/ }), /* 366 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Since a lot of sliders already exist, we did not include one by default. * However you can easily connect React InstantSearch to an existing one * using the [connectRange connector](connectors/connectRange.html). * * @name RangeSlider * @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values. * @kind widget * @example * * // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the * // range connector import PropTypes from 'prop-types'; import React, {Component} from 'react'; import {connectRange} from 'react-instantsearch/connectors'; import Rheostat from 'rheostat'; class Range extends React.Component { static propTypes = { min: PropTypes.number, max: PropTypes.number, currentRefinement: PropTypes.object, refine: PropTypes.func.isRequired, canRefine: PropTypes.bool.isRequired, }; state = {currentValues: {min: this.props.min, max: this.props.max}}; componentWillReceiveProps(sliderState) { if (sliderState.canRefine) { this.setState({currentValues: {min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max}}); } } onValuesUpdated = (sliderState) => { this.setState({currentValues: {min: sliderState.values[0], max: sliderState.values[1]}}); }; onChange = (sliderState) => { if (this.props.currentRefinement.min !== sliderState.values[0] || this.props.currentRefinement.max !== sliderState.values[1]) { this.props.refine({min: sliderState.values[0], max: sliderState.values[1]}); } }; render() { const {min, max, currentRefinement} = this.props; const {currentValues} = this.state; return min !== max ? <div> <Rheostat min={min} max={max} values={[currentRefinement.min, currentRefinement.max]} onChange={this.onChange} onValuesUpdated={this.onValuesUpdated} /> <div style={{display: 'flex', justifyContent: 'space-between'}}> <div>{currentValues.min}</div> <div>{currentValues.max}</div> </div> </div> : null; } } const ConnectedRange = connectRange(Range); */ exports.default = (0, _connectRange2.default)(function () { return _react2.default.createElement( 'div', null, 'We do not provide any Slider, see the documentation to learn how to connect one easily:', _react2.default.createElement( 'a', { target: '_blank', href: 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html' }, 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html' ) ); }); /***/ }), /* 367 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRefinementList = __webpack_require__(229); var _connectRefinementList2 = _interopRequireDefault(_connectRefinementList); var _RefinementList = __webpack_require__(391); var _RefinementList2 = _interopRequireDefault(_RefinementList); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The RefinementList component displays a list that let the end user choose multiple values for a specific facet. * @name RefinementList * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet 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 maximum number of displayed items. Only used when showMore is set to `true` * @propType {string[]} [defaultRefinement] - the values of the items selected by default * @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. * @themeKey ais-RefinementList__root - the root of the component * @themeKey ais-RefinementList__items - the container of all items in the list * @themeKey ais-RefinementList__itemSelected - the selected list item * @themeKey ais-RefinementList__itemCheckbox - the item checkbox * @themeKey ais-RefinementList__itemCheckboxSelected - the selected item checkbox * @themeKey ais-RefinementList__itemLabel - the item label * @themeKey ais-RefinementList__itemLabelSelected - the selected item label * @themeKey RefinementList__itemCount - the item count * @themeKey RefinementList__itemCountSelected - the selected item count * @themeKey ais-RefinementList__showMore - the button that let the user toggle more results * @themeKey ais-RefinementList__noRefinement - present when there is no refinement * @themeKey ais-RefinementList__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @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. * @example * import React from 'react'; * * import {RefinementList, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RefinementList attributeName="colors" /> * </InstantSearch> * ); * } */ exports.default = (0, _connectRefinementList2.default)(_RefinementList2.default); /***/ }), /* 368 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectScrollTo = __webpack_require__(230); var _connectScrollTo2 = _interopRequireDefault(_connectScrollTo); var _ScrollTo = __webpack_require__(392); var _ScrollTo2 = _interopRequireDefault(_ScrollTo); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The ScrollTo component will made the page scroll to the component wrapped by it when one of the * [search state](guide/Search_state.html) prop is updated. By default when the page number changes, * the scroll goes to the wrapped component. * * @name ScrollTo * @kind widget * @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes. * @example * import React from 'react'; * * import {ScrollTo, Hits, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ScrollTo> * <Hits /> * </ScrollTo> * </InstantSearch> * ); * } */ exports.default = (0, _connectScrollTo2.default)(_ScrollTo2.default); /***/ }), /* 369 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSearchBox = __webpack_require__(231); var _connectSearchBox2 = _interopRequireDefault(_connectSearchBox); var _SearchBox = __webpack_require__(346); var _SearchBox2 = _interopRequireDefault(_SearchBox); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The SearchBox component displays a search box that lets the user search for a specific query. * @name SearchBox * @kind widget * @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes. * @propType {boolean} [autoFocus=false] - Should the search box be focused on render? * @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused. * @propType {function} [onSubmit] - Intercept submit event sent from the SearchBox form container. * @propType {function} [onReset] - Listen to `reset` event sent from the SearchBox form container. * @propType {function} [on*] - Listen to any events sent form the search input itself. * @propType {React.Element} [submitComponent] - Change the apparence of the default submit button (magnifying glass). * @propType {React.Element} [resetComponent] - Change the apparence of the default reset button (cross). * @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted. * @themeKey ais-SearchBox__root - the root of the component * @themeKey ais-SearchBox__wrapper - the search box wrapper * @themeKey ais-SearchBox__input - the search box input * @themeKey ais-SearchBox__submit - the submit button * @themeKey ais-SearchBox__reset - the reset button * @translationkey submitTitle - The submit button title * @translationkey resetTitle - The reset button title * @translationkey placeholder - The label of the input placeholder * @example * import React from 'react'; * * import {SearchBox, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * </InstantSearch> * ); * } */ exports.default = (0, _connectSearchBox2.default)(_SearchBox2.default); /***/ }), /* 370 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(211); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Snippet = __webpack_require__(393); var _Snippet2 = _interopRequireDefault(_Snippet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Renders any attribute from an hit into its highlighted snippet form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Snippet * @kind widget * @propType {string} attributeName - the location of the highlighted snippet attribute in the hit * @propType {object} hit - the hit object containing the highlighted snippet attribute * @propType {string} [tagName='em'] - the tag to be used for highlighted parts of the attribute * @example * import React from 'react'; * * import {InstantSearch, connectHits, Snippet} from 'InstantSearch'; * * const CustomHits = connectHits(hits => { * return hits.map((hit) => <p><Snippet attributeName="description" hit={hit}/></p>); * }); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHighlight2.default)(_Snippet2.default); /***/ }), /* 371 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSortBy = __webpack_require__(232); var _connectSortBy2 = _interopRequireDefault(_connectSortBy); var _SortBy = __webpack_require__(394); var _SortBy2 = _interopRequireDefault(_SortBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The SortBy component displays a list of indexes allowing a user to change the hits are sorting. * @name SortBy * @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 widget * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {string} defaultRefinement - The default selected index. * @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. * @themeKey ais-SortBy__root - the root of the component * @example * import React from 'react'; * * import {SortBy, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SortBy * items={[ * {value: 'ikea', label: 'Featured'}, * {value: 'ikea_price_asc', label: 'Price asc.'}, * {value: 'ikea_price_desc', label: 'Price desc.'}, * ]} * defaultRefinement="ikea" * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectSortBy2.default)(_SortBy2.default); /***/ }), /* 372 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _StarRating = __webpack_require__(395); var _StarRating2 = _interopRequireDefault(_StarRating); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * StarRating lets the user refine search results by clicking on stars. * * The stars are based on the selected `attributeName`. * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @name StarRating * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {number} [min] - Minimum value for the rating. 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 for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating. * @themeKey ais-StarRating__root - The root component of the widget * @themeKey ais-StarRating__ratingLink - The item link * @themeKey ais-StarRating__ratingLinkSelected - The selected link item * @themeKey ais-StarRating__ratingLinkDisabled - The disabled link item * @themeKey ais-StarRating__ratingIcon - The rating icon * @themeKey ais-StarRating__ratingIconSelected - The selected rating icon * @themeKey ais-StarRating__ratingIconDisabled - The disabled rating icon * @themeKey ais-StarRating__ratingIconEmpty - The rating empty icon * @themeKey ais-StarRating__ratingIconEmptySelected - The selected rating empty icon * @themeKey ais-StarRating__ratingIconEmptyDisabled - The disabled rating empty icon * @themeKey ais-StarRating__ratingLabel - The link label * @themeKey ais-StarRating__ratingLabelSelected - The selected link label * @themeKey ais-StarRating__ratingLabelDisabled - The disabled link label * @themeKey ais-StarRating__ratingCount - The link count * @themeKey ais-StarRating__ratingCountSelected - The selected link count * @themeKey ais-StarRating__ratingCountDisabled - The disabled link count * @themeKey ais-StarRating__noRefinement - present when there is no refinement * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * * import {StarRating, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <StarRating attributeName="rating" /> * </InstantSearch> * ); * } */ exports.default = (0, _connectRange2.default)(_StarRating2.default); /***/ }), /* 373 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectStats = __webpack_require__(233); var _connectStats2 = _interopRequireDefault(_connectStats); var _Stats = __webpack_require__(396); var _Stats2 = _interopRequireDefault(_Stats); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). * @name Stats * @kind widget * @themeKey ais-Stats__root - the root of the component * @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time. * @example * import React from 'react'; * * import {Stats, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Stats /> * </InstantSearch> * ); * } */ exports.default = (0, _connectStats2.default)(_Stats2.default); /***/ }), /* 374 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectToggle = __webpack_require__(234); var _connectToggle2 = _interopRequireDefault(_connectToggle); var _Toggle = __webpack_require__(397); var _Toggle2 = _interopRequireDefault(_Toggle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Toggle 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 Toggle * @kind widget * @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` when checked. * @propType {boolean} [defaultChecked=false] - Default state of the widget. Should the toggle be checked by default? * @themeKey ais-Toggle__root - the root of the component * @themeKey ais-Toggle__checkbox - the toggle checkbox * @themeKey ais-Toggle__label - the toggle label * @example * import React from 'react'; * * import {Toggle, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Toggle attributeName="materials" * label="Made with solid pine" * value={'Solid pine'} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectToggle2.default)(_Toggle2.default); /***/ }), /* 375 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var AlgoliaSearchCore = __webpack_require__(404); var createAlgoliasearch = __webpack_require__(406); module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) '); /***/ }), /* 376 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('ClearAll'); var ClearAll = function (_Component) { _inherits(ClearAll, _Component); function ClearAll() { _classCallCheck(this, ClearAll); return _possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments)); } _createClass(ClearAll, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var items = _props.items; var refine = _props.refine; var isDisabled = items.length === 0; if (isDisabled) { return _react2.default.createElement( 'button', _extends({}, cx('root'), { disabled: true }), translate('reset') ); } return _react2.default.createElement( 'button', _extends({}, cx('root'), { onClick: refine.bind(null, items) }), translate('reset') ); } }]); return ClearAll; }(_react.Component); ClearAll.propTypes = { translate: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.object).isRequired, refine: _propTypes2.default.func.isRequired }; exports.default = (0, _translatable2.default)({ reset: 'Clear all filters' })(ClearAll); /***/ }), /* 377 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { return null; }; /***/ }), /* 378 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('CurrentRefinements'); var CurrentRefinements = function (_Component) { _inherits(CurrentRefinements, _Component); function CurrentRefinements() { _classCallCheck(this, CurrentRefinements); return _possibleConstructorReturn(this, (CurrentRefinements.__proto__ || Object.getPrototypeOf(CurrentRefinements)).apply(this, arguments)); } _createClass(CurrentRefinements, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var items = _props.items; var refine = _props.refine; var canRefine = _props.canRefine; return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), _react2.default.createElement( 'div', cx('items'), items.map(function (item) { return _react2.default.createElement( 'div', _extends({ key: item.label }, cx('item', item.items && 'itemParent')), _react2.default.createElement( 'span', cx('itemLabel'), item.label ), item.items ? item.items.map(function (nestedItem) { return _react2.default.createElement( 'div', _extends({ key: nestedItem.label }, cx('item')), _react2.default.createElement( 'span', cx('itemLabel'), nestedItem.label ), _react2.default.createElement( 'button', _extends({}, cx('itemClear'), { onClick: refine.bind(null, nestedItem.value) }), translate('clearFilter', nestedItem) ) ); }) : _react2.default.createElement( 'button', _extends({}, cx('itemClear'), { onClick: refine.bind(null, item.value) }), translate('clearFilter', item) ) ); }) ) ); } }]); return CurrentRefinements; }(_react.Component); CurrentRefinements.propTypes = { translate: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string })).isRequired, refine: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, transformItems: _propTypes2.default.func }; CurrentRefinements.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ clearFilter: '✕' })(CurrentRefinements); /***/ }), /* 379 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('HierarchicalMenu'); var itemsPropType = _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.string, count: _propTypes2.default.number.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var HierarchicalMenu = function (_Component) { _inherits(HierarchicalMenu, _Component); function HierarchicalMenu() { var _ref; var _temp, _this, _ret; _classCallCheck(this, HierarchicalMenu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props; var createURL = _this$props.createURL; var refine = _this$props.refine; return _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink'), { onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }), _react2.default.createElement( 'span', cx('itemLabel'), item.label ), ' ', _react2.default.createElement( 'span', cx('itemCount'), item.count ) ); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(HierarchicalMenu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isEmpty', 'canRefine']))); } }]); return HierarchicalMenu; }(_react.Component); HierarchicalMenu.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, items: itemsPropType, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; HierarchicalMenu.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /***/ }), /* 380 */ /***/ (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; }; exports.default = Highlight; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(345); var _Highlighter2 = _interopRequireDefault(_Highlighter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlight(props) { return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_highlightResult' }, props)); } Highlight.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 381 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('Hits'); var Hits = function (_Component) { _inherits(Hits, _Component); function Hits() { _classCallCheck(this, Hits); return _possibleConstructorReturn(this, (Hits.__proto__ || Object.getPrototypeOf(Hits)).apply(this, arguments)); } _createClass(Hits, [{ key: 'render', value: function render() { var _props = this.props; var ItemComponent = _props.hitComponent; var hits = _props.hits; return _react2.default.createElement( 'div', cx('root'), hits.map(function (hit) { return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }) ); } }]); return Hits; }(_react.Component); Hits.propTypes = { hits: _propTypes2.default.array, hitComponent: _propTypes2.default.func.isRequired }; /* eslint-disable react/display-name */ Hits.defaultProps = { hitComponent: function hitComponent(hit) { return _react2.default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; /* eslint-enable react/display-name */ exports.default = Hits; /***/ }), /* 382 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(347); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('HitsPerPage'); var HitsPerPage = function (_Component) { _inherits(HitsPerPage, _Component); function HitsPerPage() { _classCallCheck(this, HitsPerPage); return _possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments)); } _createClass(HitsPerPage, [{ key: 'render', value: function render() { var _props = this.props; var currentRefinement = _props.currentRefinement; var refine = _props.refine; var items = _props.items; return _react2.default.createElement(_Select2.default, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx }); } }]); return HitsPerPage; }(_react.Component); HitsPerPage.propTypes = { refine: _propTypes2.default.func.isRequired, currentRefinement: _propTypes2.default.number.isRequired, transformItems: _propTypes2.default.func, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ /** * Number of hits to display. */ value: _propTypes2.default.number.isRequired, /** * Label to display on the option. */ label: _propTypes2.default.string })) }; exports.default = HitsPerPage; /***/ }), /* 383 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); 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; } var cx = (0, _classNames2.default)('InfiniteHits'); var InfiniteHits = function (_Component) { _inherits(InfiniteHits, _Component); function InfiniteHits() { _classCallCheck(this, InfiniteHits); return _possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments)); } _createClass(InfiniteHits, [{ key: 'render', value: function render() { var _props = this.props; var ItemComponent = _props.hitComponent; var hits = _props.hits; var hasMore = _props.hasMore; var refine = _props.refine; var translate = _props.translate; var renderedHits = hits.map(function (hit) { return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }); var loadMoreButton = hasMore ? _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { onClick: function onClick() { return refine(); } }), translate('loadMore') ) : _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { disabled: true }), translate('loadMore') ); return _react2.default.createElement( 'div', cx('root'), renderedHits, loadMoreButton ); } }]); return InfiniteHits; }(_react.Component); InfiniteHits.propTypes = { hits: _propTypes2.default.array, hitComponent: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]).isRequired, hasMore: _propTypes2.default.bool.isRequired, refine: _propTypes2.default.func.isRequired, translate: _propTypes2.default.func.isRequired }; /* eslint-disable react/display-name */ InfiniteHits.defaultProps = { hitComponent: function hitComponent(hit) { return _react2.default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; /* eslint-enable react/display-name */ exports.default = (0, _translatable2.default)({ loadMore: 'Load more' })(InfiniteHits); /***/ }), /* 384 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); 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; } var LinkList = function (_Component) { _inherits(LinkList, _Component); function LinkList() { _classCallCheck(this, LinkList); return _possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments)); } _createClass(LinkList, [{ key: 'render', value: function render() { var _props = this.props; var cx = _props.cx; var createURL = _props.createURL; var items = _props.items; var onSelect = _props.onSelect; var canRefine = _props.canRefine; return _react2.default.createElement( 'ul', cx('root', !canRefine && 'noRefinement'), items.map(function (item) { return _react2.default.createElement( 'li', _extends({ key: (0, _has3.default)(item, 'key') ? item.key : item.value }, cx('item', item.selected && !item.disabled && 'itemSelected', item.disabled && 'itemDisabled', item.modifier), { disabled: item.disabled }), item.disabled ? _react2.default.createElement( 'span', cx('itemLink', 'itemLinkDisabled'), (0, _has3.default)(item, 'label') ? item.label : item.value ) : _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink', item.selected && 'itemLinkSelected'), { 'aria-label': item.ariaLabel, href: createURL(item.value), onClick: onSelect.bind(null, item.value) }), (0, _has3.default)(item, 'label') ? item.label : item.value ) ); }) ); } }]); return LinkList; }(_react.Component); LinkList.propTypes = { cx: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number, _propTypes2.default.object]).isRequired, key: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), label: _propTypes2.default.node, modifier: _propTypes2.default.string, ariaLabel: _propTypes2.default.string, disabled: _propTypes2.default.bool })), onSelect: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired }; exports.default = LinkList; /***/ }), /* 385 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); var _Highlight = __webpack_require__(235); var _Highlight2 = _interopRequireDefault(_Highlight); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('Menu'); var Menu = function (_Component) { _inherits(Menu, _Component); function Menu() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Menu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item, resetQuery) { var createURL = _this.props.createURL; var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label; return _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink', item.isRefined && 'itemLinkSelected'), { onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }), _react2.default.createElement( 'span', cx('itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', _react2.default.createElement( 'span', cx('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }, _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Menu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']))); } }]); return Menu; }(_react.Component); Menu.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, searchForItems: _propTypes2.default.func.isRequired, withSearchBox: _propTypes2.default.bool, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.string.isRequired, count: _propTypes2.default.number.isRequired, isRefined: _propTypes2.default.bool.isRequired })), isFromSearch: _propTypes2.default.bool.isRequired, canRefine: _propTypes2.default.bool.isRequired, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; Menu.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(Menu); /***/ }), /* 386 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); 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; } var cx = (0, _classNames2.default)('MultiRange'); var MultiRange = function (_Component) { _inherits(MultiRange, _Component); function MultiRange() { var _ref; var _temp, _this, _ret; _classCallCheck(this, MultiRange); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MultiRange.__proto__ || Object.getPrototypeOf(MultiRange)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props; var refine = _this$props.refine; var translate = _this$props.translate; var label = item.value === '' ? translate('all') : item.label; return _react2.default.createElement( 'label', cx(item.value === '' && 'itemAll'), _react2.default.createElement('input', _extends({}, cx('itemRadio', item.isRefined && 'itemRadioSelected'), { type: 'radio', checked: item.isRefined, disabled: item.noRefinement, onChange: refine.bind(null, item.value) })), _react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), _react2.default.createElement( 'span', cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ) ); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(MultiRange, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props; var items = _props.items; var canRefine = _props.canRefine; return _react2.default.createElement(_List2.default, { renderItem: this.renderItem, showMore: false, canRefine: canRefine, cx: cx, items: items.map(function (item) { return _extends({}, item, { key: item.value }); }) }); } }]); return MultiRange; }(_react.Component); MultiRange.propTypes = { items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.node.isRequired, value: _propTypes2.default.string.isRequired, isRefined: _propTypes2.default.bool.isRequired, noRefinement: _propTypes2.default.bool.isRequired })).isRequired, refine: _propTypes2.default.func.isRequired, transformItems: _propTypes2.default.func, canRefine: _propTypes2.default.bool.isRequired, translate: _propTypes2.default.func.isRequired }; MultiRange.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ all: 'All' })(MultiRange); /***/ }), /* 387 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _range2 = __webpack_require__(424); var _range3 = _interopRequireDefault(_range2); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _LinkList = __webpack_require__(384); var _LinkList2 = _interopRequireDefault(_LinkList); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; } 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; } var cx = (0, _classNames2.default)('Pagination'); function getPagesDisplayedCount(padding, total) { return Math.min(2 * padding + 1, total); } function calculatePaddingLeft(current, padding, total, totalDisplayedPages) { if (current <= padding) { return current; } if (current >= total - padding) { return totalDisplayedPages - (total - current); } return padding; } function getPages(page, total, padding) { var totalDisplayedPages = getPagesDisplayedCount(padding, total); if (totalDisplayedPages === total) return (0, _range3.default)(1, total + 1); var paddingLeft = calculatePaddingLeft(page, padding, total, totalDisplayedPages); var paddingRight = totalDisplayedPages - paddingLeft; var first = page - paddingLeft; var last = page + paddingRight; return (0, _range3.default)(first + 1, last + 1); } var Pagination = function (_Component) { _inherits(Pagination, _Component); function Pagination() { _classCallCheck(this, Pagination); return _possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments)); } _createClass(Pagination, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'getItem', value: function getItem(modifier, translationKey, value) { var _props = this.props; var nbPages = _props.nbPages; var maxPages = _props.maxPages; var translate = _props.translate; return { key: modifier + '.' + value, modifier: modifier, disabled: value < 1 || value >= Math.min(maxPages, nbPages), label: translate(translationKey, value), value: value, ariaLabel: translate('aria' + (0, _utils.capitalize)(translationKey), value) }; } }, { key: 'render', value: function render() { var _props2 = this.props; var nbPages = _props2.nbPages; var maxPages = _props2.maxPages; var currentRefinement = _props2.currentRefinement; var pagesPadding = _props2.pagesPadding; var showFirst = _props2.showFirst; var showPrevious = _props2.showPrevious; var showNext = _props2.showNext; var showLast = _props2.showLast; var refine = _props2.refine; var createURL = _props2.createURL; var translate = _props2.translate; var ListComponent = _props2.listComponent; var otherProps = _objectWithoutProperties(_props2, ['nbPages', 'maxPages', 'currentRefinement', 'pagesPadding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'translate', 'listComponent']); var totalPages = Math.min(nbPages, maxPages); var lastPage = totalPages; var items = []; if (showFirst) { items.push({ key: 'first', modifier: 'itemFirst', disabled: currentRefinement === 1, label: translate('first'), value: 1, ariaLabel: translate('ariaFirst') }); } if (showPrevious) { items.push({ key: 'previous', modifier: 'itemPrevious', disabled: currentRefinement === 1, label: translate('previous'), value: currentRefinement - 1, ariaLabel: translate('ariaPrevious') }); } items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) { return { key: value, modifier: 'itemPage', label: translate('page', value), value: value, selected: value === currentRefinement, ariaLabel: translate('ariaPage', value) }; })); if (showNext) { items.push({ key: 'next', modifier: 'itemNext', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('next'), value: currentRefinement + 1, ariaLabel: translate('ariaNext') }); } if (showLast) { items.push({ key: 'last', modifier: 'itemLast', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('last'), value: lastPage, ariaLabel: translate('ariaLast') }); } return _react2.default.createElement(ListComponent, _extends({}, otherProps, { cx: cx, items: items, onSelect: refine, createURL: createURL })); } }]); return Pagination; }(_react.Component); Pagination.propTypes = { nbPages: _propTypes2.default.number.isRequired, currentRefinement: _propTypes2.default.number.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, translate: _propTypes2.default.func.isRequired, listComponent: _propTypes2.default.func, showFirst: _propTypes2.default.bool, showPrevious: _propTypes2.default.bool, showNext: _propTypes2.default.bool, showLast: _propTypes2.default.bool, pagesPadding: _propTypes2.default.number, maxPages: _propTypes2.default.number }; Pagination.defaultProps = { listComponent: _LinkList2.default, showFirst: true, showPrevious: true, showNext: true, showLast: false, pagesPadding: 3, maxPages: Infinity }; Pagination.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ previous: '‹', next: '›', first: '«', last: '»', page: function page(currentRefinement) { return currentRefinement.toString(); }, ariaPrevious: 'Previous page', ariaNext: 'Next page', ariaFirst: 'First page', ariaLast: 'Last page', ariaPage: function ariaPage(currentRefinement) { return 'Page ' + currentRefinement.toString(); } })(Pagination); /***/ }), /* 388 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('Panel'); var Panel = function (_Component) { _inherits(Panel, _Component); _createClass(Panel, [{ key: 'getChildContext', value: function getChildContext() { return { canRefine: this.canRefine }; } }]); function Panel(props) { _classCallCheck(this, Panel); var _this = _possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props)); _this.state = { canRefine: true }; _this.canRefine = function (canRefine) { _this.setState({ canRefine: canRefine }); }; return _this; } _createClass(Panel, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', cx('root', !this.state.canRefine && 'noRefinement'), _react2.default.createElement( 'h5', cx('title'), this.props.title ), this.props.children ); } }]); return Panel; }(_react.Component); Panel.propTypes = { title: _propTypes2.default.string.isRequired, children: _propTypes2.default.node }; Panel.childContextTypes = { canRefine: _propTypes2.default.func }; exports.default = Panel; /***/ }), /* 389 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('PoweredBy'); /* eslint-disable max-len */ var AlgoliaLogo = function AlgoliaLogo() { return _react2.default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', baseProfile: 'basic', viewBox: '0 0 1366 362' }, _react2.default.createElement( 'linearGradient', { id: 'g', x1: '428.258', x2: '434.145', y1: '404.15', y2: '409.85', gradientUnits: 'userSpaceOnUse', gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)' }, _react2.default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }), _react2.default.createElement('stop', { offset: '1', stopColor: '#3369E7' }) ), _react2.default.createElement('path', { d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z', fill: 'url(#g)' }), _react2.default.createElement('path', { d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z', fill: '#FFFFFF' }), _react2.default.createElement('path', { d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z', fill: '#182359' }) ); }; /* eslint-enable max-len */ var PoweredBy = function (_Component) { _inherits(PoweredBy, _Component); function PoweredBy() { _classCallCheck(this, PoweredBy); return _possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments)); } _createClass(PoweredBy, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var url = _props.url; return _react2.default.createElement( 'div', cx('root'), _react2.default.createElement( 'span', cx('searchBy'), translate('searchBy'), ' ' ), _react2.default.createElement( 'a', _extends({ href: url, target: '_blank' }, cx('algoliaLink')), _react2.default.createElement(AlgoliaLogo, null) ) ); } }]); return PoweredBy; }(_react.Component); PoweredBy.propTypes = { url: _propTypes2.default.string.isRequired, translate: _propTypes2.default.func.isRequired }; exports.default = (0, _translatable2.default)({ searchBy: 'Search by' })(PoweredBy); /***/ }), /* 390 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isNaN2 = __webpack_require__(218); var _isNaN3 = _interopRequireDefault(_isNaN2); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('RangeInput'); var RangeInput = function (_Component) { _inherits(RangeInput, _Component); function RangeInput(props) { _classCallCheck(this, RangeInput); var _this = _possibleConstructorReturn(this, (RangeInput.__proto__ || Object.getPrototypeOf(RangeInput)).call(this, props)); _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); if (!(0, _isNaN3.default)(parseFloat(_this.state.from, 10)) && !(0, _isNaN3.default)(parseFloat(_this.state.to, 10))) { _this.props.refine({ min: _this.state.from, max: _this.state.to }); } }; _this.state = _this.props.canRefine ? { from: props.currentRefinement.min, to: props.currentRefinement.max } : { from: '', to: '' }; return _this; } _createClass(RangeInput, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.canRefine) { this.setState({ from: nextProps.currentRefinement.min, to: nextProps.currentRefinement.max }); } if (this.context.canRefine) this.context.canRefine(nextProps.canRefine); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var canRefine = _props.canRefine; return _react2.default.createElement( 'form', _extends({}, cx('root', !canRefine && 'noRefinement'), { onSubmit: this.onSubmit }), _react2.default.createElement( 'fieldset', _extends({ disabled: !canRefine }, cx('fieldset')), _react2.default.createElement( 'label', cx('labelMin'), _react2.default.createElement('input', _extends({}, cx('inputMin'), { type: 'number', value: this.state.from, onChange: function onChange(e) { return _this2.setState({ from: e.target.value }); } })) ), _react2.default.createElement( 'span', cx('separator'), translate('separator') ), _react2.default.createElement( 'label', cx('labelMax'), _react2.default.createElement('input', _extends({}, cx('inputMax'), { type: 'number', value: this.state.to, onChange: function onChange(e) { return _this2.setState({ to: e.target.value }); } })) ), _react2.default.createElement( 'button', _extends({}, cx('submit'), { type: 'submit' }), translate('submit') ) ) ); } }]); return RangeInput; }(_react.Component); RangeInput.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, min: _propTypes2.default.number, max: _propTypes2.default.number, currentRefinement: _propTypes2.default.shape({ min: _propTypes2.default.number, max: _propTypes2.default.number }), canRefine: _propTypes2.default.bool.isRequired }; RangeInput.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ submit: 'ok', separator: 'to' })(RangeInput); /***/ }), /* 391 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _Highlight = __webpack_require__(235); var _Highlight2 = _interopRequireDefault(_Highlight); 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; } var cx = (0, _classNames2.default)('RefinementList'); var RefinementList = function (_Component) { _inherits(RefinementList, _Component); function RefinementList(props) { _classCallCheck(this, RefinementList); var _this = _possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props)); _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }; _this.renderItem = function (item, resetQuery) { var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label; return _react2.default.createElement( 'label', null, _react2.default.createElement('input', _extends({}, cx('itemCheckbox', item.isRefined && 'itemCheckboxSelected'), { type: 'checkbox', checked: item.isRefined, onChange: function onChange() { return _this.selectItem(item, resetQuery); } })), _react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), _react2.default.createElement( 'span', cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', _react2.default.createElement( 'span', cx('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }; _this.state = { query: '' }; return _this; } _createClass(RefinementList, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement( 'div', null, _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']), { query: this.state.query })) ); } }]); return RefinementList; }(_react.Component); RefinementList.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, searchForItems: _propTypes2.default.func.isRequired, withSearchBox: _propTypes2.default.bool, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.arrayOf(_propTypes2.default.string).isRequired, count: _propTypes2.default.number.isRequired, isRefined: _propTypes2.default.bool.isRequired })), isFromSearch: _propTypes2.default.bool.isRequired, canRefine: _propTypes2.default.bool.isRequired, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; RefinementList.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(RefinementList); /***/ }), /* 392 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _reactDom = __webpack_require__(429); 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; } var ScrollTo = function (_Component) { _inherits(ScrollTo, _Component); function ScrollTo() { _classCallCheck(this, ScrollTo); return _possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments)); } _createClass(ScrollTo, [{ key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { var value = this.props.value; if (value !== prevProps.value) { var el = (0, _reactDom.findDOMNode)(this); el.scrollIntoView(); } } }, { key: 'render', value: function render() { return _react.Children.only(this.props.children); } }]); return ScrollTo; }(_react.Component); ScrollTo.propTypes = { value: _propTypes2.default.any, children: _propTypes2.default.node }; exports.default = ScrollTo; /***/ }), /* 393 */ /***/ (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; }; exports.default = Snippet; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(345); var _Highlighter2 = _interopRequireDefault(_Highlighter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Snippet(props) { return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_snippetResult' }, props)); } Snippet.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 394 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(347); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('SortBy'); var SortBy = function (_Component) { _inherits(SortBy, _Component); function SortBy() { var _ref; var _temp, _this, _ret; _classCallCheck(this, SortBy); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = SortBy.__proto__ || Object.getPrototypeOf(SortBy)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(SortBy, [{ key: 'render', value: function render() { var _props = this.props; var refine = _props.refine; var items = _props.items; var currentRefinement = _props.currentRefinement; return _react2.default.createElement(_Select2.default, { cx: cx, selectedItem: currentRefinement, onSelect: refine, items: items }); } }]); return SortBy; }(_react.Component); SortBy.propTypes = { refine: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string, value: _propTypes2.default.string.isRequired })).isRequired, currentRefinement: _propTypes2.default.string.isRequired, transformItems: _propTypes2.default.func }; exports.default = SortBy; /***/ }), /* 395 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('StarRating'); var StarRating = function (_Component) { _inherits(StarRating, _Component); function StarRating() { _classCallCheck(this, StarRating); return _possibleConstructorReturn(this, (StarRating.__proto__ || Object.getPrototypeOf(StarRating)).apply(this, arguments)); } _createClass(StarRating, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'onClick', value: function onClick(min, max, e) { e.preventDefault(); e.stopPropagation(); if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) { this.props.refine({ min: this.props.min, max: this.props.max }); } else { this.props.refine({ min: min, max: max }); } } }, { key: 'buildItem', value: function buildItem(_ref) { var max = _ref.max; var lowerBound = _ref.lowerBound; var count = _ref.count; var translate = _ref.translate; var createURL = _ref.createURL; var isLastSelectableItem = _ref.isLastSelectableItem; var disabled = !count; var isCurrentMinLower = this.props.currentRefinement.min < lowerBound; var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max; var icons = []; for (var icon = 0; icon < max; icon++) { var iconTheme = icon >= lowerBound ? 'ratingIconEmpty' : 'ratingIcon'; icons.push(_react2.default.createElement('span', _extends({ key: icon }, cx(iconTheme, selected && iconTheme + 'Selected', disabled && iconTheme + 'Disabled')))); } // The last item of the list (the default item), should not // be clickable if it is selected. var isLastAndSelect = isLastSelectableItem && selected; var StarsWrapper = isLastAndSelect ? 'div' : 'a'; var onClickHandler = isLastAndSelect ? {} : { href: createURL({ min: lowerBound, max: max }), onClick: this.onClick.bind(this, lowerBound, max) }; return _react2.default.createElement( StarsWrapper, _extends({}, cx('ratingLink', selected && 'ratingLinkSelected', disabled && 'ratingLinkDisabled'), { disabled: disabled, key: lowerBound }, onClickHandler), icons, _react2.default.createElement( 'span', cx('ratingLabel', selected && 'ratingLabelSelected', disabled && 'ratingLabelDisabled'), translate('ratingLabel') ), _react2.default.createElement( 'span', null, ' ' ), _react2.default.createElement( 'span', cx('ratingCount', selected && 'ratingCountSelected', disabled && 'ratingCountDisabled'), count ) ); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var refine = _props.refine; var min = _props.min; var max = _props.max; var count = _props.count; var createURL = _props.createURL; var canRefine = _props.canRefine; var items = []; var _loop = function _loop(i) { var hasCount = !(0, _isEmpty3.default)(count.filter(function (item) { return Number(item.value) === i; })); var lastSelectableItem = count.reduce(function (acc, item) { return item.value < acc.value || !acc.value && hasCount ? item : acc; }, {}); var itemCount = count.reduce(function (acc, item) { return item.value >= i && hasCount ? acc + item.count : acc; }, 0); items.push(_this2.buildItem({ lowerBound: i, max: max, refine: refine, count: itemCount, translate: translate, createURL: createURL, isLastSelectableItem: i === Number(lastSelectableItem.value) })); }; for (var i = max; i >= min; i--) { _loop(i); } return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), items ); } }]); return StarRating; }(_react.Component); StarRating.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, min: _propTypes2.default.number, max: _propTypes2.default.number, currentRefinement: _propTypes2.default.shape({ min: _propTypes2.default.number, max: _propTypes2.default.number }), count: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.string, count: _propTypes2.default.number })), canRefine: _propTypes2.default.bool.isRequired }; StarRating.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ ratingLabel: ' & Up' })(StarRating); /***/ }), /* 396 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('Stats'); var Stats = function (_Component) { _inherits(Stats, _Component); function Stats() { _classCallCheck(this, Stats); return _possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments)); } _createClass(Stats, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var nbHits = _props.nbHits; var processingTimeMS = _props.processingTimeMS; return _react2.default.createElement( 'span', cx('root'), translate('stats', nbHits, processingTimeMS) ); } }]); return Stats; }(_react.Component); Stats.propTypes = { translate: _propTypes2.default.func.isRequired, nbHits: _propTypes2.default.number.isRequired, processingTimeMS: _propTypes2.default.number.isRequired }; exports.default = (0, _translatable2.default)({ stats: function stats(n, ms) { return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms'; } })(Stats); /***/ }), /* 397 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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; } var cx = (0, _classNames2.default)('Toggle'); var Toggle = function (_Component) { _inherits(Toggle, _Component); function Toggle() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Toggle); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Toggle.__proto__ || Object.getPrototypeOf(Toggle)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.checked); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Toggle, [{ key: 'render', value: function render() { var _props = this.props; var currentRefinement = _props.currentRefinement; var label = _props.label; return _react2.default.createElement( 'label', cx('root'), _react2.default.createElement('input', _extends({}, cx('checkbox'), { type: 'checkbox', checked: currentRefinement, onChange: this.onChange })), _react2.default.createElement( 'span', cx('label'), label ) ); } }]); return Toggle; }(_react.Component); Toggle.propTypes = { currentRefinement: _propTypes2.default.bool.isRequired, refine: _propTypes2.default.func.isRequired, label: _propTypes2.default.string.isRequired }; exports.default = Toggle; /***/ }), /* 398 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); 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; } /* eslint valid-jsdoc: 0 */ /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @example * import {InstantSearch, Index, SearchBox, Hits, Configure} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch appId="" apiKey="" indexName="index1"> <SearchBox/> <Configure hitsPerPage={1} /> <Index indexName="index1"> <Hits /> </Index> <Index indexName="index2"> <Hits /> </Index> </InstantSearch> * ); * } */ var Index = function (_Component) { _inherits(Index, _Component); function Index() { _classCallCheck(this, Index); return _possibleConstructorReturn(this, (Index.__proto__ || Object.getPrototypeOf(Index)).apply(this, arguments)); } _createClass(Index, [{ key: 'getChildContext', value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexName } }; } }, { key: 'render', value: function render() { var childrenCount = _react.Children.count(this.props.children); var _props$root = this.props.root; var Root = _props$root.Root; var props = _props$root.props; if (childrenCount === 0) return null;else return _react2.default.createElement( Root, props, this.props.children ); } }]); return Index; }(_react.Component); Index.propTypes = { // @TODO: These props are currently constant. indexName: _propTypes2.default.string.isRequired, children: _propTypes2.default.node, root: _propTypes2.default.shape({ Root: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]), props: _propTypes2.default.object }).isRequired }; Index.childContextTypes = { // @TODO: more precise widgets manager propType multiIndexContext: _propTypes2.default.object.isRequired }; exports.default = Index; /***/ }), /* 399 */ /***/ (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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _createInstantSearchManager = __webpack_require__(400); var _createInstantSearchManager2 = _interopRequireDefault(_createInstantSearchManager); 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; } function validateNextProps(props, nextProps) { if (!props.searchState && nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } else if (props.searchState && !nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } } /* eslint valid-jsdoc: 0 */ /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @example * import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch * appId="appId" * apiKey="apiKey" * indexName="indexName" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); * } */ var InstantSearch = function (_Component) { _inherits(InstantSearch, _Component); function InstantSearch(props) { _classCallCheck(this, InstantSearch); var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = (0, _createInstantSearchManager2.default)({ indexName: props.indexName, searchParameters: props.searchParameters, algoliaClient: props.algoliaClient, initialState: initialState }); return _this; } _createClass(InstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: 'getChildContext', value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this) } }; } return { ais: _extends({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: 'createHrefForState', value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: 'onWidgetsInternalStateUpdate', value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: 'onSearchStateChange', value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: 'onSearchForFacetValues', value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: 'getKnownKeys', value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: 'render', value: function render() { var childrenCount = _react.Children.count(this.props.children); var _props$root = this.props.root; var Root = _props$root.Root; var props = _props$root.props; if (childrenCount === 0) return null;else return _react2.default.createElement( Root, props, this.props.children ); } }]); return InstantSearch; }(_react.Component); InstantSearch.propTypes = { // @TODO: These props are currently constant. indexName: _propTypes2.default.string.isRequired, algoliaClient: _propTypes2.default.object.isRequired, searchParameters: _propTypes2.default.object, createURL: _propTypes2.default.func, searchState: _propTypes2.default.object, onSearchStateChange: _propTypes2.default.func, children: _propTypes2.default.node, root: _propTypes2.default.shape({ Root: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]), props: _propTypes2.default.object }).isRequired }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: _propTypes2.default.object.isRequired }; exports.default = InstantSearch; /***/ }), /* 400 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(38); 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; }; exports.default = createInstantSearchManager; var _algoliasearchHelper = __webpack_require__(214); var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper); var _createWidgetsManager = __webpack_require__(402); var _createWidgetsManager2 = _interopRequireDefault(_createWidgetsManager); var _createStore = __webpack_require__(401); var _createStore2 = _interopRequireDefault(_createStore); var _highlightTags = __webpack_require__(213); var _highlightTags2 = _interopRequireDefault(_highlightTags); 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; } /** * Creates a new instance of the InstantSearchManager which controls the widgets and * trigger the search when the widgets are updated. * @param {string} indexName - the main index name * @param {object} initialState - initial widget state * @param {object} SearchParameters - optional additional parameters to send to the algolia API * @return {InstantSearchManager} a new instance of InstantSearchManager */ function createInstantSearchManager(_ref) { var indexName = _ref.indexName; var _ref$initialState = _ref.initialState; var initialState = _ref$initialState === undefined ? {} : _ref$initialState; var algoliaClient = _ref.algoliaClient; var _ref$searchParameters = _ref.searchParameters; var searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters; var baseSP = new _algoliasearchHelper.SearchParameters(_extends({}, searchParameters, { index: indexName }, _highlightTags2.default)); var helper = (0, _algoliasearchHelper2.default)(algoliaClient, indexName, baseSP); helper.on('result', handleSearchSuccess); helper.on('error', handleSearchError); var derivedHelpers = {}; var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used. var initialSearchParameters = helper.state; var widgetsManager = (0, _createWidgetsManager2.default)(onWidgetsUpdate); var store = (0, _createStore2.default)({ widgets: initialState, metadata: [], results: null, error: null, searching: false }); var skip = false; function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { indexMapping = {}; var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !widget.multiIndexContext; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); indexMapping[sharedParameters.index] = indexName; var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.multiIndexContext && widget.multiIndexContext.targetedIndex !== indexName; }).reduce(function (indices, widget) { var targetedIndex = widget.multiIndexContext.targetedIndex; var index = indices.find(function (i) { return i.targetedIndex === targetedIndex; }); if (index) { index.widgets.push(widget); } else { indices.push({ targetedIndex: targetedIndex, widgets: [widget] }); } return indices; }, []); var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.multiIndexContext && widget.multiIndexContext.targetedIndex === indexName; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(helper.state); var sharedParameters = _getSearchParameters.sharedParameters; var mainIndexParameters = _getSearchParameters.mainIndexParameters; var derivatedWidgets = _getSearchParameters.derivatedWidgets; Object.keys(derivedHelpers).forEach(function (key) { return derivedHelpers[key].detach(); }); derivedHelpers = {}; helper.setState(sharedParameters); derivatedWidgets.forEach(function (derivatedSearchParameters) { var index = derivatedSearchParameters.targetedIndex; var derivedHelper = helper.derive(function () { var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters.setIndex(index)); indexMapping[parameters.index] = index; return parameters; }); derivedHelper.on('result', handleSearchSuccess); derivedHelper.on('error', handleSearchError); derivedHelpers[index] = derivedHelper; }); helper.setState(mainIndexParameters); helper.search(); } } function handleSearchSuccess(content) { var state = store.getState(); var results = state.results ? state.results : []; if (!(0, _isEmpty3.default)(derivedHelpers)) { results[indexMapping[content.index]] = content; } else { results = content; } var nextState = (0, _omit3.default)(_extends({}, store.getState(), { results: results, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleSearchError(error) { var nextState = (0, _omit3.default)(_extends({}, store.getState(), { error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_extends({}, store.getState(), { metadata: metadata, searching: true })); // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); } function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.transitionState); }).reduce(function (res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); } function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_extends({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(nextSearchState) { store.setState(_extends({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(nextSearchState.facetName, nextSearchState.query).then(function (content) { var _extends2; store.setState(_extends({}, store.getState(), { resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_extends2 = {}, _defineProperty(_extends2, nextSearchState.facetName, content.facetHits), _defineProperty(_extends2, 'query', nextSearchState.query), _extends2)), searchingForFacetValues: false })); }, function (error) { store.setState(_extends({}, store.getState(), { error: error, searchingForFacetValues: false })); }).catch(function (error) { // Since setState is synchronous, any error that occurs in the render of a // component will be swallowed by this promise. // This is a trick to make the error show up correctly in the console. // See http://stackoverflow.com/a/30741722/969302 setTimeout(function () { throw error; }); }); } function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); search(); } function getWidgetsIds() { return store.getState().metadata.reduce(function (res, meta) { return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res; }, []); } return { store: store, widgetsManager: widgetsManager, getWidgetsIds: getWidgetsIds, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, onSearchForFacetValues: onSearchForFacetValues, updateClient: updateClient, updateIndex: updateIndex, skipSearch: skipSearch }; } /***/ }), /* 401 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createStore; function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } /***/ }), /* 402 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createWidgetsManager; var _utils = __webpack_require__(58); function createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; (0, _utils.defer)(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } /***/ }), /* 403 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withKeysPropType = exports.stateManagerPropType = exports.configManagerPropType = undefined; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var configManagerPropType = exports.configManagerPropType = _propTypes2.default.shape({ register: _propTypes2.default.func.isRequired, swap: _propTypes2.default.func.isRequired, unregister: _propTypes2.default.func.isRequired }); var stateManagerPropType = exports.stateManagerPropType = _propTypes2.default.shape({ createURL: _propTypes2.default.func.isRequired, setState: _propTypes2.default.func.isRequired, getState: _propTypes2.default.func.isRequired, unlisten: _propTypes2.default.func.isRequired }); var withKeysPropType = exports.withKeysPropType = function withKeysPropType(keys) { return function (props, propName, componentName) { var prop = props[propName]; if (prop) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var key = _step.value; if (keys.indexOf(key) === -1) { return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.')); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } return undefined; }; }; /***/ }), /* 404 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {module.exports = AlgoliaSearchCore; var errors = __webpack_require__(215); var exitPromise = __webpack_require__(412); var IndexCore = __webpack_require__(405); var store = __webpack_require__(416); // We will always put the API KEY in the JSON body in case of too long API KEY, // to avoid query string being too long and failing in various conditions (our server limit, browser limit, // proxies limit) var MAX_API_KEY_LENGTH = 500; var RESET_APP_DATA_TIMER = process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) || 60 * 2 * 1000; // after 2 minutes reset to first host /* * Algolia Search library initialization * https://www.algolia.com/ * * @param {string} applicationID - Your applicationID, found in your dashboard * @param {string} apiKey - Your API key, found in your dashboard * @param {Object} [opts] * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds, * another request will be issued after this timeout * @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API. * Set to 'https:' to force using https. * Default to document.location.protocol in browsers * @param {Object|Array} [opts.hosts={ * read: [this.applicationID + '-dsn.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]), * write: [this.applicationID + '.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]) - The hosts to use for Algolia Search API. * If you provide them, you will less benefit from our HA implementation */ function AlgoliaSearchCore(applicationID, apiKey, opts) { var debug = __webpack_require__(216)('algoliasearch'); var clone = __webpack_require__(119); var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)'; if (opts._allowEmptyCredentials !== true && !applicationID) { throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage); } if (opts._allowEmptyCredentials !== true && !apiKey) { throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage); } this.applicationID = applicationID; this.apiKey = apiKey; this.hosts = { read: [], write: [] }; opts = opts || {}; var protocol = opts.protocol || 'https:'; this._timeouts = opts.timeouts || { connect: 1 * 1000, // 500ms connect is GPRS latency read: 2 * 1000, write: 30 * 1000 }; // backward compat, if opts.timeout is passed, we use it to configure all timeouts like before if (opts.timeout) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout; } // while we advocate for colon-at-the-end values: 'http:' for `opts.protocol` // we also accept `http` and `https`. It's a common error. if (!/:$/.test(protocol)) { protocol = protocol + ':'; } if (opts.protocol !== 'http:' && opts.protocol !== 'https:') { throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)'); } this._checkAppIdData(); if (!opts.hosts) { var defaultHosts = map(this._shuffleResult, function(hostNumber) { return applicationID + '-' + hostNumber + '.algolianet.com'; }); // no hosts given, compute defaults this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts); this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts); } else if (isArray(opts.hosts)) { // when passing custom hosts, we need to have a different host index if the number // of write/read hosts are different. this.hosts.read = clone(opts.hosts); this.hosts.write = clone(opts.hosts); } else { this.hosts.read = clone(opts.hosts.read); this.hosts.write = clone(opts.hosts.write); } // add protocol and lowercase hosts this.hosts.read = map(this.hosts.read, prepareHost(protocol)); this.hosts.write = map(this.hosts.write, prepareHost(protocol)); this.extraHeaders = []; // In some situations you might want to warm the cache this.cache = opts._cache || {}; this._ua = opts._ua; this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache; this._useFallback = opts.useFallback === undefined ? true : opts.useFallback; this._setTimeout = opts._setTimeout; debug('init done, %j', this); } /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ AlgoliaSearchCore.prototype.initIndex = function(indexName) { return new IndexCore(this, indexName); }; /** * Add an extra field to the HTTP request * * @param name the header field name * @param value the header field value */ AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) { this.extraHeaders.push({ name: name.toLowerCase(), value: value }); }; /** * Augment sent x-algolia-agent with more data, each agent part * is automatically separated from the others by a semicolon; * * @param algoliaAgent the agent to add */ AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) { if (this._ua.indexOf(';' + algoliaAgent) === -1) { this._ua += ';' + algoliaAgent; } }; /* * Wrapper that try all hosts to maximize the quality of service */ AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) { this._checkAppIdData(); var requestDebug = __webpack_require__(216)('algoliasearch:' + initialOpts.url); var body; var additionalUA = initialOpts.additionalUA || ''; var cache = initialOpts.cache; var client = this; var tries = 0; var usingFallback = false; var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback; var headers; if ( this.apiKey.length > MAX_API_KEY_LENGTH && initialOpts.body !== undefined && (initialOpts.body.params !== undefined || // index.search() initialOpts.body.requests !== undefined) // client.search() ) { initialOpts.body.apiKey = this.apiKey; headers = this._computeRequestHeaders(additionalUA, false); } else { headers = this._computeRequestHeaders(additionalUA); } if (initialOpts.body !== undefined) { body = safeJSONStringify(initialOpts.body); } requestDebug('request start'); var debugData = []; function doRequest(requester, reqOpts) { client._checkAppIdData(); var startTime = new Date(); var cacheID; if (client._useCache) { cacheID = initialOpts.url; } // as we sometime use POST requests to pass parameters (like query='aa'), // the cacheID must also include the body to be different between calls if (client._useCache && body) { cacheID += '_body_' + reqOpts.body; } // handle cache existence if (client._useCache && cache && cache[cacheID] !== undefined) { requestDebug('serving response from cache'); return client._promise.resolve(JSON.parse(cache[cacheID])); } // if we reached max tries if (tries >= client.hosts[initialOpts.hostType].length) { if (!hasFallback || usingFallback) { requestDebug('could not get any response'); // then stop return client._promise.reject(new errors.AlgoliaSearchError( 'Cannot connect to the AlgoliaSearch API.' + ' Send an email to [email protected] to report and resolve the issue.' + ' Application id was: ' + client.applicationID, {debugData: debugData} )); } requestDebug('switching to fallback'); // let's try the fallback starting from here tries = 0; // method, url and body are fallback dependent reqOpts.method = initialOpts.fallback.method; reqOpts.url = initialOpts.fallback.url; reqOpts.jsonBody = initialOpts.fallback.body; if (reqOpts.jsonBody) { reqOpts.body = safeJSONStringify(reqOpts.jsonBody); } // re-compute headers, they could be omitting the API KEY headers = client._computeRequestHeaders(additionalUA); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); client._setHostIndexByType(0, initialOpts.hostType); usingFallback = true; // the current request is now using fallback return doRequest(client._request.fallback, reqOpts); } var currentHost = client._getHostByType(initialOpts.hostType); var url = currentHost + reqOpts.url; var options = { body: reqOpts.body, jsonBody: reqOpts.jsonBody, method: reqOpts.method, headers: headers, timeouts: reqOpts.timeouts, debug: requestDebug }; requestDebug('method: %s, url: %s, headers: %j, timeouts: %d', options.method, url, options.headers, options.timeouts); if (requester === client._request.fallback) { requestDebug('using fallback'); } // `requester` is any of this._request or this._request.fallback // thus it needs to be called using the client as context return requester.call(client, url, options).then(success, tryFallback); function success(httpResponse) { // compute the status of the response, // // When in browser mode, using XDR or JSONP, we have no statusCode available // So we rely on our API response `status` property. // But `waitTask` can set a `status` property which is not the statusCode (it's the task status) // So we check if there's a `message` along `status` and it means it's an error // // That's the only case where we have a response.status that's not the http statusCode var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status || // this is important to check the request statusCode AFTER the body eventual // statusCode because some implementations (jQuery XDomainRequest transport) may // send statusCode 200 while we had an error httpResponse.statusCode || // When in browser mode, using XDR or JSONP // we default to success when no error (no response.status && response.message) // If there was a JSON.parse() error then body is null and it fails httpResponse && httpResponse.body && 200; requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j', httpResponse.statusCode, status, httpResponse.headers); var httpResponseOk = Math.floor(status / 100) === 2; var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime, statusCode: status }); if (httpResponseOk) { if (client._useCache && cache) { cache[cacheID] = httpResponse.responseText; } return httpResponse.body; } var shouldRetry = Math.floor(status / 100) !== 4; if (shouldRetry) { tries += 1; return retryRequest(); } requestDebug('unrecoverable error'); // no success and no retry => fail var unrecoverableError = new errors.AlgoliaSearchError( httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status} ); return client._promise.reject(unrecoverableError); } function tryFallback(err) { // error cases: // While not in fallback mode: // - CORS not supported // - network error // While in fallback mode: // - timeout // - network error // - badly formatted JSONP (script loaded, did not call our callback) // In both cases: // - uncaught exception occurs (TypeError) requestDebug('error: %s, stack: %s', err.message, err.stack); var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime }); if (!(err instanceof errors.AlgoliaSearchError)) { err = new errors.Unknown(err && err.message, err); } tries += 1; // stop the request implementation when: if ( // we did not generate this error, // it comes from a throw in some other piece of code err instanceof errors.Unknown || // server sent unparsable JSON err instanceof errors.UnparsableJSON || // max tries and already using fallback or no fallback tries >= client.hosts[initialOpts.hostType].length && (usingFallback || !hasFallback)) { // stop request implementation for this command err.debugData = debugData; return client._promise.reject(err); } // When a timeout occured, retry by raising timeout if (err instanceof errors.RequestTimeout) { return retryRequestWithHigherTimeout(); } return retryRequest(); } function retryRequest() { requestDebug('retrying request'); client._incrementHostIndex(initialOpts.hostType); return doRequest(requester, reqOpts); } function retryRequestWithHigherTimeout() { requestDebug('retrying request with higher timeout'); client._incrementHostIndex(initialOpts.hostType); client._incrementTimeoutMultipler(); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); return doRequest(requester, reqOpts); } } var promise = doRequest( client._request, { url: initialOpts.url, method: initialOpts.method, body: body, jsonBody: initialOpts.body, timeouts: client._getTimeoutsForRequest(initialOpts.hostType) } ); // either we have a callback // either we are using promises if (initialOpts.callback) { promise.then(function okCb(content) { exitPromise(function() { initialOpts.callback(null, content); }, client._setTimeout || setTimeout); }, function nookCb(err) { exitPromise(function() { initialOpts.callback(err); }, client._setTimeout || setTimeout); }); } else { return promise; } }; /* * Transform search param object in query string * @param {object} args arguments to add to the current query string * @param {string} params current query string * @return {string} the final query string */ AlgoliaSearchCore.prototype._getSearchParams = function(args, params) { if (args === undefined || args === null) { return params; } for (var key in args) { if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) { params += params === '' ? '' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]); } } return params; }; AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) { var forEach = __webpack_require__(110); var ua = additionalUA ? this._ua + ';' + additionalUA : this._ua; var requestHeaders = { 'x-algolia-agent': ua, 'x-algolia-application-id': this.applicationID }; // browser will inline headers in the url, node.js will use http headers // but in some situations, the API KEY will be too long (big secured API keys) // so if the request is a POST and the KEY is very long, we will be asked to not put // it into headers but in the JSON body if (withAPIKey !== false) { requestHeaders['x-algolia-api-key'] = this.apiKey; } if (this.userToken) { requestHeaders['x-algolia-usertoken'] = this.userToken; } if (this.securityTags) { requestHeaders['x-algolia-tagfilters'] = this.securityTags; } if (this.extraHeaders) { forEach(this.extraHeaders, function addToRequestHeaders(header) { requestHeaders[header.name] = header.value; }); } return requestHeaders; }; /** * Search through multiple indices at the same time * @param {Object[]} queries An array of queries you want to run. * @param {string} queries[].indexName The index name you want to target * @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params` * @param {Object} queries[].params Any search param like hitsPerPage, .. * @param {Function} callback Callback to be called * @return {Promise|undefined} Returns a promise if no callback given */ AlgoliaSearchCore.prototype.search = function(queries, opts, callback) { var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: client.search(arrayOfQueries[, callback])'; if (!isArray(queries)) { throw new Error(usage); } if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } var client = this; var postObj = { requests: map(queries, function prepareRequest(query) { var params = ''; // allow query.query // so we are mimicing the index.search(query, params) method // {indexName:, query:, params:} if (query.query !== undefined) { params += 'query=' + encodeURIComponent(query.query); } return { indexName: query.indexName, params: client._getSearchParams(query.params, params) }; }) }; var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) { return requestId + '=' + encodeURIComponent( '/1/indexes/' + encodeURIComponent(request.indexName) + '?' + request.params ); }).join('&'); var url = '/1/indexes/*/queries'; if (opts.strategy !== undefined) { url += '?strategy=' + opts.strategy; } return this._jsonRequest({ cache: this.cache, method: 'POST', url: url, body: postObj, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/*', body: { params: JSONPParams } }, callback: callback }); }; /** * Set the extra security tagFilters header * @param {string|array} tags The list of tags defining the current security filters */ AlgoliaSearchCore.prototype.setSecurityTags = function(tags) { if (Object.prototype.toString.call(tags) === '[object Array]') { var strTags = []; for (var i = 0; i < tags.length; ++i) { if (Object.prototype.toString.call(tags[i]) === '[object Array]') { var oredTags = []; for (var j = 0; j < tags[i].length; ++j) { oredTags.push(tags[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tags[i]); } } tags = strTags.join(','); } this.securityTags = tags; }; /** * Set the extra user token header * @param {string} userToken The token identifying a uniq user (used to apply rate limits) */ AlgoliaSearchCore.prototype.setUserToken = function(userToken) { this.userToken = userToken; }; /** * Clear all queries in client's cache * @return undefined */ AlgoliaSearchCore.prototype.clearCache = function() { this.cache = {}; }; /** * Set the number of milliseconds a request can take before automatically being terminated. * @deprecated * @param {Number} milliseconds */ AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) { if (milliseconds) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds; } }; /** * Set the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) { this._timeouts = timeouts; }; /** * Get the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.getTimeouts = function() { return this._timeouts; }; AlgoliaSearchCore.prototype._getAppIdData = function() { var data = store.get(this.applicationID); if (data !== null) this._cacheAppIdData(data); return data; }; AlgoliaSearchCore.prototype._setAppIdData = function(data) { data.lastChange = (new Date()).getTime(); this._cacheAppIdData(data); return store.set(this.applicationID, data); }; AlgoliaSearchCore.prototype._checkAppIdData = function() { var data = this._getAppIdData(); var now = (new Date()).getTime(); if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) { return this._resetInitialAppIdData(data); } return data; }; AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) { var newData = data || {}; newData.hostIndexes = {read: 0, write: 0}; newData.timeoutMultiplier = 1; newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]); return this._setAppIdData(newData); }; AlgoliaSearchCore.prototype._cacheAppIdData = function(data) { this._hostIndexes = data.hostIndexes; this._timeoutMultiplier = data.timeoutMultiplier; this._shuffleResult = data.shuffleResult; }; AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) { var foreach = __webpack_require__(110); var currentData = this._getAppIdData(); foreach(newData, function(value, key) { currentData[key] = value; }); return this._setAppIdData(currentData); }; AlgoliaSearchCore.prototype._getHostByType = function(hostType) { return this.hosts[hostType][this._getHostIndexByType(hostType)]; }; AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() { return this._timeoutMultiplier; }; AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) { return this._hostIndexes[hostType]; }; AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) { var clone = __webpack_require__(119); var newHostIndexes = clone(this._hostIndexes); newHostIndexes[hostType] = hostIndex; this._partialAppIdDataUpdate({hostIndexes: newHostIndexes}); return hostIndex; }; AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) { return this._setHostIndexByType( (this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType ); }; AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() { var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4); return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier}); }; AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) { return { connect: this._timeouts.connect * this._timeoutMultiplier, complete: this._timeouts[hostType] * this._timeoutMultiplier }; }; function prepareHost(protocol) { return function prepare(host) { return protocol + '//' + host.toLowerCase(); }; } // Prototype.js < 1.7, a widely used library, defines a weird // Array.prototype.toJSON function that will fail to stringify our content // appropriately // refs: // - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q // - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c // - http://stackoverflow.com/a/3148441/147079 function safeJSONStringify(obj) { /* eslint no-extend-native:0 */ if (Array.prototype.toJSON === undefined) { return JSON.stringify(obj); } var toJSON = Array.prototype.toJSON; delete Array.prototype.toJSON; var out = JSON.stringify(obj); Array.prototype.toJSON = toJSON; return out; } function shuffle(array) { var currentIndex = array.length; var temporaryValue; var randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function removeCredentials(headers) { var newHeaders = {}; for (var headerName in headers) { if (Object.prototype.hasOwnProperty.call(headers, headerName)) { var value; if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') { value = '**hidden for security purposes**'; } else { value = headers[headerName]; } newHeaders[headerName] = value; } } return newHeaders; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109))) /***/ }), /* 405 */ /***/ (function(module, exports, __webpack_require__) { var buildSearchMethod = __webpack_require__(348); var deprecate = __webpack_require__(410); var deprecatedMessage = __webpack_require__(411); module.exports = IndexCore; /* * Index class constructor. * You should not use this method directly but use initIndex() function */ function IndexCore(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; // make sure every index instance has it's own cache this.cache = {}; } /* * Clear all queries in cache */ IndexCore.prototype.clearCache = function() { this.cache = {}; }; /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the full text query * @param {object} [args] (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, * to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes * you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use an array (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all * values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you * want to highlight according to the query. * Attributes are separated by a comma. You can also use an array (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. * By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. * Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside * the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use an array (Example: attributesToSnippet: ['name:10','content:10']). * By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word * to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking * information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given * latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) * and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of * less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points * of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to * apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. * Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use an array (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]] * means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute * of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use an array (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Comma separated list: `"category,author"` or array `['category','author']` * Only attributes that have been added in **attributesForFaceting** index setting * can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should * be considered as optional when found in the query. * Comma separated and array are accepted. * - distinct: If set to 1, enable the distinct feature (disabled by default) * if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled * in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best * one is kept and others are removed. * - restrictSearchableAttributes: List of attributes you want to use for * textual search (must be a subset of the attributesToIndex index setting) * either comma separated or as an array * @param {function} [callback] the result callback called with two arguments: * error: null or Error('message'). If false, the content contains the error. * content: the server answer that contains the list of results. */ IndexCore.prototype.search = buildSearchMethod('query'); /* * -- BETA -- * Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the similar query * @param {object} [args] (optional) if set, contains an object with query parameters. * All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters * are the two most useful to restrict the similar results and get more relevant content */ IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery'); /* * Browse index content. The response content will have a `cursor` property that you can use * to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browse('cool songs', { * tagFilters: 'public,comments', * hitsPerPage: 500 * }, callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browse = function(query, queryParameters, callback) { var merge = __webpack_require__(413); var indexObj = this; var page; var hitsPerPage; // we check variadic calls that are not the one defined // .browse()/.browse(fn) // => page = 0 if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') { page = 0; callback = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'number') { // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn) page = arguments[0]; if (typeof arguments[1] === 'number') { hitsPerPage = arguments[1]; } else if (typeof arguments[1] === 'function') { callback = arguments[1]; hitsPerPage = undefined; } query = undefined; queryParameters = undefined; } else if (typeof arguments[0] === 'object') { // .browse(queryParameters)/.browse(queryParameters, cb) if (typeof arguments[1] === 'function') { callback = arguments[1]; } queryParameters = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') { // .browse(query, cb) callback = arguments[1]; queryParameters = undefined; } // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb) // get search query parameters combining various possible calls // to .browse(); queryParameters = merge({}, queryParameters || {}, { page: page, hitsPerPage: hitsPerPage, query: query }); var params = this.as._getSearchParams(queryParameters, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse', body: {params: params}, hostType: 'read', callback: callback }); }; /* * Continue browsing from a previous position (cursor), obtained via a call to `.browse()`. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browseFrom('14lkfsakl32', callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browseFrom = function(cursor, callback) { return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse', body: {cursor: cursor}, hostType: 'read', callback: callback }); }; /* * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * * @param {string} params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} params.facetQuery Query for the facet search * @param {string} [params.*] Any search parameter of Algolia, * see https://www.algolia.com/doc/api-client/javascript/search#search-parameters * Pagination is not supported. The page and hitsPerPage parameters will be ignored. * @param callback (optional) */ IndexCore.prototype.searchForFacetValues = function(params, callback) { var clone = __webpack_require__(119); var omit = __webpack_require__(414); var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])'; if (params.facetName === undefined || params.facetQuery === undefined) { throw new Error(usage); } var facetName = params.facetName; var filteredParams = omit(clone(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = this.as._getSearchParams(filteredParams, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters}, callback: callback }); }; IndexCore.prototype.searchFacet = deprecate(function(params, callback) { return this.searchForFacetValues(params, callback); }, deprecatedMessage( 'index.searchFacet(params[, callback])', 'index.searchForFacetValues(params[, callback])' )); IndexCore.prototype._search = function(params, url, callback, additionalUA) { return this.as._jsonRequest({ cache: this.cache, method: 'POST', url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: {params: params}, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: {params: params} }, callback: callback, additionalUA: additionalUA }); }; /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attrs (optional) if set, contains the array of attribute names to retrieve * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the object to retrieve or the error message if a failure occured */ IndexCore.prototype.getObject = function(objectID, attrs, callback) { var indexObj = this; if (arguments.length === 1 || typeof attrs === 'function') { callback = attrs; attrs = undefined; } var params = ''; if (attrs !== undefined) { params = '?attributes='; for (var i = 0; i < attrs.length; ++i) { if (i !== 0) { params += ','; } params += attrs[i]; } } return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params, hostType: 'read', callback: callback }); }; /* * Get several objects from this index * * @param objectIDs the array of unique identifier of objects to retrieve */ IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) { var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])'; if (!isArray(objectIDs)) { throw new Error(usage); } var indexObj = this; if (arguments.length === 1 || typeof attributesToRetrieve === 'function') { callback = attributesToRetrieve; attributesToRetrieve = undefined; } var body = { requests: map(objectIDs, function prepareRequest(objectID) { var request = { indexName: indexObj.indexName, objectID: objectID }; if (attributesToRetrieve) { request.attributesToRetrieve = attributesToRetrieve.join(','); } return request; }) }; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/*/objects', hostType: 'read', body: body, callback: callback }); }; IndexCore.prototype.as = null; IndexCore.prototype.indexName = null; IndexCore.prototype.typeAheadArgs = null; IndexCore.prototype.typeAheadValueOption = null; /***/ }), /* 406 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(421); var Promise = global.Promise || __webpack_require__(420).Promise; // This is the standalone browser build entry point // Browser implementation of the Algolia Search JavaScript client, // using XMLHttpRequest, XDomainRequest and JSONP as fallback module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) { var inherits = __webpack_require__(349); var errors = __webpack_require__(215); var inlineHeaders = __webpack_require__(408); var jsonpRequest = __webpack_require__(409); var places = __webpack_require__(415); uaSuffix = uaSuffix || ''; if (false) { require('debug').enable('algoliasearch*'); } function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = __webpack_require__(119); var getDocumentProtocol = __webpack_require__(407); opts = cloneDeep(opts || {}); if (opts.protocol === undefined) { opts.protocol = getDocumentProtocol(); } opts._ua = opts._ua || algoliasearch.ua; return new AlgoliaSearchBrowser(applicationID, apiKey, opts); } algoliasearch.version = __webpack_require__(417); algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version; algoliasearch.initPlaces = places(algoliasearch); // we expose into window no matter how we are used, this will allow // us to easily debug any website running algolia global.__algolia = { debug: __webpack_require__(216), algoliasearch: algoliasearch }; var support = { hasXMLHttpRequest: 'XMLHttpRequest' in global, hasXDomainRequest: 'XDomainRequest' in global }; if (support.hasXMLHttpRequest) { support.cors = 'withCredentials' in new XMLHttpRequest(); } function AlgoliaSearchBrowser() { // call AlgoliaSearch constructor AlgoliaSearch.apply(this, arguments); } inherits(AlgoliaSearchBrowser, AlgoliaSearch); AlgoliaSearchBrowser.prototype._request = function request(url, opts) { return new Promise(function wrapRequest(resolve, reject) { // no cors or XDomainRequest, no request if (!support.cors && !support.hasXDomainRequest) { // very old browser, not supported reject(new errors.Network('CORS not supported')); return; } url = inlineHeaders(url, opts.headers); var body = opts.body; var req = support.cors ? new XMLHttpRequest() : new XDomainRequest(); var reqTimeout; var timedOut; var connected = false; reqTimeout = setTimeout(onTimeout, opts.timeouts.connect); // we set an empty onprogress listener // so that XDomainRequest on IE9 is not aborted // refs: // - https://github.com/algolia/algoliasearch-client-js/issues/76 // - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment req.onprogress = onProgress; if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange; req.onload = onLoad; req.onerror = onError; // do not rely on default XHR async flag, as some analytics code like hotjar // breaks it and set it to false by default if (req instanceof XMLHttpRequest) { req.open(opts.method, url, true); } else { req.open(opts.method, url); } // headers are meant to be sent after open if (support.cors) { if (body) { if (opts.method === 'POST') { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests req.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); } else { req.setRequestHeader('content-type', 'application/json'); } } req.setRequestHeader('accept', 'application/json'); } req.send(body); // event object not received in IE8, at least // but we do not use it, still important to note function onLoad(/* event */) { // When browser does not supports req.timeout, we can // have both a load and timeout event, since handled by a dumb setTimeout if (timedOut) { return; } clearTimeout(reqTimeout); var out; try { out = { body: JSON.parse(req.responseText), responseText: req.responseText, statusCode: req.status, // XDomainRequest does not have any response headers headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {} }; } catch (e) { out = new errors.UnparsableJSON({ more: req.responseText }); } if (out instanceof errors.UnparsableJSON) { reject(out); } else { resolve(out); } } function onError(event) { if (timedOut) { return; } clearTimeout(reqTimeout); // error event is trigerred both with XDR/XHR on: // - DNS error // - unallowed cross domain request reject( new errors.Network({ more: event }) ); } function onTimeout() { timedOut = true; req.abort(); reject(new errors.RequestTimeout()); } function onConnect() { connected = true; clearTimeout(reqTimeout); reqTimeout = setTimeout(onTimeout, opts.timeouts.complete); } function onProgress() { if (!connected) onConnect(); } function onReadyStateChange() { if (!connected && req.readyState > 1) onConnect(); } }); }; AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) { url = inlineHeaders(url, opts.headers); return new Promise(function wrapJsonpRequest(resolve, reject) { jsonpRequest(url, opts, function jsonpRequestDone(err, content) { if (err) { reject(err); return; } resolve(content); }); }); }; AlgoliaSearchBrowser.prototype._promise = { reject: function rejectPromise(val) { return Promise.reject(val); }, resolve: function resolvePromise(val) { return Promise.resolve(val); }, delay: function delayPromise(ms) { return new Promise(function resolveOnTimeout(resolve/* , reject*/) { setTimeout(resolve, ms); }); } }; return algoliasearch; }; /***/ }), /* 407 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = getDocumentProtocol; function getDocumentProtocol() { var protocol = window.document.location.protocol; // when in `file:` mode (local html file), default to `http:` if (protocol !== 'http:' && protocol !== 'https:') { protocol = 'http:'; } return protocol; } /***/ }), /* 408 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = inlineHeaders; var encode = __webpack_require__(428); function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode(headers); } /***/ }), /* 409 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = jsonpRequest; var errors = __webpack_require__(215); var JSONPCounter = 0; function jsonpRequest(url, opts, cb) { if (opts.method !== 'GET') { cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.')); return; } opts.debug('JSONP: start'); var cbCalled = false; var timedOut = false; JSONPCounter += 1; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); var cbName = 'algoliaJSONP_' + JSONPCounter; var done = false; window[cbName] = function(data) { removeGlobals(); if (timedOut) { opts.debug('JSONP: Late answer, ignoring'); return; } cbCalled = true; clean(); cb(null, { body: data/* , // We do not send the statusCode, there's no statusCode in JSONP, it will be // computed using data.status && data.message like with XDR statusCode*/ }); }; // add callback by hand url += '&callback=' + cbName; // add body params manually if (opts.jsonBody && opts.jsonBody.params) { url += '&' + opts.jsonBody.params; } var ontimeout = setTimeout(timeout, opts.timeouts.complete); // script onreadystatechange needed only for // <= IE8 // https://github.com/angular/angular.js/issues/4523 script.onreadystatechange = readystatechange; script.onload = success; script.onerror = error; script.async = true; script.defer = true; script.src = url; head.appendChild(script); function success() { opts.debug('JSONP: success'); if (done || timedOut) { return; } done = true; // script loaded but did not call the fn => script loading error if (!cbCalled) { opts.debug('JSONP: Fail. Script loaded but did not call the callback'); clean(); cb(new errors.JSONPScriptFail()); } } function readystatechange() { if (this.readyState === 'loaded' || this.readyState === 'complete') { success(); } } function clean() { clearTimeout(ontimeout); script.onload = null; script.onreadystatechange = null; script.onerror = null; head.removeChild(script); } function removeGlobals() { try { delete window[cbName]; delete window[cbName + '_loaded']; } catch (e) { window[cbName] = window[cbName + '_loaded'] = undefined; } } function timeout() { opts.debug('JSONP: Script timeout'); timedOut = true; clean(); cb(new errors.RequestTimeout()); } function error() { opts.debug('JSONP: Script error'); if (done || timedOut) { return; } clean(); cb(new errors.JSONPScriptError()); } } /***/ }), /* 410 */ /***/ (function(module, exports) { module.exports = function deprecate(fn, message) { var warned = false; function deprecated() { if (!warned) { /* eslint no-console:0 */ console.log(message); warned = true; } return fn.apply(this, arguments); } return deprecated; }; /***/ }), /* 411 */ /***/ (function(module, exports) { module.exports = function deprecatedMessage(previousUsage, newUsage) { var githubAnchorLink = previousUsage.toLowerCase() .replace('.', '') .replace('()', ''); return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage + '`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink; }; /***/ }), /* 412 */ /***/ (function(module, exports) { // Parse cloud does not supports setTimeout // We do not store a setTimeout reference in the client everytime // We only fallback to a fake setTimeout when not available // setTimeout cannot be override globally sadly module.exports = function exitPromise(fn, _setTimeout) { _setTimeout(fn, 0); }; /***/ }), /* 413 */ /***/ (function(module, exports, __webpack_require__) { var foreach = __webpack_require__(110); module.exports = function merge(destination/* , sources */) { var sources = Array.prototype.slice.call(arguments); foreach(sources, function(source) { for (var keyName in source) { if (source.hasOwnProperty(keyName)) { if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') { destination[keyName] = merge({}, destination[keyName], source[keyName]); } else if (source[keyName] !== undefined) { destination[keyName] = source[keyName]; } } } }); return destination; }; /***/ }), /* 414 */ /***/ (function(module, exports, __webpack_require__) { module.exports = function omit(obj, test) { var keys = __webpack_require__(426); var foreach = __webpack_require__(110); var filtered = {}; foreach(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; /***/ }), /* 415 */ /***/ (function(module, exports, __webpack_require__) { module.exports = createPlacesClient; var buildSearchMethod = __webpack_require__(348); function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = __webpack_require__(119); opts = opts && cloneDeep(opts) || {}; opts.hosts = opts.hosts || [ 'places-dsn.algolia.net', 'places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com' ]; // allow initPlaces() no arguments => community rate limited if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) { appID = ''; apiKey = ''; opts._allowEmptyCredentials = true; } var client = algoliasearch(appID, apiKey, opts); var index = client.initIndex('places'); index.search = buildSearchMethod('query', '/1/places/query'); return index; }; } /***/ }), /* 416 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var debug = __webpack_require__(216)('algoliasearch:src/hostIndexState.js'); var localStorageNamespace = 'algoliasearch-client-js'; var store; var moduleStore = { state: {}, set: function(key, data) { this.state[key] = data; return this.state[key]; }, get: function(key) { return this.state[key] || null; } }; var localStorageStore = { set: function(key, data) { moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure try { var namespace = JSON.parse(global.localStorage[localStorageNamespace]); namespace[key] = data; global.localStorage[localStorageNamespace] = JSON.stringify(namespace); return namespace[key]; } catch (e) { return localStorageFailure(key, e); } }, get: function(key) { try { return JSON.parse(global.localStorage[localStorageNamespace])[key] || null; } catch (e) { return localStorageFailure(key, e); } } }; function localStorageFailure(key, e) { debug('localStorage failed with', e); cleanup(); store = moduleStore; return store.get(key); } store = supportsLocalStorage() ? localStorageStore : moduleStore; module.exports = { get: getOrSet, set: getOrSet, supportsLocalStorage: supportsLocalStorage }; function getOrSet(key, data) { if (arguments.length === 1) { return store.get(key); } return store.set(key, data); } function supportsLocalStorage() { try { if ('localStorage' in global && global.localStorage !== null) { if (!global.localStorage[localStorageNamespace]) { // actual creation of the namespace global.localStorage.setItem(localStorageNamespace, JSON.stringify({})); } return true; } return false; } catch (_) { return false; } } // In case of any error on localStorage, we clean our own namespace, this should handle // quota errors when a lot of keys + data are used function cleanup() { try { global.localStorage.removeItem(localStorageNamespace); } catch (_) { // nothing to do } } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 417 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = '3.21.1'; /***/ }), /* 418 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }), /* 419 */ /***/ (function(module, exports, __webpack_require__) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug.debug = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __webpack_require__(425); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting args = exports.formatArgs.apply(self, args); var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }), /* 420 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global) {var require;/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 4.0.5 */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.ES6Promise = factory()); }(this, (function () { 'use strict'; function objectOrFunction(x) { return typeof x === 'function' || typeof x === 'object' && x !== null; } function isFunction(x) { return typeof x === 'function'; } var _isArray = undefined; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var r = require; var vertx = __webpack_require__(430); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { (function () { var callback = _arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); })(); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); _resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then) { asap(function (promise) { var sealed = false; var error = tryThen(then, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { _resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; _reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; _reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { _reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return _resolve(promise, value); }, function (reason) { return _reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$) { if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { handleOwnThenable(promise, maybeThenable); } else { if (then$$ === GET_THEN_ERROR) { _reject(promise, GET_THEN_ERROR.error); } else if (then$$ === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$)) { handleForeignThenable(promise, maybeThenable, then$$); } else { fulfill(promise, maybeThenable); } } } function _resolve(promise, value) { if (promise === value) { _reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function _reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { _reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { _resolve(promise, value); } else if (failed) { _reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { _reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { _resolve(promise, value); }, function rejectPromise(reason) { _reject(promise, reason); }); } catch (e) { _reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { _reject(this.promise, validationError()); } } function validationError() { return new Error('Array Methods must be provided an Array'); }; Enumerator.prototype._enumerate = function () { var length = this.length; var _input = this._input; for (var i = 0; this._state === PENDING && i < length; i++) { this._eachEntry(_input[i], i); } }; Enumerator.prototype._eachEntry = function (entry, i) { var c = this._instanceConstructor; var resolve$$ = c.resolve; if (resolve$$ === resolve) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$) { return resolve$$(entry); }), i); } } else { this._willSettleAt(resolve$$(entry), i); } }; Enumerator.prototype._settledAt = function (state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { _reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function (promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); _reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } Promise.all = all; Promise.race = race; Promise.resolve = resolve; Promise.reject = reject; Promise._setScheduler = setScheduler; Promise._setAsap = setAsap; Promise._asap = asap; Promise.prototype = { constructor: Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: then, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function _catch(onRejection) { return this.then(null, onRejection); } }; function polyfill() { var local = undefined; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise; } // Strange compat.. Promise.polyfill = polyfill; Promise.Promise = Promise; return Promise; }))); //# sourceMappingURL=es6-promise.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109), __webpack_require__(54))) /***/ }), /* 421 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 422 */ /***/ (function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeMax = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } module.exports = baseRange; /***/ }), /* 423 */ /***/ (function(module, exports, __webpack_require__) { var baseRange = __webpack_require__(422), isIterateeCall = __webpack_require__(217), toFinite = __webpack_require__(219); /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } module.exports = createRange; /***/ }), /* 424 */ /***/ (function(module, exports, __webpack_require__) { var createRange = __webpack_require__(423); /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); module.exports = range; /***/ }), /* 425 */ /***/ (function(module, exports) { /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } /***/ }), /* 426 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = __webpack_require__(427); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }), /* 427 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }), /* 428 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 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 stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; /***/ }), /* 429 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_429__; /***/ }), /* 430 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 431 */, /* 432 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Panel = exports.Toggle = exports.Stats = exports.SortBy = exports.SearchBox = exports.ScrollTo = exports.ClearAll = exports.RefinementList = exports.StarRating = exports.RangeSlider = exports.RangeInput = exports.PoweredBy = exports.Pagination = exports.MultiRange = exports.Menu = exports.InfiniteHits = exports.HitsPerPage = exports.Hits = exports.Snippet = exports.Highlight = exports.HierarchicalMenu = exports.CurrentRefinements = exports.Configure = exports.Index = exports.InstantSearch = undefined; var _Configure = __webpack_require__(354); Object.defineProperty(exports, 'Configure', { enumerable: true, get: function get() { return _interopRequireDefault(_Configure).default; } }); var _CurrentRefinements = __webpack_require__(355); Object.defineProperty(exports, 'CurrentRefinements', { enumerable: true, get: function get() { return _interopRequireDefault(_CurrentRefinements).default; } }); var _HierarchicalMenu = __webpack_require__(356); Object.defineProperty(exports, 'HierarchicalMenu', { enumerable: true, get: function get() { return _interopRequireDefault(_HierarchicalMenu).default; } }); var _Highlight = __webpack_require__(235); Object.defineProperty(exports, 'Highlight', { enumerable: true, get: function get() { return _interopRequireDefault(_Highlight).default; } }); var _Snippet = __webpack_require__(370); Object.defineProperty(exports, 'Snippet', { enumerable: true, get: function get() { return _interopRequireDefault(_Snippet).default; } }); var _Hits = __webpack_require__(357); Object.defineProperty(exports, 'Hits', { enumerable: true, get: function get() { return _interopRequireDefault(_Hits).default; } }); var _HitsPerPage = __webpack_require__(358); Object.defineProperty(exports, 'HitsPerPage', { enumerable: true, get: function get() { return _interopRequireDefault(_HitsPerPage).default; } }); var _InfiniteHits = __webpack_require__(359); Object.defineProperty(exports, 'InfiniteHits', { enumerable: true, get: function get() { return _interopRequireDefault(_InfiniteHits).default; } }); var _Menu = __webpack_require__(360); Object.defineProperty(exports, 'Menu', { enumerable: true, get: function get() { return _interopRequireDefault(_Menu).default; } }); var _MultiRange = __webpack_require__(361); Object.defineProperty(exports, 'MultiRange', { enumerable: true, get: function get() { return _interopRequireDefault(_MultiRange).default; } }); var _Pagination = __webpack_require__(362); Object.defineProperty(exports, 'Pagination', { enumerable: true, get: function get() { return _interopRequireDefault(_Pagination).default; } }); var _PoweredBy = __webpack_require__(364); Object.defineProperty(exports, 'PoweredBy', { enumerable: true, get: function get() { return _interopRequireDefault(_PoweredBy).default; } }); var _RangeInput = __webpack_require__(365); Object.defineProperty(exports, 'RangeInput', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeInput).default; } }); var _RangeSlider = __webpack_require__(366); Object.defineProperty(exports, 'RangeSlider', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeSlider).default; } }); var _StarRating = __webpack_require__(372); Object.defineProperty(exports, 'StarRating', { enumerable: true, get: function get() { return _interopRequireDefault(_StarRating).default; } }); var _RefinementList = __webpack_require__(367); Object.defineProperty(exports, 'RefinementList', { enumerable: true, get: function get() { return _interopRequireDefault(_RefinementList).default; } }); var _ClearAll = __webpack_require__(353); Object.defineProperty(exports, 'ClearAll', { enumerable: true, get: function get() { return _interopRequireDefault(_ClearAll).default; } }); var _ScrollTo = __webpack_require__(368); Object.defineProperty(exports, 'ScrollTo', { enumerable: true, get: function get() { return _interopRequireDefault(_ScrollTo).default; } }); var _SearchBox = __webpack_require__(369); Object.defineProperty(exports, 'SearchBox', { enumerable: true, get: function get() { return _interopRequireDefault(_SearchBox).default; } }); var _SortBy = __webpack_require__(371); Object.defineProperty(exports, 'SortBy', { enumerable: true, get: function get() { return _interopRequireDefault(_SortBy).default; } }); var _Stats = __webpack_require__(373); Object.defineProperty(exports, 'Stats', { enumerable: true, get: function get() { return _interopRequireDefault(_Stats).default; } }); var _Toggle = __webpack_require__(374); Object.defineProperty(exports, 'Toggle', { enumerable: true, get: function get() { return _interopRequireDefault(_Toggle).default; } }); var _Panel = __webpack_require__(363); Object.defineProperty(exports, 'Panel', { enumerable: true, get: function get() { return _interopRequireDefault(_Panel).default; } }); var _createInstantSearch = __webpack_require__(352); var _createInstantSearch2 = _interopRequireDefault(_createInstantSearch); var _createIndex = __webpack_require__(351); var _createIndex2 = _interopRequireDefault(_createIndex); var _lite = __webpack_require__(375); var _lite2 = _interopRequireDefault(_lite); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InstantSearch = (0, _createInstantSearch2.default)(_lite2.default, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); exports.InstantSearch = InstantSearch; var Index = (0, _createIndex2.default)({ Root: 'div', props: { className: 'ais-MultiIndex__root' } }); exports.Index = Index; /***/ }) /******/ ]); }); //# sourceMappingURL=Dom.js.map
src/components/Footer/Footer.js
djfm/ps-translations-interface-mockup
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import s from './Footer.scss'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; @withStyles(s) class Footer extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© PrestaShop</span> <span className={s.spacer}>·</span> <Link className={s.link} to="/">Home</Link> </div> </div> ); } } export default Footer;
app/javascript/flavours/glitch/features/ui/components/boost_modal.js
im-in-space/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Button from 'flavours/glitch/components/button'; import StatusContent from 'flavours/glitch/components/status_content'; import Avatar from 'flavours/glitch/components/avatar'; import RelativeTimestamp from 'flavours/glitch/components/relative_timestamp'; import DisplayName from 'flavours/glitch/components/display_name'; import AttachmentList from 'flavours/glitch/components/attachment_list'; import Icon from 'flavours/glitch/components/icon'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PrivacyDropdown from 'flavours/glitch/features/compose/components/privacy_dropdown'; import classNames from 'classnames'; import { changeBoostPrivacy } from 'flavours/glitch/actions/boosts'; import VisibilityIcon from 'flavours/glitch/components/status_visibility_icon'; const messages = defineMessages({ cancel_reblog: { id: 'status.cancel_reblog_private', defaultMessage: 'Unboost' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, }); const mapStateToProps = state => { return { privacy: state.getIn(['boosts', 'new', 'privacy']), }; }; const mapDispatchToProps = dispatch => { return { onChangeBoostPrivacy(value) { dispatch(changeBoostPrivacy(value)); }, }; }; export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class BoostModal extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, onReblog: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, missingMediaDescription: PropTypes.bool, intl: PropTypes.object.isRequired, }; componentDidMount() { this.button.focus(); } handleReblog = () => { this.props.onReblog(this.props.status, this.props.privacy); this.props.onClose(); } handleAccountClick = (e) => { if (e.button === 0) { e.preventDefault(); this.props.onClose(); let state = {...this.context.router.history.location.state}; state.mastodonBackSteps = (state.mastodonBackSteps || 0) + 1; this.context.router.history.push(`/@${this.props.status.getIn(['account', 'acct'])}`, state); } } _findContainer = () => { return document.getElementsByClassName('modal-root__container')[0]; }; setRef = (c) => { this.button = c; } render () { const { status, missingMediaDescription, privacy, intl } = this.props; const buttonText = status.get('reblogged') ? messages.cancel_reblog : messages.reblog; return ( <div className='modal-root__modal boost-modal'> <div className='boost-modal__container'> <div className={classNames('status', `status-${status.get('visibility')}`, 'light')}> <div className='boost-modal__status-header'> <div className='boost-modal__status-time'> <a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener noreferrer'> <VisibilityIcon visibility={status.get('visibility')} /> <RelativeTimestamp timestamp={status.get('created_at')} /></a> </div> <a onClick={this.handleAccountClick} href={status.getIn(['account', 'url'])} className='status__display-name'> <div className='status__avatar'> <Avatar account={status.get('account')} size={48} /> </div> <DisplayName account={status.get('account')} /> </a> </div> <StatusContent status={status} /> {status.get('media_attachments').size > 0 && ( <AttachmentList compact media={status.get('media_attachments')} /> )} </div> </div> <div className='boost-modal__action-bar'> <div> { missingMediaDescription ? <FormattedMessage id='boost_modal.missing_description' defaultMessage='This toot contains some media without description' /> : <FormattedMessage id='boost_modal.combo' defaultMessage='You can press {combo} to skip this next time' values={{ combo: <span>Shift + <Icon id='retweet' /></span> }} /> } </div> {status.get('visibility') !== 'private' && !status.get('reblogged') && ( <PrivacyDropdown noDirect value={privacy} container={this._findContainer} onChange={this.props.onChangeBoostPrivacy} /> )} <Button text={intl.formatMessage(buttonText)} onClick={this.handleReblog} ref={this.setRef} /> </div> </div> ); } }
web/src/routes/Contacts/components/ContactForm.js
darioml/farley-files
import React from 'react' export class ContactAdd extends React.Component { constructor(props) { super(props); if (this.props.contact) { this.state = Object.assign({ id: undefined, first_name: '', last_name: '', birthday: undefined, phone_number: '', notes: '' }, this.props.contact); } else { this.state = { id: undefined, first_name: '', last_name: '', birthday: undefined, phone_number: '', notes: '' }; } this.handleInputChange = this.handleInputChange.bind(this); this.save = this.save.bind(this); } save() { const url = (this.state.id) ? `http://localhost:8000/contacts/${this.state.id}/` : 'http://localhost:8000/contacts/'; fetch(url, { method: (this.state.id) ? 'PUT' : 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa('darioml:latios1994') }, body: JSON.stringify(this.state) }).then(() => { this.setState({ first_name: '', last_name: '', birthday: '', phone_number: '', notes: '' }) if (this.props.onSave) { this.props.onSave(); } }) } handleInputChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : (target.value === '') ? undefined : target.value; const name = target.name; this.setState({ [name]: value }); } render() { return ( <div> <div className="form-group"> <label className="col-sm-2 control-label">First name</label> <div className="col-sm-10"> <input name="first_name" className="form-control" type="text" onChange={this.handleInputChange} value={this.state.first_name}/> </div> </div> <div className="form-group"> <label className="col-sm-2 control-label">Last name</label> <div className="col-sm-10"> <input name="last_name" className="form-control" type="text" onChange={this.handleInputChange} value={this.state.last_name}/> </div> </div> <div className="form-group"> <label className="col-sm-2 control-label">Birthday</label> <div className="col-sm-10"> <input name="birthday" className="form-control" type="date" onChange={this.handleInputChange} value={this.state.birthday}/> </div> </div> <div className="form-group"> <label className="col-sm-2 control-label">Phone Number</label> <div className="col-sm-10"> <input name="phone_number" className="form-control" type="text" onChange={this.handleInputChange} value={this.state.phone_number}/> </div> </div> <div className="form-group"> <label className="col-sm-2 control-label">Notes</label> <div className="col-sm-10"> <textarea name="notes" className="form-control" type="text" onChange={this.handleInputChange} value={this.state.notes}></textarea> </div> </div> <div className="form-group"> <div className="col-sm-12 text-right"> <button className="btn btn-default" onClick={this.save}>Save</button> </div> </div> </div> ); } } ContactAdd.propTypes = { contact: React.PropTypes.object, onSave: React.PropTypes.func }
src/client/components/NewPollPage.js
dgrcode/FCC-Voting-App
'use strict'; import React from 'react'; import NewChoiceInput from './NewChoiceInput'; import { communicateNewPoll } from '../actions/pollActions'; export default class NewPollPage extends React.Component { constructor (props) { super(props); this.state = { name: '', choices: [''] }; } handleTitleChange = (e) => { this.setState({ name: e.target.value }); } updateInput = (value, index) => { this.setState({ choices: this.state.choices.map((v, i) => i === index ? value : v) }); } addNewChoice = () => { this.setState({ choices: [...this.state.choices, ''] }); } deleteChoice = (idx) => { this.setState({ choices: this.state.choices.filter((v, i) => i !== idx) }); } submitPoll = () => { const newPoll = { name: this.state.name, choices: this.state.choices.map(val => ({ choice: val, votes: 0 })), // dateCreated is set by the server owner: this.props.user._id }; const newPollData = communicateNewPoll(newPoll); this.props.ws.send(JSON.stringify(newPollData)); this.props.history.push('/'); } render () { return ( <div className="app-root"> <h1>New Poll</h1> <label> Title: <input type="text" value={this.state.name} onChange={this.handleTitleChange} /> </label> <h4>Options:</h4> <button className="btn" onClick={this.addNewChoice}>New choice</button> <br/> { this.state.choices.map((choice, idx) => ( <NewChoiceInput key={idx} idx={idx} val={this.state.choices[idx]} updateInput={this.updateInput} deleteChoice={this.deleteChoice} /> )) } <br/> <button className="btn btn-info" onClick={this.submitPoll}>Submit</button> </div> ); } }
react-flux-mui/js/material-ui/src/svg-icons/content/low-priority.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentLowPriority = (props) => ( <SvgIcon {...props}> <path d="M14 5h8v2h-8zm0 5.5h8v2h-8zm0 5.5h8v2h-8zM2 11.5C2 15.08 4.92 18 8.5 18H9v2l3-3-3-3v2h-.5C6.02 16 4 13.98 4 11.5S6.02 7 8.5 7H12V5H8.5C4.92 5 2 7.92 2 11.5z"/> </SvgIcon> ); ContentLowPriority = pure(ContentLowPriority); ContentLowPriority.displayName = 'ContentLowPriority'; ContentLowPriority.muiName = 'SvgIcon'; export default ContentLowPriority;
src/icons/Wifi.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class Wifi extends React.Component { render() { if(this.props.bare) { return <g> <g> <path d="M256.1,96L256.1,96c-79.9,0-155.7,29.9-213.9,84.1L32,189.6l9.9,9.8l32.3,32l9.3,9.2l9.6-8.8 c44.5-40.9,102.3-63.5,162.8-63.5c60.5,0,118.4,22.6,162.8,63.5l9.6,8.8l9.3-9.2l32.3-32l9.9-9.8l-10.2-9.5 C411.6,125.9,335.7,96,256.1,96z"></path> <path d="M397.4,256.4c-38.8-35.1-88.9-54.4-141.1-54.4h-0.1h-0.3h-8.5l-0.1,0.2c-49.2,2-96,21.1-132.6,54.2l-10.5,9.5l10.1,10 l32.7,32.4l9.1,9l9.6-8.4c25.3-22.2,57.4-34.5,90.3-34.5c33.1,0,65.2,12.3,90.5,34.5l9.6,8.4l9.1-9l32.7-32.4l10.1-10L397.4,256.4z "></path> <path d="M256.2,416l9.6-9.5l52.8-52.2l10.6-10.5l-11.6-9.5c-15.4-11.4-32.4-20-61.5-20c-29,0-44.9,9.4-61.5,20l-11.5,9.5l10.6,10.5 l52.8,52.2L256.2,416z"></path> </g> </g>; } return <IconBase> <g> <path d="M256.1,96L256.1,96c-79.9,0-155.7,29.9-213.9,84.1L32,189.6l9.9,9.8l32.3,32l9.3,9.2l9.6-8.8 c44.5-40.9,102.3-63.5,162.8-63.5c60.5,0,118.4,22.6,162.8,63.5l9.6,8.8l9.3-9.2l32.3-32l9.9-9.8l-10.2-9.5 C411.6,125.9,335.7,96,256.1,96z"></path> <path d="M397.4,256.4c-38.8-35.1-88.9-54.4-141.1-54.4h-0.1h-0.3h-8.5l-0.1,0.2c-49.2,2-96,21.1-132.6,54.2l-10.5,9.5l10.1,10 l32.7,32.4l9.1,9l9.6-8.4c25.3-22.2,57.4-34.5,90.3-34.5c33.1,0,65.2,12.3,90.5,34.5l9.6,8.4l9.1-9l32.7-32.4l10.1-10L397.4,256.4z "></path> <path d="M256.2,416l9.6-9.5l52.8-52.2l10.6-10.5l-11.6-9.5c-15.4-11.4-32.4-20-61.5-20c-29,0-44.9,9.4-61.5,20l-11.5,9.5l10.6,10.5 l52.8,52.2L256.2,416z"></path> </g> </IconBase>; } };Wifi.defaultProps = {bare: false}
src/js/pages/Featured.js
fjferrer/todoReactFlux
import React from 'react'; export default class Featured extends React.Component { render() { return ( <h1>Featured</h1> ); } }
src/entypo/SelectArrows.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--SelectArrows'; let EntypoSelectArrows = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M10,1L5,8h10L10,1z M10,19l5-7H5L10,19z"/> </EntypoIcon> ); export default EntypoSelectArrows;
components/Layout.js
akiran/nextjs-demo
import React from 'react' import Header from './Header' import Head from 'next/head' export default function Layout(props) { return ( <div> <Head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> </Head> <div className='container'> <Header /> {props.children} </div> </div> ) }
ui/js/components/ShellTerminal/ShellTerminal.js
NitorCreations/willow-ui
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { connect } from 'react-redux'; import Terminal from 'term.js'; import ReduxWebSocketService from 'websocket/ReduxWebSocketService'; import createUuid from 'util/uuid'; const TerminalStates = { CONNECTING: 0, OPEN: 1, CLOSED: 3, ERROR: 4 }; const StatusToClass = { 0: 'connecting', 1: 'open', 3: 'closed', 4: 'error' }; const StatusToDescription = { 0: 'Connecting to server...', 1: 'Connection open', 3: 'Connection closed', 4: 'Connection ERROR' }; const HEARTBEAT_IN_MILLIS = 5000; function resolveWebsocketUri(user, host, nCols, nRows) { var location = window.location; var ws_protocol = resolveProtocol(location); var ws_host = resolveHost(location); var ws_context = resolveContext(location); return `${ws_protocol}//${ws_host}${ws_context}/rawterminal/?user=${user}&host=${host}&cols=${nCols}&rows=${nRows}`; function resolveProtocol(location) { return location.protocol === 'https:' ? 'wss:' : 'ws:'; } function resolveHost(location) { return location.host; } function resolveContext(location) { return location.pathname.replace(/ui.*$/, '').substring(1); } } class ShellTerminal extends Component { constructor(props) { super(props); var rowsAndCols = { rows: this.props.rows, cols: this.props.maxCols }; var webSocketId = 'host_' + this.props.host; var webSocketUri = resolveWebsocketUri(this.props.user, this.props.host, rowsAndCols.cols, rowsAndCols.rows); var term = new Terminal({ cols: rowsAndCols.cols, rows: rowsAndCols.rows, screenKeys: true, cursorBlink: true, useStyles: true }); term.on('title', title => { document.title = title; }); var socket = new ReduxWebSocketService(webSocketUri, webSocketId, this.props.dispatch) .withRawData() .onOpened(() => { this.setState({ connectionStatus: TerminalStates.OPEN }); }) .onMsg(data => { term.write(data.msg); }) .onError(() => { this.setState({ connectionStatus: TerminalStates.ERROR }); }) .onClose(() => { this.setState({ connectionStatus: TerminalStates.CLOSED }); term.destroy(); }); term.on('data', data => { socket.send(data); }); window.setInterval(function() { socket.send(JSON.stringify({ ping: 1 })); }, HEARTBEAT_IN_MILLIS); this.state = { uuid: createUuid(), socket: socket, terminal: term, connectionStatus: TerminalStates.CONNECTING, webSocketId: webSocketId, ...rowsAndCols }; } render() { return ( <div className="shell-terminal"> <header className={StatusToClass[this.state.connectionStatus]}> <div>ID: {this.state.webSocketId}</div> <div>{StatusToDescription[this.state.connectionStatus]}</div> </header> <div className="terminal-content"> <div className="ruler">1</div> <div id={this.state.uuid} className="terminal-container"></div> </div> </div> ); } componentDidMount() { window.addEventListener('resize', this.updateDimensions.bind(this)); this.state.terminal.open(document.getElementById(this.state.uuid)); this.state.socket.open(); } componentWillUnmount() { window.removeEventListener('resize', this.updateDimensions.bind(this)); this.state.socket.close(); } updateDimensions() { var rowsAndCols = this.calculateOptimalRowsAndCols(); this.state.terminal.resize(rowsAndCols.cols, rowsAndCols.rows); this.state.socket.send(JSON.stringify(rowsAndCols)); this.setState({ ...rowsAndCols }); } calculateOptimalRowsAndCols() { var rootElement = ReactDOM.findDOMNode(this); var terminalElement = rootElement.getElementsByClassName('terminal-container')[0]; var rulerElement = rootElement.getElementsByClassName('ruler')[0]; var characterWidth = rulerElement.clientWidth; var width = terminalElement.clientWidth; var nCols = Math.min(parseInt(width / characterWidth), this.props.maxCols); return {cols: nCols, rows: this.props.rows }; } } export default connect( (state, componentProperties) => { return { componentProperties, }; }) (ShellTerminal);
src/FormGroup.js
insionng/react-bootstrap
import React from 'react'; import classNames from 'classnames'; class FormGroup extends React.Component { render() { let classes = { 'form-group': !this.props.standalone, 'form-group-lg': !this.props.standalone && this.props.bsSize === 'large', 'form-group-sm': !this.props.standalone && this.props.bsSize === 'small', 'has-feedback': this.props.hasFeedback, 'has-success': this.props.bsStyle === 'success', 'has-warning': this.props.bsStyle === 'warning', 'has-error': this.props.bsStyle === 'error' }; return ( <div className={classNames(classes, this.props.groupClassName)}> {this.props.children} </div> ); } } FormGroup.defaultProps = { hasFeedback: false, standalone: false }; FormGroup.propTypes = { standalone: React.PropTypes.bool, hasFeedback: React.PropTypes.bool, bsSize (props) { if (props.standalone && props.bsSize !== undefined) { return new Error('bsSize will not be used when `standalone` is set.'); } return React.PropTypes.oneOf(['small', 'medium', 'large']) .apply(null, arguments); }, bsStyle: React.PropTypes.oneOf(['success', 'warning', 'error']), groupClassName: React.PropTypes.string }; export default FormGroup;
src/components/player-bar.js
marcusdarmstrong/mockdraftable-web
// @flow import React from 'react'; import { connect } from 'react-redux'; import type { Dispatch } from 'redux'; import { updateModalType } from '../redux/actions'; import type { Action } from '../redux/actions'; import type { Position } from '../types/domain'; import type { PlayerPageState } from '../types/state'; type Props = { selectedPlayerName: string, selectedPosition: Position, openPositionSelector: () => void, }; const PlayerBar = ({ selectedPlayerName, selectedPosition, openPositionSelector }: Props) => ( <div className="row fixed-top p-2 pl-3 pr-3 mb-2 playerbar"> <div className="col-12 d-flex ml-auto mr-auto col-lg-10"> <div className="mb-0 mt-1 h3 align-bottom playerbar-name"> {selectedPlayerName} </div> <div className="ml-auto"> <button type="button" className="btn" onClick={() => openPositionSelector()} style={{ backgroundColor: selectedPosition.color, color: '#fff', }} > {selectedPosition.abbreviation} </button> </div> </div> </div> ); export default connect( (state: PlayerPageState) => ({ selectedPlayerName: state.players[state.selectedPlayerId].name, selectedPosition: state.positions[state.selectedPositionId], }), (dispatch: Dispatch<Action>) => ({ openPositionSelector: () => dispatch(updateModalType('PositionSelector')), }), )(PlayerBar);
classic/src/scenes/wbfa/generated/FASCookie.pro.js
wavebox/waveboxapp
import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faCookie } from '@fortawesome/pro-solid-svg-icons/faCookie' export default class FASCookie extends React.Component { render () { return (<FontAwesomeIcon {...this.props} icon={faCookie} />) } }
scripts/apps/translations/directives/TranslationReactDropdown.js
mugurrus/superdesk-client-core
/* eslint-disable react/no-multi-comp */ import React from 'react'; import PropTypes from 'prop-types'; /** * @ngdoc directive * @module superdesk.apps.translations * @name TranslationReactDropdown * * @requires React * @requires item * @requires className * @requires TranslationService * @requires noLanguagesLabel * * @param {Object} [langugages] collection of languages * * @description Creates dropdown react element with list of available languages */ TranslationReactDropdown.$inject = ['item', 'className', 'TranslationService', 'noLanguagesLabel']; export function TranslationReactDropdown(item, className, TranslationService, noLanguagesLabel) { var languages = TranslationService.get() || {_items: []}; /* * Creates specific language button in list * @return {React} Language button */ class TranslateBtn extends React.Component { constructor(props) { super(props); this.markTranslate = this.markTranslate.bind(this); } markTranslate(event) { event.stopPropagation(); TranslationService.set(this.props.item, this.props.language); } render() { var item = this.props.item; var language = this.props.language; var isCurrentLang = item.language === language.language; if (!language.destination) { return false; } return React.createElement( 'button', { disabled: isCurrentLang, onClick: this.markTranslate, }, language.label ); } } TranslateBtn.propTypes = { item: PropTypes.object, language: PropTypes.object, }; /* * Creates list element for specific language * @return {React} Single list element */ var createTranslateItem = function(language) { return React.createElement( 'li', {key: 'language-' + language._id}, React.createElement(TranslateBtn, {item: item, language: language}) ); }; /* * If there are no languages, print none-langugage message * @return {React} List element */ var noLanguage = function() { return React.createElement( 'li', {}, React.createElement( 'button', {disabled: true}, noLanguagesLabel) ); }; /* * Creates list with languages * @return {React} List element */ return React.createElement( 'ul', {className: className}, languages._items.length ? languages._items.map(createTranslateItem) : React.createElement(noLanguage) ); }
assets/js/src/components/_myApps.js
stechDevSP/stechDev
import React from 'react'; import ReactDOM from 'react-dom'; import { StMultiList } from '../webparts/st-multilist.jsx'; import { StCheckUp } from '../webparts/st-checkup.jsx'; import { StProjectGantter } from '../webparts/st-projectgantter.jsx'; import { StPdfMaker } from '../webparts/st-pdfmaker.jsx'; import { StNewsAggregate } from '../webparts/st-newsaggregate.jsx'; export class MyApps extends React.Component { getInitialState() { return { showMultiList: false, showCheckUp: false, showProjectGantter: false, showPdfMaker: false, showNews: false, apps: [], appsRemain: [] }; } constructor(props) { super(props); var self = this; this.handleClick = this.handleClick.bind(this); this.goShopClick = this.goShopClick.bind(this); var appsArray = []; var allApps = []; var arrayStorage = sessionStorage.getItem("AppsSelected"); if (arrayStorage) { appsArray = JSON.parse(arrayStorage); //test } else { //get my apps } var allApps = JSON.parse(sessionStorage.getItem("AllApps")); var appsArray2 = []; if (appsArray.length > 0 && allApps.length > 0) { $.each(allApps, function(iAll, eAll) { var find = false; $.each(appsArray, function(iMy, eMy) { if (eMy.Name === eAll.Name) { find = true; } }); if (!find) { appsArray2.push(eAll); } }); } else { appsArray2 = allApps; } sessionStorage.setItem("AppsShop", JSON.stringify(appsArray2)); self.state = { apps: appsArray, appsRemain: appsArray2, showCheckUp: false, showPdfMaker: false, showMultiList: false, showProjectGantter: false, showNews: false }; } goBackClick() { $(".goBack-selectApps").hide(); $(".view-my-apps, .profile-drop, .select-currency").show(); this.setState({ showCheckUp: false }); this.setState({ showPdfMaker: false }); this.setState({ showMultiList: false }); this.setState({ showProjectGantter: false }); this.setState({ showNews: false }); } goShopClick() { $(".my-select-apps-zone").slideUp(); $(".login-zone").find(".select-apps-zone").slideDown(); $(".start-apps, .cardShop").hide(); $(".suggested-apps, .select-currency").show(); var appsRemain = JSON.parse(sessionStorage.getItem("AppsShop")); $.each(appsRemain, function(index, value) { $(".cardId_" + value.Id).show(); }); $(".cart-container").html("No apps selected"); $(".totale-cart-value, .totale-sub-value, .orderNumber").html(0); $(".packageVersions").hide(); $(".cart-icon").show(); $(".version-select-zone").show(); var versionSelected = sessionStorage.getItem("PackageSelected"); $("." + versionSelected).show(); $("." + versionSelected).find(".package").addClass("packageSel"); $(".priceEuroPackageSel").html($("." + versionSelected).find(".priceEuroVersion").html()); $(".priceSterlinPackageSel").html($("." + versionSelected).find(".priceSterlinVersion").html()); $(".priceDollarPackageSel").html($("." + versionSelected).find(".priceDollarVersion").html()); $(".subEuroPackageSel").html($("." + versionSelected).find(".valueEuroPrice").html()); $(".subSterlinPackageSel").html($("." + versionSelected).find(".valueSterlinPrice").html()); $(".subDollarPackageSel").html($("." + versionSelected).find(".valueDollarPrice").html()); $(".packageSelected").html($("." + versionSelected).find(".nameVersion").html()); sessionStorage.setItem("packageSelected", $("." + versionSelected).find(".nameVersion").html()); $(".packageSelDetails").html("Your business plan: " + $("." + versionSelected).find(".nameVersion").html()); } handleClick(nameApp) { var myApps = true; if (nameApp == "ST-CheckUp Intranet") { this.setState({ showCheckUp: true }); this.setState({ showPdfMaker: false }); this.setState({ showMultiList: false }); this.setState({ showProjectGantter: false }); this.setState({ showNews: false }); myApps = false; } else { this.setState({ showCheckUp: false }); } if (nameApp == "ST-PdfMaker") { this.setState({ showPdfMaker: true }); this.setState({ showCheckUp: false }); this.setState({ showMultiList: false }); this.setState({ showProjectGantter: false }); this.setState({ showNews: false }); myApps = false; } else { this.setState({ showPdfMaker: false }); } if (nameApp == "ST-MultiList") { this.setState({ showMultiList: true }); this.setState({ showPdfMaker: false }); this.setState({ showCheckUp: false }); this.setState({ showProjectGantter: false }); this.setState({ showNews: false }); myApps = false; } else { this.setState({ showHelpDesk: false }); } if (nameApp == "ST-Project Gantter") { this.setState({ showProjectGantter: true }); this.setState({ showPdfMaker: false }); this.setState({ showMultiList: false }); this.setState({ showCheckUp: false }); this.setState({ showNews: false }); myApps = false; } else { this.setState({ showProjectGantter: false }); } if (nameApp == "ST-News Aggregate") { this.setState({ showNews: true }); this.setState({ showProjectGantter: false }); this.setState({ showPdfMaker: false }); this.setState({ showMultiList: false }); this.setState({ showCheckUp: false }); myApps = false; } else { this.setState({ showNews: false }); } if (myApps) { $(".goBack-selectApps").hide(); $(".view-my-apps, .profile-drop, .select-currency").show(); } else { $(".view-my-apps, .profile-drop, .select-currency").hide(); $(".goBack-selectApps").show(); } } render() { var self = this; var items; if (this.state.apps && this.state.apps.length > 0) { items = this.state.apps.map(function(item, i) { var app = ( <div className="col-md-3 col-sm-6 col-xs-12 card myCardRedirect" key={i} data-myApp={item.Name} onClick={() => self.handleClick(item.Name)} > <div className="flip-container"> <div className={"titleCard cardTitle_" + i}>{item.Name}</div> <div className="myCard"> <div className={"front " + item.Name}></div> </div> </div> </div> ); return app; }); } else { items = "No apps found"; } var otherItems; if (this.state.appsRemain && this.state.appsRemain.length > 0) { otherItems = this.state.appsRemain.map(function(item, i) { var app2 = ( <div className="col-md-3 col-sm-6 col-xs-12 card otherShopCard" key={i}> <div className="flip-container"> <div className={"titleCard cardTitle_" + i}>{item.Name}</div> <div className="myCard"> <div className={"front " + item.Name}></div> </div> </div> </div> ); return app2; }); } else { otherItems = "No apps suggested"; } return ( <div> <div className="goBack-selectApps" onClick={() => this.goBackClick()}> <img className="icon icons8-Long-Arrow-Left" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAA30lEQVRIS+2U/Q2CMBTE7ybQDWQDdQNHcARH0wl0Ax3BEXADneCZI21SPgOlEGPoX9Dy+utdj0fMNDgTBwso2unfsM7MMgBXySC5j5aj+rZiM9sBuANYO9Ao9Y3FZnZwSgrIJCAzO3q7QrUk0ymq2tVg6xvAM5h/BM+a17rGi2ReOqh/6QGJycKF5KmwPgDpBJuY3bpqvOUhSNK3c4D0zwi2SgirW6fN3T3pgttgn55hyFvDUAlFDZY03l2wSUCBjTefxMlADqYWdAaQkVTvix6j2soQ6gIa4lbp2/+z7gvHwkYbyI5xugAAAABJRU5ErkJggg==" width="26" height="26" /> <div className="backLabel">Back to apps</div> </div> <div className="view-my-apps"> <div> <div className="col-md-12 title-select-apps">My apps</div> <div className="col-md-12 myApps">{items}</div> <hr /> <div className="col-md-12 title-select-apps title-sugg">Other suggested apps</div> <div className="col-md-12 other-apps">{otherItems}</div> </div> <div className="col-md-12 btn-suggested"> <div className="col-md-9">&nbsp;</div> <div className="col-md-3 col-sm- 12 col-xs-12"> <div className="btn-welcome go-shop" onClick={() => this.goShopClick()}>Go to shop</div> </div> </div> </div> <div id="view" className="div-React"> {this.state.showCheckUp ? <StCheckUp /> : <div className="STCheckUp"></div>} {this.state.showPdfMaker ? <StPdfMaker /> : <div className="StPdfMaker"></div>} {this.state.showMultiList ? <StMultiList /> : <div className="StMultiList"></div>} {this.state.showProjectGantter ? <StProjectGantter /> : <div className="StProjectGantter"></div>} {this.state.showNews ? <StNewsAggregate /> : <div className="StNewsAggregate"></div>} </div> </div> ); } }
src/containers/Login/index.js
dadongfang/react_redux_webpack_es6_qiniu
import React from 'react' import { connect } from 'react-redux' import { Form, Input, Button, Icon } from 'antd' import { login } from 'src/actions/account' import global from 'src/js/global' import './index.less' const FormItem = Form.Item class Login extends React.Component { constructor(props, context) { super(props, context) this.handleSubmit = this.handleSubmit.bind(this) } componentWillMount() { if (window.LS.get('token')) { const { history } = this.props history.replace('/') } } handleSubmit(e) { e.preventDefault() if (this.props.logining) return this.props.form.validateFields({ force: true }, (err, values) => { if (!err) { const { dispatch, history } = this.props dispatch(login(values)).then(result => { if (result.code === global.successCode) { window.LS.set('token', result.userDTO.token) window.LS.set('userInfo', JSON.stringify(result.userDTO)) window.LS.set('roleList', JSON.stringify(result.roleMenuList)) // history.replace('/user') window.location.href = '/user' } }) } }) } render() { const { form, logining, error } = this.props const { getFieldDecorator } = form return ( <div className='login'> <div className='logo'> <img alt="" src={global.logo} /> <span>后台管理系统</span> </div> <Form onSubmit={this.handleSubmit}> <FormItem> {getFieldDecorator('userName', { rules: [{ required: true, message: '请输入用户名' }], })( <Input prefix={<Icon type="user" className='prefixIcon' />} placeholder="请输入用户名" /> )} </FormItem> <FormItem> {getFieldDecorator('password', { rules: [{ required: true, message: '请输入密码' }], })( <Input prefix={<Icon type="lock" className='prefixIcon' />} type="password" placeholder="请输入密码" /> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit" loading={logining}> 登录{logining} </Button> </FormItem> { // error && ( // <div className='error'> // {/* <Icon type="info-circle" /> */} // {error} // </div> // ) } </Form> </div> ) } } function mapStateToProps({ account }) { return { logining: account.logining, user: account.user, error: account.error } } Login = Form.create()(Login) export default connect(mapStateToProps)(Login)
internals/templates/homePage/homePage.js
pashakbit/react-gallery
/* * HomePage * * This is the first thing users see of our App, at the '/' 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 HomePage extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/containers/Chats/ChatMessages.js
petorious/dmprov-app
import React, { Component } from 'react'; import { connect } from 'react-redux'; import ReactDOM from 'react-dom'; import firebase from 'firebase'; import PropTypes from 'prop-types'; import muiThemeable from 'material-ui/styles/muiThemeable'; import { injectIntl, intlShape } from 'react-intl'; import { setSimpleValue } from '../../store/simpleValues/actions'; import FontIcon from 'material-ui/FontIcon'; import IconButton from 'material-ui/IconButton'; import TextField from 'material-ui/TextField'; import { withRouter } from 'react-router-dom'; import { withFirebase } from 'firekit'; import Chip from 'material-ui/Chip'; import { ListItem } from 'material-ui/List'; import Divider from 'material-ui/Divider'; import ReactList from 'react-list'; import { getGeolocation } from '../../utils/googleMaps'; import googleMapsLogo from '../../utils/resources/google-maps-logo.png' import Scrollbar from '../../components/Scrollbar/Scrollbar'; import Image from 'material-ui-image' const pageStep=20; class ChatMessages extends Component { constructor(props) { super(props); this.name = null; this.listEnd=null; } scrollToBottom = () => { const node = ReactDOM.findDOMNode(this.listEnd); if(node){ node.scrollIntoView({ behavior: "smooth" }); } } componentWillReceiveProps(nextProps) { const {uid: currentUid, destroyPath, path, auth} =this.props; const {uid: nextUid, auth: nextAuth} =nextProps; if(currentUid!==nextUid || auth.uid!==nextAuth.uid){ destroyPath(path); this.initMessages(nextProps); } } componentDidUpdate(prevProps, prevState) { this.scrollToBottom(); } componentDidMount() { this.initMessages(this.props); this.scrollToBottom(); } initMessages = (props) => { const {watchList, firebaseApp, path}=props; let messagesRef=firebaseApp.database().ref(path).orderByKey().limitToLast(pageStep); watchList(messagesRef); watchList('predefined_chat_messages'); } handleLoadMore = () => { const { watchList, unwatchList, firebaseApp, setSimpleValue, simpleValues, path } =this.props; const currentAmount=simpleValues['chat_messages_limit']?simpleValues['chat_messages_limit']:pageStep; const nextAmount=currentAmount+pageStep; unwatchList(path); setSimpleValue('chat_messages_limit', nextAmount); let messagesRef=firebaseApp.database().ref(path).orderByKey().limitToLast(nextAmount); watchList(messagesRef); } handleKeyDown = (event, onSucces) => { if(event.keyCode===13){ onSucces(); } } handleAddMessage = (type, message) => { const { auth, firebaseApp, path } = this.props const newMessage = { created: firebase.database.ServerValue.TIMESTAMP, authorName: auth.displayName, authorUid: auth.uid, authorPhotoUrl: auth.photoURL, } if (type === 'image') { newMessage.image = message } else if (type === 'location') { newMessage.location = message } else { if(message.startsWith('http') || message.startsWith('https')) { newMessage.link = message } else { newMessage.message = message } } this.name.input.value = '' this.name.state.hasValue = false if (message.length > 0) { firebaseApp.database().ref(path).push(newMessage) } } renderList(messages) { const { auth, intl, muiTheme} = this.props; let currentDate=''; let currentAuthor=''; if(messages===undefined){ return <div></div> } return messages.map((row, i) => { const values=row.val // const key=row.key if (values.created == null) { return undefined } const stringDate=new Date(values.created).toISOString().slice(0,10) let dataChanged=false let authorChanged=false const backgroundColor=values.authorUid===auth.uid?muiTheme.palette.primary2Color:muiTheme.palette.canvasColor const color=muiTheme.chip.textColor const type = values.message?'text':(values.link?"link":(values.location?'location':(values.image?'image':undefined))) if(currentDate!==stringDate){ currentDate=stringDate; dataChanged=true; } if(currentAuthor!==values.authorUid){ currentAuthor=values.authorUid; authorChanged=true; } return <div key={i} style={{width: '100%'}}> <div > {dataChanged && <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', paddingTop: 10, paddingBottom:10 }}> <div> <Chip backgroundColor={muiTheme.palette.primary3Color}> {`${values.created?intl.formatRelative(new Date(values.created), {units: 'day'}):undefined}`} </Chip> </div> </div> } <div style={{display: 'flex', width: '100%', justifyContent: values.authorUid===auth.uid?'flex-end':'flex-start'}}> <div style={{ ...muiTheme.chip, margin: 1, marginTop: authorChanged===true?8:1, boxShadow: muiTheme.chip.shadow, borderRadius: authorChanged===true?(values.authorUid===auth.uid?'8px 0px 8px 8px':'0px 8px 8px 8px'):'8px 8px 8px 8px' , backgroundColor:backgroundColor, color:color, fontFamily: muiTheme.fontFamily}}> <div style={{ display: 'flex', margin: 5, flexOrientation: 'row', justifyContent: 'space-between', width:'fit-content'}}> <div style={{ maxWidth: 500, width: 'fit-content', fontSize: 16, paddingLeft: 8, margin: 'auto', whiteSpace: 'pre-wrap', overflowWrap: 'break-word', fontFamily: muiTheme.fontFamily}}> { type === 'location' && <div style={{padding: 7}}> <div style={{padding: 3}}> {intl.formatMessage({id:'my_location'})} </div> <div style={{textAlign: 'center', width: '100%', height: '100%'}}> <a target="_blank" href={values.location} style={{width: '100%', height: '100%'}}> <img src={googleMapsLogo} alt='' height={50} width={50}/> </a> </div> </div> } { type === 'link' && <a target="_blank" href={values.link}>{values.link}</a> } { type === 'image' && values.image != null && <Image style={{width: 'auto', height: 'auto'}} imageStyle={{maxWidth: '100%', padding: 7}} onLoad={this.scrollToBottom} src={values.image} color={backgroundColor} /> } { type === 'text' && values.message } </div> <div style={{ fontSize: 9, color:values.authorUid!==auth.uid?muiTheme.palette.primary2Color:muiTheme.palette.canvasColor, marginLeft: 8, //marginRight: 3, //marginLeft: 5, alignSelf: 'flex-end', fontFamily: muiTheme.fontFamily }}> {`${values.created?intl.formatTime(new Date(values.created)):undefined}`} </div> </div> </div> </div> </div> </div> }); } renderItem = (i, k) => { const { predefinedMessages, muiTheme, setSimpleValue } = this.props; const key = predefinedMessages[i].key; const message = predefinedMessages[i].val.message; return <div key={key}> <ListItem rightIconButton={ <IconButton onClick={() => { setSimpleValue('chatMessageMenuOpen', false) this.handleAddMessage("text", message) }}> <FontIcon className="material-icons" color={muiTheme.palette.text1Color}>send</FontIcon> </IconButton> } onClick={()=>{ setSimpleValue('chatMessageMenuOpen', false); this.name.input.value = message; this.name.state.hasValue = true; this.name.state.isFocused = true; this.name.focus(); }} key={key} id={key} primaryText={message} /> <Divider/> </div>; } uploadSelectedFile = (file, handleAddMessage) => { const { firebaseApp, intl } = this.props if(file == null) { return } if(((file.size/1024)/1024).toFixed(4) > 20) { //file larger than 10mb alert(intl.formatMessage({id: 'max_file_size'})) return } let reader = new FileReader() let key=firebaseApp.database().ref(`/user_chat_messages/`).push().key reader.onload = function(fileData) { let uploadTask = firebaseApp.storage().ref(`/user_chats/${key}`).putString(fileData.target.result, 'data_url') uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => { }, error => { console.log(error) }, ()=>{ handleAddMessage('image', uploadTask.snapshot.downloadURL) }) } reader.readAsDataURL(file) } render(){ const { messages, muiTheme, intl, setSimpleValue, chatMessageMenuOpen, predefinedMessages, uid, firebaseApp, auth } = this.props return ( <div style={{ display: 'flex', flexDirection: 'column', height: '100%', backgroundColor: muiTheme.chip.backgroundColor, }} onClick={() => { firebaseApp.database().ref(`user_chats/${auth.uid}/${uid}/unread`).remove(); }}> <Scrollbar style={{ backgroundColor: muiTheme.palette.convasColor, width: '100%', }}> <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}> <div style={{maxWidth: 600, margin: 8, width: '100%'}} > <div style={{display: 'flex', justifyContent:'center'}}> <Chip onClick={this.handleLoadMore} backgroundColor={muiTheme.palette.primary3Color}> {intl.formatMessage({id:'load_more_label'})} </Chip> </div> {this.renderList(messages)} </div> </div> <div style={{ float:"left", clear: "both" }} ref={(el) => { this.listEnd = el; }}> </div> </Scrollbar> <div style={{ display:'block', alignItems: 'row', justifyContent: 'center', height: chatMessageMenuOpen?300:56, backgroundColor: muiTheme.palette.canvasColor }}> <div style={{display:'flex', alignItems: 'center', justifyContent: 'center'}}> <IconButton onClick={() => { if(chatMessageMenuOpen === true) { setSimpleValue('chatMessageMenuOpen', false); } else { setSimpleValue('chatMessageMenuOpen', true); } }}> <FontIcon className="material-icons" color={muiTheme.palette.borderColor}>{chatMessageMenuOpen===true?'keyboard_arrow_down':'keyboard_arrow_up'}</FontIcon> </IconButton> <div style={{ backgroundColor: muiTheme.chip.backgroundColor, flexGrow: 1, borderRadius: 8, paddingLeft: 8, paddingRight: 8, }}> <div style={{position: 'relative', display: 'inline-block', width: '100%'}}> <TextField id="message" style={{height:42, width: 'calc(100% - 72px)', lineHeight: undefined}} underlineShow={false} fullWidth={true} hintText={intl.formatMessage({id:'write_message_hint'})} onKeyDown={(event)=>{this.handleKeyDown(event, () => this.handleAddMessage("text", this.name.getValue()))}} ref={(field) => { this.name = field}} type="Text" /> <div style={{position: 'absolute', right: 25, top: -3, width: 20, height: 0}}> <IconButton onClick={() => getGeolocation((pos) => { if(!pos) { return; } else if(!pos.coords) { return; } const lat = pos.coords.latitude; const long = pos.coords.longitude; this.handleAddMessage("location", `https://www.google.com/maps/place/${lat}+${long}/@${lat},${long}`); }, (error) => console.log(error)) }> <FontIcon className="material-icons" color={muiTheme.palette.primary1Color}>my_location</FontIcon> </IconButton> </div> <input style={{display: 'none'}} type='file' onChange={(e) => this.uploadSelectedFile(e.target.files[0], this.handleAddMessage)} ref={(input) => {this.fileInput = input}} /> <div style={{position: 'absolute', right: 55, top: -3, width: 20, height: 0}}> <IconButton containerElement='label' onClick={() => this.fileInput.click()}> <FontIcon className="material-icons" color={muiTheme.palette.primary1Color}>photo</FontIcon> </IconButton> </div> </div> </div> <IconButton disabled={messages===undefined} onClick={() => this.handleAddMessage("text", this.name.getValue())}> <FontIcon className="material-icons" color={muiTheme.palette.primary1Color}>send</FontIcon> </IconButton> </div> { chatMessageMenuOpen && <Scrollbar style={{height: 200, backgroundColor: muiTheme.chip.backgroundColor}}> <div style={{padding: 10, paddingRight: 0,}}> <ReactList itemRenderer={this.renderItem} length={predefinedMessages?predefinedMessages.length:0} type='simple' /> </div> </Scrollbar> } </div> </div> ); } } ChatMessages.propTypes = { intl: intlShape.isRequired, muiTheme: PropTypes.object.isRequired, auth: PropTypes.object.isRequired, }; const mapStateToProps = (state, ownProps) => { const { lists, auth, browser, simpleValues } = state; const { uid } = ownProps; const path=`user_chat_messages/${auth.uid}/${uid}` const chatMessageMenuOpen = simpleValues['chatMessageMenuOpen']===true const imageDialogOpen = simpleValues.chatOpenImageDialog; return { imageDialogOpen, simpleValues, path, uid, chatMessageMenuOpen, messages: lists[path], predefinedMessages: lists['predefined_chat_messages'], auth, browser }; }; export default connect( mapStateToProps, { setSimpleValue } )(injectIntl(muiThemeable()(withRouter(withFirebase(ChatMessages)))));
webpack/scenes/RedHatRepositories/index.js
adamruzicka/katello
/* eslint-disable import/no-extraneous-dependencies */ /* eslint import/no-unresolved: [2, { ignore: [foremanReact/*] }] */ /* eslint-disable import/no-unresolved */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Grid, Row, Col } from 'react-bootstrap'; import { Button } from 'patternfly-react'; import { translate as __ } from 'foremanReact/common/I18n'; import { LoadingState } from '../../move_to_pf/LoadingState'; import { createEnabledRepoParams, loadEnabledRepos } from '../../redux/actions/RedHatRepositories/enabled'; import { loadRepositorySets, updateRecommendedRepositorySets } from '../../redux/actions/RedHatRepositories/sets'; import SearchBar from './components/SearchBar'; import RecommendedRepositorySetsToggler from './components/RecommendedRepositorySetsToggler'; import { getSetsComponent, getEnabledComponent } from './helpers'; import api from '../../services/api'; class RedHatRepositoriesPage extends Component { componentDidMount() { this.loadData(); } loadData() { this.props.loadEnabledRepos(); this.props.loadRepositorySets({ search: { filters: ['rpm'] } }); } render() { const { enabledRepositories, repositorySets } = this.props; const { repoParams } = createEnabledRepoParams(enabledRepositories); return ( <Grid id="redhatRepositoriesPage" bsClass="container-fluid"> <h1>{__('Red Hat Repositories')}</h1> <Row className="toolbar-pf"> <Col sm={12}> <SearchBar /> </Col> </Row> <Row className="row-eq-height"> <Col sm={6} className="available-repositories-container"> <div className="available-repositories-header"> <h2>{__('Available Repositories')}</h2> <RecommendedRepositorySetsToggler enabled={repositorySets.recommended} onChange={value => this.props.updateRecommendedRepositorySets(value)} className="recommended-repositories-toggler" /> </div> <LoadingState loading={repositorySets.loading} loadingText={__('Loading')}> {getSetsComponent( repositorySets, (pagination) => { this.props.loadRepositorySets({ ...pagination, search: repositorySets.search, }); }, )} </LoadingState> </Col> <Col sm={6} className="enabled-repositories-container"> <h2> {__('Enabled Repositories')} <Button className="pull-right" onClick={() => { api.open('/repositories.csv', repoParams); }} > {__('Export as CSV')} </Button> </h2> <LoadingState loading={enabledRepositories.loading} loadingText={__('Loading')}> {getEnabledComponent( enabledRepositories, (pagination) => { this.props.loadEnabledRepos({ ...pagination, search: enabledRepositories.search, }); }, )} </LoadingState> </Col> </Row> </Grid> ); } } RedHatRepositoriesPage.propTypes = { loadEnabledRepos: PropTypes.func.isRequired, loadRepositorySets: PropTypes.func.isRequired, updateRecommendedRepositorySets: PropTypes.func.isRequired, enabledRepositories: PropTypes.shape({ loading: PropTypes.bool, search: PropTypes.shape({}), }).isRequired, repositorySets: PropTypes.shape({ recommended: PropTypes.array, loading: PropTypes.bool, search: PropTypes.shape({}), }).isRequired, }; const mapStateToProps = ({ katello: { redHatRepositories: { enabled, sets }, }, }) => ({ enabledRepositories: enabled, repositorySets: sets, }); export default connect(mapStateToProps, { loadEnabledRepos, loadRepositorySets, updateRecommendedRepositorySets, })(RedHatRepositoriesPage);
app/javascript/mastodon/main.js
cobodo/mastodon
import * as registerPushNotifications from './actions/push_notifications'; import { setupBrowserNotifications } from './actions/notifications'; import { default as Mastodon, store } from './containers/mastodon'; import React from 'react'; import ReactDOM from 'react-dom'; import ready from './ready'; const perf = require('./performance'); function main() { perf.start('main()'); if (window.history && history.replaceState) { const { pathname, search, hash } = window.location; const path = pathname + search + hash; if (!(/^\/web($|\/)/).test(path)) { history.replaceState(null, document.title, `/web${path}`); } } ready(() => { const mountNode = document.getElementById('mastodon'); const props = JSON.parse(mountNode.getAttribute('data-props')); ReactDOM.render(<Mastodon {...props} />, mountNode); store.dispatch(setupBrowserNotifications()); if (process.env.NODE_ENV === 'production') { // avoid offline in dev mode because it's harder to debug require('offline-plugin/runtime').install(); store.dispatch(registerPushNotifications.register()); } perf.stop('main()'); }); } export default main;
app/constants/Global.js
jaminzzhang/MZMovie
import React from 'react'; import { Dimensions, Platform } from 'react-native'; let {height, width} = Dimensions.get('window'); // 获取屏幕宽度 global.SCREEN_WIDTH = width; // 获取屏幕高度 global.SCREEN_HEIGHT = height; // 系统是iOS global.iOS = (Platform.OS === 'ios'); // 系统是安卓 global.Android = (Platform.OS === 'android');
01_webstack/03Wk04/1_conFusion_http/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
allenmodroid/webstack
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/components/header/Navigation.js
samihda/pizza
import React from 'react'; import Sequence from './Sequence'; import MainMenu from './MainMenu'; const Navigation = (props) => { const Empty = () => null; return ( <nav> <div className="pure-menu pure-menu-horizontal"> {props.step === 0 ? <MainMenu {...props} /> : <Empty />} {props.step > 0 ? <Sequence {...props} /> : <Empty />} </div> </nav> ); }; Navigation.propTypes = { step: React.PropTypes.number.isRequired }; export default Navigation;
app/components/badges/run-statistics/component.js
DenQ/electron-react-lex
import React, { Component } from 'react'; import Badge from 'material-ui/Badge'; export default class RunVariable extends Component { render() { const { statisticsAlbum } = this.props; return ( <span> <Badge badgeContent={statisticsAlbum.learned} primary={true} secondary={false} badgeStyle={{top: 5, right: 1}} title="Learned words" /> <Badge badgeContent={statisticsAlbum.length} secondary={true} badgeStyle={{top: 5, right: 1}} title="Size album" /> </span> ); } }
src/containers/NotFound/NotFound.js
RomanovRoman/react-redux-universal-hot-example
import React from 'react'; export default function NotFound() { return ( <div className="container"> <h1>Doh! 404!</h1> <p>These are <em>not</em> the droids you are looking for!</p> </div> ); }
src/Components/svg/BikeIcon.js
fcgomes92/pousadacaminhodosventos
import React, { Component } from 'react'; export default class BikeIcon extends Component { render() { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" {...this.props}> <path d="M13.24 61.67c1.682-.642 3.41-.945 5.11-.95l-1.897 14.21c-.1.757.247 1.502.888 1.915.53.34 1.19.4 1.76.18.12-.045.24-.104.35-.175l12.12-7.663c.13.278.25.557.36.844 2.85 7.46-.9 15.84-8.36 18.69-7.45 2.85-15.83-.91-18.68-8.36-2.84-7.45.91-15.83 8.36-18.68zm9.003-.424c2.785.773 5.322 2.37 7.22 4.624l-8.56 5.415zm2.515-18.82l11.81 14.1c-.995 1.556-1.34 3.498-.83 5.375l-2.926 1.85c-2.564-3.22-6.126-5.46-10.044-6.42zm16.46 15.11c1.432-.545 3.04.175 3.586 1.605.546 1.44-.174 3.05-1.604 3.59-1.43.55-3.047-.17-3.593-1.6-.545-1.43.182-3.04 1.612-3.58zm39.042-5.023c.565.53 1.363.658 2.038.4.273-.105.523-.27.733-.496.75-.793.7-2.036-.09-2.775l-10.48-9.777c1.17-.954 2.5-1.74 3.99-2.31 7.46-2.843 15.84.908 18.68 8.364 2.85 7.45-.91 15.83-8.36 18.68-7.46 2.84-15.83-.91-18.68-8.37-1.78-4.67-.98-9.69 1.69-13.5zm-55.3 39.87c9.475-3.617 14.252-14.274 10.636-23.753-.205-.536-.435-1.054-.685-1.558l2.94-1.855c1.8 1.55 4.38 2.088 6.76 1.18 3.45-1.316 5.19-5.2 3.87-8.654-.2-.538-.47-1.03-.79-1.48L63 36.42l3.886 3.63c-3.652 4.886-4.81 11.48-2.477 17.59 3.61 9.48 14.27 14.248 23.75 10.63 9.47-3.615 14.25-14.27 10.63-23.75-3.62-9.48-14.28-14.245-23.75-10.63-2.07.787-3.91 1.91-5.49 3.28L57.39 25.826l7.45-16.648c.325-.726.183-1.575-.367-2.15-.54-.58-1.38-.77-2.128-.486L50.8 10.947c-1.012.387-1.52 1.52-1.132 2.534.39 1.02 1.52 1.53 2.536 1.14l7.115-2.71-5.76 12.86-9.89 3.77c-1.02.39-1.53 1.53-1.14 2.54.38 1.01 1.53 1.52 2.54 1.13l9.5-3.62 5.52 5.16-15.55 20.13c-1.48-.55-3.15-.6-4.74 0-.1.04-.17.08-.27.12L27.04 39.09l6.87-2.62c1.013-.38 1.52-1.52 1.133-2.53-.39-1.02-1.52-1.525-2.54-1.14l-8.136 3.1-2.44-2.913 2.39-.91c1.01-.385 1.52-1.52 1.134-2.535-.383-1.02-1.523-1.52-2.53-1.14L13 32.19c-1.014.386-1.522 1.52-1.135 2.534.386 1.01 1.52 1.52 2.535 1.13l3.65-1.396 3.265 3.894-2.46 18.45c-2.336-.065-4.72.316-7.034 1.2-9.46 3.618-14.23 14.27-10.61 23.75C4.83 91.23 15.48 96 24.96 92.38" /> <path d="M21.73 83.915c1.435-.548 2.722-1.45 3.723-2.604.71-.81.623-2.06-.197-2.77-.82-.71-2.06-.62-2.77.2-.587.68-1.314 1.19-2.158 1.51-2.464.94-5.23-.02-6.574-2.28-.554-.93-1.76-1.24-2.69-.68-.932.56-1.24 1.76-.686 2.69 2.324 3.91 7.097 5.57 11.35 3.95M10.792 75.8c.367.067.728.027 1.052-.096.62-.237 1.105-.78 1.234-1.482.02-.106.042-.212.067-.315.255-1.055-.394-2.116-1.448-2.37-1.054-.255-2.114.393-2.37 1.448-.042.175-.08.352-.112.528-.197 1.068.51 2.09 1.577 2.286M87.42 58.22c.236-.09.463-.232.662-.42 3.276-3.154 3.797-8.178 1.253-11.952-.863-1.272-2.037-2.32-3.388-3.032-.958-.505-2.15-.133-2.65.825-.506.97-.135 2.15.824 2.66.8.42 1.46 1.01 1.96 1.76 1.48 2.19 1.18 5.1-.72 6.92-.78.75-.8 2-.05 2.78.56.59 1.41.75 2.12.48m-5.9 2.19c.18.01.36 0 .54-.01.21 0 .42-.05.61-.12.77-.29 1.31-1.05 1.26-1.92-.04-1.08-.96-1.92-2.05-1.87-.1.01-.21.01-.32.01-1.09-.01-1.98.86-1.98 1.946-.01 1.08.86 1.97 1.95 1.98M39.08 34.5l1.1-.42c1.01-.386 1.52-1.52 1.13-2.534-.39-1.017-1.52-1.525-2.54-1.14l-1.095.42c-1.014.388-1.52 1.52-1.133 2.535.383 1.02 1.52 1.53 2.53 1.14m7.52-17.75l.61-.23c1.013-.38 1.52-1.52 1.132-2.53-.385-1.01-1.518-1.52-2.53-1.13l-.61.23c-1.016.39-1.53 1.52-1.14 2.54.384 1.01 1.525 1.52 2.54 1.13" /> </svg> ) } }
newclient/scripts/components/config/disclosure-requirements/configuring-panel/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program 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, either version 3 of the License, or (at your option) any later version. This program 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 styles from './style'; import React from 'react'; import ConfigActions from '../../../../actions/config-actions'; import CheckBox from '../../check-box'; import Panel from '../../panel'; export default class ConfiguringPanel extends React.Component { constructor() { super(); this.returnToProjectTypes = this.returnToProjectTypes.bind(this); } returnToProjectTypes() { ConfigActions.configureProjectType(undefined); } render() { const projectRoles = this.props.roles.map((role,index) => { const tmpRole = JSON.parse(JSON.stringify(role)); tmpRole.index = index; return tmpRole; }) .filter(role => { return role.projectTypeCd == this.props.projectType.typeCd; // eslint-disable-line eqeqeq }) .map((role, index) => { return ( <span key={index} className={styles.checkbox}> <CheckBox path={`config.projectRoles[${role.index}].reqDisclosure`} checked={role.reqDisclosure === 1} label={role.description} /> </span> ); }); const projectStatuses = this.props.statuses.map((status,index) => { const tmpStatus = JSON.parse(JSON.stringify(status)); tmpStatus.index = index; return tmpStatus; }) .filter(status => { return status.projectTypeCd == this.props.projectType.typeCd; // eslint-disable-line eqeqeq }) .map((status, index) => { return ( <span key={index} className={styles.checkbox}> <CheckBox path={`config.projectStatuses[${status.index}].reqDisclosure`} checked={status.reqDisclosure === 1} label={status.description} key={index} /> </span> ); }); return ( <div> <i className={`fa fa-chevron-left ${styles.icon}`} /> <button className={styles.link} onClick={this.returnToProjectTypes}>BACK TO PROJECT TYPES</button> <div className={styles.title}> {this.props.projectType.description} </div> <Panel title="Project Roles"> {projectRoles} </Panel> <Panel title="Project Statuses"> {projectStatuses} </Panel> </div> ); } }
src/containers/About/About.js
rmwdeveloper/portfolio
import React, { Component } from 'react'; export default class About extends Component { render() { return ( <div> Hey whats up </div> ); } }
node_modules/react-native/Libraries/Components/TextInput/TextInput.js
senolakkas/react-native-minesweeper
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule TextInput * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const DocumentSelectionState = require('DocumentSelectionState'); const EventEmitter = require('EventEmitter'); const NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); const Platform = require('Platform'); const PropTypes = require('react/lib/ReactPropTypes'); const React = require('React'); const ReactNative = require('react/lib/ReactNative'); const ReactChildren = require('react/lib/ReactChildren'); const StyleSheet = require('StyleSheet'); const Text = require('Text'); const TextInputState = require('TextInputState'); const TimerMixin = require('react-timer-mixin'); const TouchableWithoutFeedback = require('TouchableWithoutFeedback'); const UIManager = require('UIManager'); const View = require('View'); const warning = require('fbjs/lib/warning'); const emptyFunction = require('fbjs/lib/emptyFunction'); const invariant = require('fbjs/lib/invariant'); const requireNativeComponent = require('requireNativeComponent'); const onlyMultiline = { onTextInput: true, children: true, }; if (Platform.OS === 'android') { var AndroidTextInput = requireNativeComponent('AndroidTextInput', null); } else if (Platform.OS === 'ios') { var RCTTextView = requireNativeComponent('RCTTextView', null); var RCTTextField = requireNativeComponent('RCTTextField', null); } type Event = Object; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; /** * A foundational component for inputting text into the app via a * keyboard. Props provide configurability for several features, such as * auto-correction, auto-capitalization, placeholder text, and different keyboard * types, such as a numeric keypad. * * The simplest use case is to plop down a `TextInput` and subscribe to the * `onChangeText` events to read the user input. There are also other events, * such as `onSubmitEditing` and `onFocus` that can be subscribed to. A simple * example: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * constructor(props) { * super(props); * this.state = { text: 'Useless Placeholder' }; * } * * render() { * return ( * <TextInput * style={{height: 40, borderColor: 'gray', borderWidth: 1}} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput); * ``` * * Note that some props are only available with `multiline={true/false}`. * Additionally, border styles that apply to only one side of the element * (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if * `multiline=false`. To achieve the same effect, you can wrap your `TextInput` * in a `View`: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * render() { * return ( * <TextInput * {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below * editable = {true} * maxLength = {40} * /> * ); * } * } * * class UselessTextInputMultiline extends Component { * constructor(props) { * super(props); * this.state = { * text: 'Useless Multiline Placeholder', * }; * } * * // If you type something in the text box that is a color, the background will change to that * // color. * render() { * return ( * <View style={{ * backgroundColor: this.state.text, * borderBottomColor: '#000000', * borderBottomWidth: 1 }} * > * <UselessTextInput * multiline = {true} * numberOfLines = {4} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * </View> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent( * 'AwesomeProject', * () => UselessTextInputMultiline * ); * ``` * * `TextInput` has by default a border at the bottom of its view. This border * has its padding set by the background image provided by the system, and it * cannot be changed. Solutions to avoid this is to either not set height * explicitly, case in which the system will take care of displaying the border * in the correct position, or to not display the border by setting * `underlineColorAndroid` to transparent. * */ const TextInput = React.createClass({ statics: { /* TODO(brentvatne) docs are needed for this */ State: TextInputState, }, propTypes: { ...View.propTypes, /** * Can tell `TextInput` to automatically capitalize certain characters. * * - `characters`: all characters. * - `words`: first letter of each word. * - `sentences`: first letter of each sentence (*default*). * - `none`: don't auto capitalize anything. */ autoCapitalize: PropTypes.oneOf([ 'none', 'sentences', 'words', 'characters', ]), /** * If `false`, disables auto-correct. The default value is `true`. */ autoCorrect: PropTypes.bool, /** * If `true`, focuses the input on `componentDidMount`. * The default value is `false`. */ autoFocus: PropTypes.bool, /** * If `false`, text is not editable. The default value is `true`. */ editable: PropTypes.bool, /** * Determines which keyboard to open, e.g.`numeric`. * * The following values work across platforms: * * - `default` * - `numeric` * - `email-address` * - `phone-pad` */ keyboardType: PropTypes.oneOf([ // Cross-platform 'default', 'email-address', 'numeric', 'phone-pad', // iOS-only 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', ]), /** * Determines the color of the keyboard. * @platform ios */ keyboardAppearance: PropTypes.oneOf([ 'default', 'light', 'dark', ]), /** * Determines how the return key should look. On Android you can also use * `returnKeyLabel`. * * *Cross platform* * * The following values work across platforms: * * - `done` * - `go` * - `next` * - `search` * - `send` * * *Android Only* * * The following values work on Android only: * * - `none` * - `previous` * * *iOS Only* * * The following values work on iOS only: * * - `default` * - `emergency-call` * - `google` * - `join` * - `route` * - `yahoo` */ returnKeyType: PropTypes.oneOf([ // Cross-platform 'done', 'go', 'next', 'search', 'send', // Android-only 'none', 'previous', // iOS-only 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo', ]), /** * Sets the return key to the label. Use it instead of `returnKeyType`. * @platform android */ returnKeyLabel: PropTypes.string, /** * Limits the maximum number of characters that can be entered. Use this * instead of implementing the logic in JS to avoid flicker. */ maxLength: PropTypes.number, /** * Sets the number of lines for a `TextInput`. Use it with multiline set to * `true` to be able to fill the lines. * @platform android */ numberOfLines: PropTypes.number, /** * If `true`, the keyboard disables the return key when there is no text and * automatically enables it when there is text. The default value is `false`. * @platform ios */ enablesReturnKeyAutomatically: PropTypes.bool, /** * If `true`, the text input can be multiple lines. * The default value is `false`. */ multiline: PropTypes.bool, /** * Callback that is called when the text input is blurred. */ onBlur: PropTypes.func, /** * Callback that is called when the text input is focused. */ onFocus: PropTypes.func, /** * Callback that is called when the text input's text changes. */ onChange: PropTypes.func, /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText: PropTypes.func, /** * Callback that is called when the text input's content size changes. * This will be called with * `{ nativeEvent: { contentSize: { width, height } } }`. * * Only called for multiline text inputs. */ onContentSizeChange: PropTypes.func, /** * Callback that is called when text input ends. */ onEndEditing: PropTypes.func, /** * Callback that is called when the text input selection is changed. */ onSelectionChange: PropTypes.func, /** * Callback that is called when the text input's submit button is pressed. * Invalid if `multiline={true}` is specified. */ onSubmitEditing: PropTypes.func, /** * Callback that is called when a key is pressed. * Pressed key value is passed as an argument to the callback handler. * Fires before `onChange` callbacks. * @platform ios */ onKeyPress: PropTypes.func, /** * Invoked on mount and layout changes with `{x, y, width, height}`. */ onLayout: PropTypes.func, /** * The string that will be rendered before text input has been entered. */ placeholder: PropTypes.string, /** * The text color of the placeholder string. */ placeholderTextColor: ColorPropType, /** * If `true`, the text input obscures the text entered so that sensitive text * like passwords stay secure. The default value is `false`. */ secureTextEntry: PropTypes.bool, /** * The highlight (and cursor on iOS) color of the text input. */ selectionColor: ColorPropType, /** * An instance of `DocumentSelectionState`, this is some state that is responsible for * maintaining selection information for a document. * * Some functionality that can be performed with this instance is: * * - `blur()` * - `focus()` * - `update()` * * > You can reference `DocumentSelectionState` in * > [`vendor/document/selection/DocumentSelectionState.js`](https://github.com/facebook/react-native/blob/master/Libraries/vendor/document/selection/DocumentSelectionState.js) * * @platform ios */ selectionState: PropTypes.instanceOf(DocumentSelectionState), /** * The value to show for the text input. `TextInput` is a controlled * component, which means the native value will be forced to match this * value prop if provided. For most uses, this works great, but in some * cases this may cause flickering - one common cause is preventing edits * by keeping value the same. In addition to simply setting the same value, * either set `editable={false}`, or set/update `maxLength` to prevent * unwanted edits without flicker. */ value: PropTypes.string, /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you do not want to deal with listening * to events and updating the value prop to keep the controlled state in sync. */ defaultValue: PropTypes.string, /** * When the clear button should appear on the right side of the text view. * @platform ios */ clearButtonMode: PropTypes.oneOf([ 'never', 'while-editing', 'unless-editing', 'always', ]), /** * If `true`, clears the text field automatically when editing begins. * @platform ios */ clearTextOnFocus: PropTypes.bool, /** * If `true`, all text will automatically be selected on focus. */ selectTextOnFocus: PropTypes.bool, /** * If `true`, the text field will blur when submitted. * The default value is true for single-line fields and false for * multiline fields. Note that for multiline fields, setting `blurOnSubmit` * to `true` means that pressing return will blur the field and trigger the * `onSubmitEditing` event instead of inserting a newline into the field. */ blurOnSubmit: PropTypes.bool, /** * [Styles](/react-native/docs/style.html) */ style: Text.propTypes.style, /** * The color of the `TextInput` underline. * @platform android */ underlineColorAndroid: ColorPropType, /** * If defined, the provided image resource will be rendered on the left. * @platform android */ inlineImageLeft: PropTypes.string, /** * Padding between the inline image, if any, and the text input itself. * @platform android */ inlineImagePadding: PropTypes.number, /** * Determines the types of data converted to clickable URLs in the text input. * Only valid if `multiline={true}` and `editable={false}`. * By default no data types are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), }, /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ mixins: [NativeMethodsMixin, TimerMixin], viewConfig: ((Platform.OS === 'ios' && RCTTextField ? RCTTextField.viewConfig : (Platform.OS === 'android' && AndroidTextInput ? AndroidTextInput.viewConfig : {})) : Object), /** * Returns `true` if the input is currently focused; `false` otherwise. */ isFocused: function(): boolean { return TextInputState.currentlyFocusedField() === ReactNative.findNodeHandle(this.refs.input); }, contextTypes: { onFocusRequested: React.PropTypes.func, focusEmitter: React.PropTypes.instanceOf(EventEmitter), }, _focusSubscription: (undefined: ?Function), _lastNativeText: (undefined: ?string), componentDidMount: function() { this._lastNativeText = this.props.value; if (!this.context.focusEmitter) { if (this.props.autoFocus) { this.requestAnimationFrame(this.focus); } return; } this._focusSubscription = this.context.focusEmitter.addListener( 'focus', (el) => { if (this === el) { this.requestAnimationFrame(this.focus); } else if (this.isFocused()) { this.blur(); } } ); if (this.props.autoFocus) { this.context.onFocusRequested(this); } }, componentWillUnmount: function() { this._focusSubscription && this._focusSubscription.remove(); if (this.isFocused()) { this.blur(); } }, getChildContext: function(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: React.PropTypes.bool }, /** * Removes all text from the `TextInput`. */ clear: function() { this.setNativeProps({text: ''}); }, render: function() { if (Platform.OS === 'ios') { return this._renderIOS(); } else if (Platform.OS === 'android') { return this._renderAndroid(); } }, _getText: function(): ?string { return typeof this.props.value === 'string' ? this.props.value : this.props.defaultValue; }, _renderIOS: function() { var textContainer; var onSelectionChange; if (this.props.selectionState || this.props.onSelectionChange) { onSelectionChange = (event: Event) => { if (this.props.selectionState) { var selection = event.nativeEvent.selection; this.props.selectionState.update(selection.start, selection.end); } this.props.onSelectionChange && this.props.onSelectionChange(event); }; } var props = Object.assign({}, this.props); props.style = [styles.input, this.props.style]; if (!props.multiline) { if (__DEV__) { for (var propKey in onlyMultiline) { if (props[propKey]) { const error = new Error( 'TextInput prop `' + propKey + '` is only supported with multiline.' ); warning(false, '%s', error.stack); } } } textContainer = <RCTTextField ref="input" {...props} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={onSelectionChange} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} />; } else { var children = props.children; var childCount = 0; ReactChildren.forEach(children, () => ++childCount); invariant( !(props.value && childCount), 'Cannot specify both value and children.' ); if (childCount >= 1) { children = <Text style={props.style}>{children}</Text>; } if (props.inputView) { children = [children, props.inputView]; } textContainer = <RCTTextView ref="input" {...props} children={children} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onContentSizeChange={this.props.onContentSizeChange} onSelectionChange={onSelectionChange} onTextInput={this._onTextInput} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} dataDetectorTypes={this.props.dataDetectorTypes} />; } return ( <TouchableWithoutFeedback onLayout={props.onLayout} onPress={this._onPress} rejectResponderTermination={true} accessible={props.accessible} accessibilityLabel={props.accessibilityLabel} accessibilityTraits={props.accessibilityTraits} testID={props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _renderAndroid: function() { var onSelectionChange; if (this.props.selectionState || this.props.onSelectionChange) { onSelectionChange = (event: Event) => { if (this.props.selectionState) { var selection = event.nativeEvent.selection; this.props.selectionState.update(selection.start, selection.end); } this.props.onSelectionChange && this.props.onSelectionChange(event); }; } const props = Object.assign({}, this.props); props.style = [this.props.style]; props.autoCapitalize = UIManager.AndroidTextInput.Constants.AutoCapitalizationType[this.props.autoCapitalize]; var children = this.props.children; var childCount = 0; ReactChildren.forEach(children, () => ++childCount); invariant( !(this.props.value && childCount), 'Cannot specify both value and children.' ); if (childCount > 1) { children = <Text>{children}</Text>; } const textContainer = <AndroidTextInput ref="input" {...props} mostRecentEventCount={0} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={onSelectionChange} onTextInput={this._onTextInput} text={this._getText()} children={children} />; return ( <TouchableWithoutFeedback onLayout={this.props.onLayout} onPress={this._onPress} shouldBlockResponder={this.isFocused} accessible={this.props.accessible} accessibilityLabel={this.props.accessibilityLabel} accessibilityComponentType={this.props.accessibilityComponentType} testID={this.props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _onFocus: function(event: Event) { if (this.props.onFocus) { this.props.onFocus(event); } if (this.props.selectionState) { this.props.selectionState.focus(); } }, _onPress: function(event: Event) { if (this.props.editable || this.props.editable === undefined) { this.focus(); } }, _onChange: function(event: Event) { // Make sure to fire the mostRecentEventCount first so it is already set on // native when the text value is set. this.refs.input.setNativeProps({ mostRecentEventCount: event.nativeEvent.eventCount, }); var text = event.nativeEvent.text; this.props.onChange && this.props.onChange(event); this.props.onChangeText && this.props.onChangeText(text); if (!this.refs.input) { // calling `this.props.onChange` or `this.props.onChangeText` // may clean up the input itself. Exits here. return; } this._lastNativeText = text; this.forceUpdate(); }, componentDidUpdate: function () { // This is necessary in case native updates the text and JS decides // that the update should be ignored and we should stick with the value // that we have in JS. if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') { this.refs.input.setNativeProps({ text: this.props.value, }); } }, _onBlur: function(event: Event) { this.blur(); if (this.props.onBlur) { this.props.onBlur(event); } if (this.props.selectionState) { this.props.selectionState.blur(); } }, _onTextInput: function(event: Event) { this.props.onTextInput && this.props.onTextInput(event); }, }); var styles = StyleSheet.create({ input: { alignSelf: 'stretch', }, }); module.exports = TextInput;
main.js
lifeiscontent/OpenPoGoUI
import 'babel-polyfill'; import 'whatwg-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import FastClick from 'fastclick'; import { Provider } from 'react-redux'; import store from './core/store'; import router from './core/router'; import history from './core/history'; let routes = require('./routes.json'); // Loaded with utils/routes-loader.js const container = document.getElementById('container'); function renderComponent(component) { ReactDOM.render(<Provider store={store}>{component}</Provider>, container); } // Find and render a web page matching the current URL path, // if such page is not found then render an error page (see routes.json, core/router.js) function render(location) { router.resolve(routes, location) .then(renderComponent) .catch(error => router.resolve(routes, { ...location, error }).then(renderComponent)); } // Handle client-side navigation by using HTML5 History API // For more information visit https://github.com/ReactJSTraining/history/tree/master/docs#readme history.listen(render); render(history.getCurrentLocation()); // Eliminates the 300ms delay between a physical tap // and the firing of a click event on mobile browsers // https://github.com/ftlabs/fastclick FastClick.attach(document.body); // Enable Hot Module Replacement (HMR) if (module.hot) { module.hot.accept('./routes.json', () => { routes = require('./routes.json'); // eslint-disable-line global-require render(history.getCurrentLocation()); }); }
client/src/containers/MNISTVisualView.js
scandalouswool/rally
/* MNIST MACHINE LEARNING VISUALIZATION */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import _ from 'lodash'; const Synaptic = require('synaptic'); const Network = Synaptic.Network; class MNISTVisualView extends Component { constructor(props) { super(props); this.chart = null; this.maxWidth = 700; this.maxHeight = 500; this.dataSet = []; this.testingData = [{"input":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.196,0.925,1,0.486,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.208,0.906,0.992,0.992,0.42,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.035,0.757,0.992,0.992,0.902,0.016,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.027,0.612,0.992,0.992,0.584,0.141,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.094,0.992,0.992,0.745,0.031,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.012,0.686,0.992,0.992,0.282,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.482,0.992,0.992,0.541,0.012,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.039,0.957,0.992,0.902,0.133,0,0.035,0.094,0.09,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.71,0.992,0.976,0.482,0,0.271,0.765,0.992,0.976,0.573,0.059,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.082,0.906,0.992,0.792,0,0.275,0.925,0.992,0.992,0.992,0.992,0.667,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.086,0.545,0.992,0.835,0.102,0.051,0.784,0.992,0.992,0.718,0.988,0.992,0.863,0.086,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.282,0.992,0.992,0.506,0,0.337,0.992,0.992,0.506,0.016,0.412,0.992,0.992,0.275,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.282,0.992,0.992,0.302,0.086,0.961,0.992,0.718,0.016,0,0.008,0.412,0.992,0.275,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.518,0.992,0.992,0.043,0.094,0.992,0.992,0.455,0,0,0.004,0.588,0.992,0.275,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.741,0.992,0.945,0.039,0.094,0.992,0.992,0.231,0,0,0.322,0.992,0.831,0.118,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.741,0.992,0.576,0,0.094,0.992,0.992,0.588,0.118,0.173,0.816,0.831,0.122,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.741,0.992,0.682,0.012,0.027,0.725,0.992,0.992,0.89,0.969,0.722,0.118,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.588,0.992,0.992,0.569,0.373,0.918,0.992,0.992,0.992,0.494,0.004,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.282,0.992,0.992,0.992,0.992,0.992,0.992,0.992,0.663,0.055,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.02,0.447,0.941,0.992,0.992,0.918,0.529,0.173,0.012,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"output":[0,0,0,0,0,0,1,0,0,0]},{"input":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.102,0.941,0.282,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.098,0.933,0.816,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.82,0.886,0.055,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.82,0.996,0.169,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.686,0.996,0.502,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.247,0.996,0.8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.42,0.996,0.8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.345,0.996,0.8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.216,0.996,0.8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.494,0.996,0.8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.494,0.996,0.741,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.663,0.996,0.475,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.82,0.996,0.757,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.82,0.996,0.435,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.086,0.922,0.996,0.145,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.537,0.996,0.89,0.063,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.804,1,0.725,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.804,0.996,0.49,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.804,0.996,0.49,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.435,0.831,0.169,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"output":[0,1,0,0,0,0,0,0,0,0]},{"input":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.012,0.027,0.027,0.016,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.016,0.051,0.471,0.537,0.729,0.996,0.996,0.533,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.02,0.208,0.561,0.702,0.996,0.996,0.996,1,0.996,0.996,0.757,0,0,0,0,0,0,0,0,0,0,0,0,0,0.016,0.098,0.196,0.584,0.686,0.996,0.996,0.996,0.996,0.996,0.996,1,0.996,0.996,0.424,0,0,0,0,0,0,0,0,0,0,0,0,0.376,0.667,0.996,0.996,0.996,0.996,0.996,0.961,0.718,0.388,0.388,0.576,0.988,0.996,0.769,0.012,0,0,0,0,0,0,0,0,0.016,0.569,0.635,0.635,0.859,0.996,0.996,0.996,0.965,0.729,0.365,0.259,0,0,0,0.49,0.965,0.996,0.467,0.008,0,0,0,0,0,0,0,0,0.341,0.843,0.996,0.996,0.996,0.996,0.8,0.341,0.267,0,0,0,0,0,0.18,0.773,0.996,0.706,0.184,0,0,0,0,0,0,0,0,0,0.659,0.996,0.612,0.314,0.314,0.314,0.11,0,0,0,0,0,0,0,0.494,0.961,1,0.224,0,0,0,0,0,0,0,0,0,0,0.008,0.29,0.129,0,0,0,0,0,0,0,0,0,0,0.169,0.784,0.996,0.357,0.024,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.612,0.961,0.804,0.051,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.486,0.957,0.996,0.333,0.024,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.231,0.851,0.996,0.475,0.027,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.69,0.996,0.996,0.239,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.631,0.961,0.843,0.227,0.027,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.212,0.965,0.996,0.725,0.027,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.486,0.996,0.996,0.251,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.204,0.929,0.996,0.494,0.02,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.463,0.996,0.996,0.467,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.463,0.996,0.996,0.239,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.008,0.024,0.024,0.008,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"output":[0,0,0,0,0,0,0,1,0,0]},{"input":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.11,0.765,0.996,0.996,0.996,0.996,0.996,1,0.239,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.024,0.749,0.992,0.992,0.992,0.992,0.992,0.992,0.992,0.235,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.102,0.745,0.992,0.992,0.992,0.992,0.941,0.749,0.949,0.992,0.235,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.059,0.733,0.992,0.992,0.992,0.992,0.992,0.784,0,0.827,0.992,0.235,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.086,0.259,0.992,0.992,0.992,0.992,0.945,0.82,0.173,0.09,0.855,0.992,0.235,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.486,0.992,0.992,0.992,0.992,0.992,0.714,0,0,0.514,0.992,0.992,0.235,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.149,0.851,0.992,0.992,0.957,0.435,0.145,0,0,0.514,0.992,0.992,0.235,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.486,0.992,0.992,0.992,0.647,0,0,0,0.086,0.714,0.992,0.992,0.235,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.486,0.992,0.992,0.941,0.176,0,0,0,0.208,0.992,0.992,0.976,0.227,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.063,0.659,0.992,0.847,0.176,0,0,0,0,0.208,0.992,0.992,0.541,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.624,0.992,0.992,0.576,0,0,0,0,0,0.208,0.992,0.992,0.541,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.533,0.988,0.992,0.89,0.02,0,0,0,0,0,0.208,0.992,0.953,0.396,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.549,0.992,0.992,0.486,0,0,0,0,0,0,0.612,0.992,0.855,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.051,0.643,0.992,0.557,0.02,0,0,0,0,0,0.125,0.914,0.992,0.855,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.243,0.992,0.992,0.51,0,0,0,0,0,0.145,0.796,0.992,0.992,0.498,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.243,0.992,0.992,0.576,0.141,0.141,0.141,0.141,0.592,0.871,0.992,0.961,0.498,0.031,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.133,0.792,0.992,0.992,0.992,0.992,0.992,0.992,0.992,0.992,0.992,0.784,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.549,0.992,0.992,0.992,0.992,0.992,0.992,0.992,0.973,0.922,0.255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.341,0.678,0.992,0.992,0.992,0.992,0.992,0.992,0.714,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.055,0.306,0.376,0.992,0.992,0.992,0.537,0.22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"output":[1,0,0,0,0,0,0,0,0,0]}] } componentDidMount() { this.chart = d3.select('#visualizer').append('canvas') .attr('width', this.maxWidth) .attr('height', this.maxHeight); this.context = this.chart.node().getContext('2d'); // Create an in-memory element to hold the data this.detachedContainer = document.createElement('custom'); // Create a D3 selection for the detached container this.dataContainer = d3.select(this.detachedContainer); this.drawChart(this.props.ANNJobPoolReady); } componentDidUpdate() { this.drawChart(this.props.ANNJobPoolReady); if (this.props.updatedNetwork.length !== 0) { this.testNetwork(this.props.updatedNetwork); } } drawChart (dataSet) { // Bind data for visualization const dataBinding = this.dataContainer.selectAll('custom') .data(dataSet, (d) => { return d; }); // UPDATE dataBinding .classed('rect', true) .attr('opacity', 0.5) .attr('x', (d, i) => { return 10 + (28 * (i % 10)) + (1 * (i % 10)); }) .attr('y', (d, i) => { return 75 + (28 * Math.floor(i / 10)) + Math.floor(1 * (i / 10)); }) .attr('num', (d) => { return d; }) // ENTER dataBinding.enter() .append('custom') .classed('rect', true) .attr('x', (d, i) => { return 10 + (28 * (i % 10)) + (1 * (i % 10)); }) .attr('y', (d, i) => { return 75 + (28 * Math.floor(i / 10)) + Math.floor(1 * (i / 10)); }) .attr('num', (d) => { return d; }) // EXIT dataBinding.exit() .remove(); this.drawCanvas(dataBinding); this.drawTestingData(); } drawCanvas() { // clear the existing canvas this.context.fillStyle = '#fff'; this.context.rect(0, 0, this.chart.attr('width'), this.chart.attr('height')); this.context.fill(); // Draw text on the screen this.context.font = '24px Arial'; this.context.fillText('Data Under Analysis', 50, 30); this.context.fillText('Testing Set', 450, 30); const elements = this.dataContainer.selectAll("custom.rect"); // Draw each image // context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); // s- is the coordinate to start clipping const self = this; elements.each(function(d) { const node = d3.select(this); const image = new Image(); const randomY = Math.floor( Math.random() * 10 ); image.onload = () => { self.context.drawImage(image, node.attr('num') * 28 + 1 * node.attr('num'), 0 + randomY * 28 + randomY * 1, 28, 28, node.attr('x'), node.attr('y'), 28, 28); } image.src = '../../assets/mnist.png'; }); } drawTestingData() { const self = this; const trainingNumbers = this.testingData.map( (item) => { return item.output.indexOf(1); }); trainingNumbers.forEach( (num, i) => { const image = new Image(); image.onload = () => { self.context.drawImage(image, num * 28 + num * 1, num * 28 + num * 1, 28, 28, 400 + i * 28 + i * 10, 75, 28, 28); } image.src = '../../assets/mnist.png'; }); } drawTestingResults(results) { const self = this; results.forEach( (num, i) => { const image = new Image(); image.onload = () => { self.context.drawImage(image, num * 28 + num * 1, num * 28 + num * 1, 28, 28, 400 + i * 28 + i * 10, 175, 28, 28); } image.src = '../../assets/mnist.png'; }); } testNetwork(updatedNetwork) { updatedNetwork = Network.fromJSON(updatedNetwork.trainedNetwork); const testResults = []; console.log(updatedNetwork); this.testingData.forEach( (test) => { const result = updatedNetwork.activate(test.input); console.log('testing', test.input); const guess = _.max(result); console.log('guess:', guess); console.log('number:', result.indexOf(guess)); testResults.push(result.indexOf(guess)); }); this.drawTestingResults(testResults); console.log('Predictions from network:', testResults); } render() { return ( <div id="visualizer"></div> ); } } function mapStateToProps(state) { return { results: state.updateResults, project: state.selectedProject, ANNJobPoolReady: state.ANNJobPoolReady, updatedNetwork: state.updatedNetwork }; } export default connect(mapStateToProps)(MNISTVisualView);
packages/docs/components/Examples/image/gettingStarted.js
nikgraf/draft-js-plugin-editor
// It is important to import the Editor which accepts plugins. import Editor from '@draft-js-plugins/editor'; import createImagePlugin from '@draft-js-plugins/image'; import React from 'react'; const imagePlugin = createImagePlugin(); // The Editor accepts an array of plugins. In this case, only the imagePlugin // is passed in, although it is possible to pass in multiple plugins. const MyEditor = ({ editorState, onChange }) => ( <Editor editorState={editorState} onChange={onChange} plugins={[imagePlugin]} /> ); export default MyEditor;
src/svg-icons/toggle/radio-button-checked.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleRadioButtonChecked = (props) => ( <SvgIcon {...props}> <path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.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 8z"/> </SvgIcon> ); ToggleRadioButtonChecked = pure(ToggleRadioButtonChecked); ToggleRadioButtonChecked.displayName = 'ToggleRadioButtonChecked'; ToggleRadioButtonChecked.muiName = 'SvgIcon'; export default ToggleRadioButtonChecked;
src/js/app/header/SearchBar/MobileSearchBar.js
ludonow/ludo-beta-react
import React from 'react'; import styled from 'styled-components'; import magnifierIcon from '../../../../images/magnifier.svg'; import { CancelIconButton, CancelIconPlaceHolder, SearchBar } from './common'; const MobileSearchBarWrapper = styled.div` display: flex; justify-content: center; margin: 0 auto; padding: 20px 0; `; const MobileSearchBar = ({ handleSearchSubmitKeyUp, handleSearchingTextChange, handleSearchingTextClear, searchingText }) => ( <MobileSearchBarWrapper> <SearchBar isMobile={true}> <img src={magnifierIcon} /> <input autoFocus maxLength={50} onChange={handleSearchingTextChange} onKeyUp={handleSearchSubmitKeyUp} type="text" value={searchingText} /> { searchingText ? <CancelIconButton handleSearchingTextClear={handleSearchingTextClear} height="25px" isMobile={true} width="25px" /> : <CancelIconPlaceHolder height="25px" width="25px" /> } </SearchBar> </MobileSearchBarWrapper> ); export default MobileSearchBar;
src/svg-icons/notification/personal-video.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPersonalVideo = (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 14H3V5h18v12z"/> </SvgIcon> ); NotificationPersonalVideo = pure(NotificationPersonalVideo); NotificationPersonalVideo.displayName = 'NotificationPersonalVideo'; NotificationPersonalVideo.muiName = 'SvgIcon'; export default NotificationPersonalVideo;
pyxis/views/beacon/all.js
gtkatakura/furb-desenvolvimento-plataformas-moveis
import React from 'react'; import { Text, View, Button, StyleSheet, ScrollView } from 'react-native'; import Components from './../../components'; const styles = StyleSheet.create({ base: { padding: 24, flex: 1 }, name: { fontSize: 24 }, header: { flexWrap: 'wrap', flexDirection: 'row' } }); class ListBeaconsScreen extends Components.PyxisComponent { static navigationOptions = { title: 'Beacons' }; constructor(props) { super(props); this.state = { beacons: [] }; } createBeacon() { this.navigate('NewBeacon'); } goToBeacon(beacon) { this.navigate('Beacon', { beacon }); } async componentWillMount() { const beacons = await this.services.beaconsRepository.all(); this.setState({ beacons }) } render() { return ( <View style={styles.base}> <View> <Text style={styles.name}>Beacons</Text> <View style={styles.header}> { //<Components.PButton title="Excluir" onPress={() => this.remove()}></Components.PButton> } </View> </View> <ScrollView> { this.isMaintainer() && <Components.PButton title="Novo beacon" onPress={() => this.createBeacon()}></Components.PButton> } { this.state.beacons.map((beacon, idx) => { return <Components.PButton key={`${idx}_${beacon.name}`} title={beacon.name} onPress={() => this.goToBeacon(beacon)}></Components.PButton> }) } </ScrollView> <Components.BackButton onPress={() => this.goBack()}></Components.BackButton> </View> ); } } export default ListBeaconsScreen;
src/pages/string/Zalgorithm/Zalgorithm.js
hyy1115/react-redux-webpack3
import React from 'react' class Zalgorithm extends React.Component { render() { return ( <div>Zalgorithm</div> ) } } export default Zalgorithm
src/app/components/DialogExampleSimple.js
leoliew/react-webpack-example
/** * Created by leoliew on 2016/11/28. */ import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import ShowCaseCard from './ShowCaseCard'; /** * Dialog with action buttons. The actions are passed in as an array of React objects, * in this example [FlatButtons](/#/components/flat-button). * * You can also close this dialog by clicking outside the dialog, or with the 'Esc' key. */ export default class DialogExampleSimple extends React.Component { state = { open: false, }; handleOpen = () => { this.setState({open: true}); }; handleClose = () => { this.setState({open: false}); }; render() { const actions = [ <FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose} />, <FlatButton label="Submit" primary={true} keyboardFocused={true} onTouchTap={this.handleClose} />, ]; var showCase = <div> <RaisedButton label="Dialog" onTouchTap={this.handleOpen}/> <Dialog title="Dialog With Actions" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > The actions in this window were passed in as an array of React objects. </Dialog> </div> ; return ( <ShowCaseCard title="Simple dialog" subtitle="Dialog with action buttons. The actions are passed in as an array of React objects, in this example FlatButtons.You can also close this dialog by clicking outside the dialog, or with the 'Esc' key." text={showCase} /> ); } }
src/index.js
faalsh/react-materialize-demo
import React from 'react' import { render } from 'react-dom' import { Router, Route, browserHistory, IndexRoute } from 'react-router' import {Provider} from 'react-redux' import store from './store' import Layout from './containers/Layout/Layout.jsx' import Matches from './containers/Matches/Matches.jsx' import Repos from './containers/Repos/Repos.jsx' import Repo from './components/Repo/Repo.jsx' import {fetchSeasons} from './actions/leagueActions'; import Home from './containers/Home/Home.jsx' import './index.css' // import 'materialize-loader' import './favicon.ico' render(( <Provider store={store} > <Router history={browserHistory}> <Route path="/" component={Layout}> <IndexRoute component={Home}/> <Route path="/repos" component={Repos}> <Route path="/repos/:userName/:repoName" component={Repo}/> </Route> <Route path="/matches" component={Matches}> </Route> </Route> </Router> </Provider> ), document.getElementById('app'))
app/jsx/nav_tourpoints/tour.js
djbender/canvas-lms
/* * Copyright (C) 2020 - 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 Reactour from '@instructure/reactour/dist/reactour.cjs' import I18n from 'i18n!TourPoints' import tourPubSub from './tourPubsub' import TourContainer from './TourContainer' import {Heading} from '@instructure/ui-heading' import useLocalStorage from '../shared/hooks/useLocalStorage' import adminTour from './tours/adminTour' import teacherTour from './tours/teacherTour' import studentTour from './tours/studentTour' import handleOpenTray from './handleOpenTray' const allSteps = { admin: adminTour, teacher: teacherTour, student: studentTour } const softCloseSteps = [ { selector: '.welcome-tour-link', content: ( <section> <Heading level="h3">{I18n.t('Come back later!')}</Heading> {I18n.t('You can access the Welcome Tour here any time as well as other new resources.')} </section> ) } ] const Tour = ({roles}) => { const [currentRole, setCurrentRole] = React.useState(() => { if ( window.ENV?.COURSE?.is_student && roles.includes('student') && !localStorage.getItem(`canvas-tourpoints-shown-student`) ) { // The current page is for a course that the user is a student is in. // And they haven't seen the tour yet. Change roles to student. return 'student' } if ( window.ENV?.COURSE?.is_instructor && roles.includes('teacher') && !localStorage.getItem(`canvas-tourpoints-shown-teacher`) ) { // Same for teacher return 'teacher' } return roles[0] }) const steps = allSteps[currentRole] // TODO: Someday, it would be great if this were stored // in user data as a user setting. const [hasOpened, setHasOpened] = useLocalStorage(`canvas-tourpoints-shown-${currentRole}`, false) const [open, setOpen] = React.useState(!hasOpened) const [reopened, setReopened] = React.useState(false) const [softClose, setSoftClose] = React.useState(false) React.useEffect(() => { // Override the tray dismiss function while this // tour is open; if (open) { tourPubSub.publish('navigation-tray-override-dismiss', true) } return () => tourPubSub.publish('navigation-tray-override-dismiss', false) }, [open]) const handleSoftClose = React.useCallback( async (options = {}) => { const {forceClose} = options setHasOpened(true) if (softClose || forceClose) { restoreTrayScreenReader() tourPubSub.publish('navigation-tray-close') setOpen(false) } else { // As part of the soft close, open the help tray await handleOpenTray('help') setSoftClose(true) const tourElement = document.getElementById('___reactour') if (tourElement) { tourElement.setAttribute('aria-hidden', false) } } }, [setHasOpened, softClose] ) React.useEffect(() => { const escapeClose = e => { if (e.keyCode === 27) { // Escape Key handleSoftClose() } } document.addEventListener('keydown', escapeClose) return () => document.removeEventListener('keydown', escapeClose) }, [handleSoftClose]) const restoreTrayScreenReader = () => { // Restore the nav tray's screen reader visibility const navElement = document.getElementById('nav-tray-portal') if (navElement) { navElement.setAttribute('aria-hidden', false) } const appElement = document.getElementById('application') if (appElement) { appElement.setAttribute('aria-hidden', false) } } const blockApplicationScreenReader = () => { const navElement = document.getElementById('nav-tray-portal') if (navElement) { navElement.setAttribute('aria-hidden', true) } const appElement = document.getElementById('application') if (appElement) { appElement.setAttribute('aria-hidden', true) } } React.useEffect(() => { if (open) { blockApplicationScreenReader() } return () => restoreTrayScreenReader() }, [open]) React.useEffect(() => { const unsub = tourPubSub.subscribe('tour-open', () => { tourPubSub.publish('navigation-tray-close') blockApplicationScreenReader() setOpen(true) setReopened(true) setSoftClose(true) // If we are on a course the user is a student in, show the student tour if (roles.length === 1) { setCurrentRole(roles[0]) } // If user is a student, only show on courses page // that student is enrolled in. else if (window.ENV?.COURSE?.is_student && roles.includes('student')) { setCurrentRole('student') } // If that user is a teacher and not an admin, // just show the tour else if (roles.includes('teacher') && !roles.includes('admin')) { setCurrentRole('teacher') } // If that user is a teacher and an admin, only show on // courses page which the teacher is instructor in else if ( window.ENV?.COURSE?.is_instructor && roles.includes('teacher') && roles.includes('admin') ) { setCurrentRole('teacher') } // If that user is an admin, show the admin tour else if (roles.includes('admin')) { setCurrentRole('admin') } }) return () => unsub() }, [roles]) if (!currentRole || !steps) return null const firstStepLabels = { student: I18n.t('Student Tour'), teacher: I18n.t('Teacher Tour'), admin: I18n.t('Admin Tour') } return ( <Reactour key={`${softClose}-${open}-${currentRole}`} CustomHelper={props => ( <TourContainer softClose={handleSoftClose} close={() => { tourPubSub.publish('navigation-tray-close') restoreTrayScreenReader() props.close() }} firstLabel={firstStepLabels[currentRole] || ''} {...props} /> )} steps={!reopened && softClose ? softCloseSteps : steps} isOpen={open} onRequestClose={handleSoftClose} /> ) } export default Tour
src/components/RouteNavItem.js
availabs/avail_app_bootstrap
import React from 'react'; import { Route } from 'react-router-dom'; import { NavItem } from 'react-bootstrap'; export default props => ( <Route path={props.href} exact children={({ match, history }) => ( <NavItem onClick={e => history.push(e.currentTarget.getAttribute('href'))} {...props} active={match ? true : false} > {props.children} </NavItem> )} /> );
src-example/components/organisms/FeatureList/index.stories.js
SIB-Colombia/biodiversity_catalogue_v2_frontend
import React from 'react' import { storiesOf } from '@kadira/storybook' import { FeatureList } from 'components' storiesOf('FeatureList', module) .add('default', () => ( <FeatureList /> ))
src/collections/Form/FormDropdown.js
koenvg/Semantic-UI-React
import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, } from '../../lib' import Dropdown from '../../modules/Dropdown' import FormField from './FormField' /** * Sugar for <Form.Field control={Dropdown} />. * @see Dropdown * @see Form */ function FormDropdown(props) { const { control } = props const rest = getUnhandledProps(FormDropdown, props) const ElementType = getElementType(FormDropdown, props) return <ElementType {...rest} control={control} /> } FormDropdown._meta = { name: 'FormDropdown', parent: 'Form', type: META.TYPES.COLLECTION, } FormDropdown.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** A FormField control prop. */ control: FormField.propTypes.control, } FormDropdown.defaultProps = { as: FormField, control: Dropdown, } export default FormDropdown
src/RefreshIndicator/RefreshIndicator.js
rscnt/material-ui
import React from 'react'; import autoPrefix from '../utils/autoPrefix'; import transitions from '../styles/transitions'; import Paper from '../Paper'; const VIEWBOX_SIZE = 32; function getStyles(props) { const padding = props.size * 0.1; // same implementation of `this.getPaddingSize()` return { root: { position: 'absolute', zIndex: 2, width: props.size, height: props.size, padding: padding, top: -10000, left: -10000, transform: `translate3d(${10000 + props.left}px, ${10000 + props.top}px, 0)`, opacity: props.status === 'hide' ? 0 : 1, transition: props.status === 'hide' ? transitions.create('all', '.3s', 'ease-out') : 'none', }, }; } class RefreshIndicator extends React.Component { static propTypes = { /** * Override the theme's color of the indicator while it's status is * "ready" and it's percentage is less than 100. */ color: React.PropTypes.string, /** * The absolute left position of the indicator in pixels. */ left: React.PropTypes.number.isRequired, /** * Override the theme's color of the indicator while * it's status is "loading" or when it's percentage is 100. */ loadingColor: React.PropTypes.string, /** * The confirmation progress to fetch data. Max value is 100. */ percentage: React.PropTypes.number, /** * Size in pixels. */ size: React.PropTypes.number, /** * The display status of the indicator. If the status is * "ready", the indicator will display the ready state * arrow. If the status is "loading", it will display * the loading progress indicator. If the status is "hide", * the indicator will be hidden. */ status: React.PropTypes.oneOf(['ready', 'loading', 'hide']), /** * Override the inline-styles of the root element. */ style: React.PropTypes.object, /** * The absolute top position of the indicator in pixels. */ top: React.PropTypes.number.isRequired, }; static defaultProps = { percentage: 0, size: 40, status: 'hide', }; static contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; componentDidMount() { this.componentDidUpdate(); } componentDidUpdate() { this.scalePath(this.refs.path, 0); this.rotateWrapper(this.refs.wrapper); } componentWillUnmount() { clearTimeout(this.scalePathTimer); clearTimeout(this.rotateWrapperTimer); clearTimeout(this.rotateWrapperSecondTimer); } renderChildren() { const {prepareStyles} = this.context.muiTheme; const paperSize = this.getPaperSize(); let childrenCmp = null; if (this.props.status !== 'ready') { const circleStyle = this.getCircleStyle(paperSize); childrenCmp = ( <div ref="wrapper" style={prepareStyles({ transition: transitions.create('transform', '20s', null, 'linear'), width: '100%', height: '100%', })} > <svg style={{ width: paperSize, height: paperSize, }} viewBox={`0 0 ${VIEWBOX_SIZE} ${VIEWBOX_SIZE}`} > <circle ref="path" style={prepareStyles(Object.assign(circleStyle.style, { transition: transitions.create('all', '1.5s', null, 'ease-in-out'), }))} {...circleStyle.attr} /> </svg> </div> ); } else { const circleStyle = this.getCircleStyle(paperSize); const polygonStyle = this.getPolygonStyle(paperSize); childrenCmp = ( <svg style={{ width: paperSize, height: paperSize, }} viewBox={`0 0 ${VIEWBOX_SIZE} ${VIEWBOX_SIZE}`} > <circle style={prepareStyles(circleStyle.style)} {...circleStyle.attr} > </circle> <polygon style={prepareStyles(polygonStyle.style)} {...polygonStyle.attr} /> </svg> ); } return childrenCmp; } getTheme() { return this.context.muiTheme.refreshIndicator; } getPaddingSize() { const padding = this.props.size * 0.1; return padding; } getPaperSize() { return this.props.size - this.getPaddingSize() * 2; } getCircleAttr() { return { radiu: VIEWBOX_SIZE / 2 - 5, originX: VIEWBOX_SIZE / 2, originY: VIEWBOX_SIZE / 2, strokeWidth: 3, }; } getArcDeg() { const p = this.props.percentage / 100; const beginDeg = p * 120; const endDeg = p * 410; return [beginDeg, endDeg]; } getFactor() { const p = this.props.percentage / 100; const p1 = Math.min(1, p / 0.4); return p1; } getCircleStyle() { const isLoading = this.props.status === 'loading'; const p1 = isLoading ? 1 : this.getFactor(); const circle = this.getCircleAttr(); const perimeter = Math.PI * 2 * circle.radiu; const [beginDeg, endDeg] = this.getArcDeg(); const arcLen = (endDeg - beginDeg) * perimeter / 360; const dashOffset = -beginDeg * perimeter / 360; const theme = this.getTheme(); return { style: { strokeDasharray: `${arcLen}, ${(perimeter - arcLen)}`, strokeDashoffset: dashOffset, stroke: (isLoading || this.props.percentage === 100) ? (this.props.loadingColor || theme.loadingStrokeColor) : (this.props.color || theme.strokeColor), strokeLinecap: 'round', opacity: p1, strokeWidth: circle.strokeWidth * p1, fill: 'none', }, attr: { cx: circle.originX, cy: circle.originY, r: circle.radiu, }, }; } getPolygonStyle() { const p1 = this.getFactor(); const circle = this.getCircleAttr(); const triangleCx = circle.originX + circle.radiu; const triangleCy = circle.originY; const dx = (circle.strokeWidth * 7 / 4) * p1; const trianglePath = `${(triangleCx - dx)},${triangleCy} ${(triangleCx + dx)},${ triangleCy} ${triangleCx},${(triangleCy + dx)}`; const [, endDeg] = this.getArcDeg(); const theme = this.getTheme(); return { style: { fill: this.props.percentage === 100 ? (this.props.loadingColor || theme.loadingStrokeColor) : (this.props.color || theme.strokeColor), transform: `rotate(${endDeg}deg)`, transformOrigin: `${circle.originX}px ${circle.originY}px`, opacity: p1, }, attr: { points: trianglePath, }, }; } scalePath(path, step) { if (this.props.status !== 'loading') return; const currStep = (step || 0) % 3; const circle = this.getCircleAttr(); const perimeter = Math.PI * 2 * circle.radiu; const arcLen = perimeter * 0.64; let strokeDasharray; let strokeDashoffset; let transitionDuration; if (currStep === 0) { strokeDasharray = '1, 200'; strokeDashoffset = 0; transitionDuration = '0ms'; } else if (currStep === 1) { strokeDasharray = `${arcLen}, 200`; strokeDashoffset = -15; transitionDuration = '750ms'; } else { strokeDasharray = `${arcLen}, 200`; strokeDashoffset = -(perimeter - 1); transitionDuration = '850ms'; } autoPrefix.set(path.style, 'strokeDasharray', strokeDasharray); autoPrefix.set(path.style, 'strokeDashoffset', strokeDashoffset); autoPrefix.set(path.style, 'transitionDuration', transitionDuration); this.scalePathTimer = setTimeout(() => this.scalePath(path, currStep + 1), currStep ? 750 : 250); } rotateWrapper(wrapper) { if (this.props.status !== 'loading') return; autoPrefix.set(wrapper.style, 'transform', null); autoPrefix.set(wrapper.style, 'transform', 'rotate(0deg)'); autoPrefix.set(wrapper.style, 'transitionDuration', '0ms'); this.rotateWrapperSecondTimer = setTimeout(() => { autoPrefix.set(wrapper.style, 'transform', 'rotate(1800deg)'); autoPrefix.set(wrapper.style, 'transitionDuration', '10s'); autoPrefix.set(wrapper.style, 'transitionTimingFunction', 'linear'); }, 50); this.rotateWrapperTimer = setTimeout(() => this.rotateWrapper(wrapper), 10050); } render() { const {style} = this.props; const styles = getStyles(this.props, this.context); return ( <Paper circle={true} style={Object.assign(styles.root, style)} ref="indicatorCt" > {this.renderChildren()} </Paper> ); } } export default RefreshIndicator;
src/parser/demonhunter/havoc/modules/talents/DemonBlades.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import Events from 'parser/core/Events'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import { formatThousands, formatPercentage } from 'common/format'; /** * Example Report: https://www.warcraftlogs.com/reports/4GR2pwAYW8KtgFJn/#fight=6&source=18 */ class DemonBlades extends Analyzer{ furyGain = 0; furyWaste = 0; damage = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.DEMON_BLADES_TALENT.id); if (!this.active) { return; } this.addEventListener(Events.energize.by(SELECTED_PLAYER).spell(SPELLS.DEMON_BLADES_FURY), this.onEnergizeEvent); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.DEMON_BLADES_FURY), this.onDamageEvent); } onEnergizeEvent(event) { this.furyGain += event.resourceChange; this.furyWaste += event.waste; } onDamageEvent(event) { this.damage += event.amount; } get furyPerMin() { return ((this.furyGain - this.furyWaste) / (this.owner.fightDuration/60000)).toFixed(2); } get suggestionThresholds() { return { actual: this.furyWaste / this.furyGain, isGreaterThan: { minor: 0.03, average: 0.07, major: 0.1, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<> Be mindful of your Fury levels and spend it before capping your Fury due to <SpellLink id={SPELLS.DEMON_BLADES_TALENT.id} />.</>) .icon(SPELLS.DEMON_BLADES_TALENT.icon) .actual(`${formatPercentage(actual)}% Fury wasted`) .recommended(`${formatPercentage(recommended)}% is recommended.`); }); } statistic(){ const effectiveFuryGain = this.furyGain - this.furyWaste; return ( <TalentStatisticBox talent={SPELLS.DEMON_BLADES_TALENT.id} position={STATISTIC_ORDER.OPTIONAL(6)} value={( <> {this.furyPerMin} <small>Fury per min</small> <br /> {this.owner.formatItemDamageDone(this.damage)} </> )} tooltip={( <> {formatThousands(this.damage)} Total damage<br /> {effectiveFuryGain} Effective Fury gained<br /> {this.furyGain} Total Fury gained<br /> {this.furyWaste} Fury wasted </> )} /> ); } } export default DemonBlades;
django/webcode/webcode/frontend/node_modules/react-bootstrap/es/Fade.js
OpenKGB/webcode
import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import Transition from 'react-overlays/lib/Transition'; var propTypes = { /** * Show the component; triggers the fade in or fade out animation */ 'in': PropTypes.bool, /** * Wait until the first "enter" transition to mount the component (add it to the DOM) */ mountOnEnter: PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: PropTypes.bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ transitionAppear: PropTypes.bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: PropTypes.number, /** * Callback fired before the component fades in */ onEnter: PropTypes.func, /** * Callback fired after the component starts to fade in */ onEntering: PropTypes.func, /** * Callback fired after the has component faded in */ onEntered: PropTypes.func, /** * Callback fired before the component fades out */ onExit: PropTypes.func, /** * Callback fired after the component starts to fade out */ onExiting: PropTypes.func, /** * Callback fired after the component has faded out */ onExited: PropTypes.func }; var defaultProps = { 'in': false, timeout: 300, mountOnEnter: false, unmountOnExit: false, transitionAppear: false }; var Fade = function (_React$Component) { _inherits(Fade, _React$Component); function Fade() { _classCallCheck(this, Fade); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Fade.prototype.render = function render() { return React.createElement(Transition, _extends({}, this.props, { className: classNames(this.props.className, 'fade'), enteredClassName: 'in', enteringClassName: 'in' })); }; return Fade; }(React.Component); Fade.propTypes = propTypes; Fade.defaultProps = defaultProps; export default Fade;
src/common/Clipboard/Clipboard.js
Syncano/syncano-dashboard
import React from 'react'; import CopyToClipboard from 'react-copy-to-clipboard'; import { IconButton, FlatButton, FontIcon } from 'material-ui'; import Tooltip from '../Tooltip'; import Truncate from '../Truncate'; const Clipboard = ({ style, iconStyle, tooltip, text, copyText, onCopy, type, children, ...other }) => { const styles = { listItem: { display: 'flex', padding: '16px 16px 16px 72px' }, tooltipInnerDiv: { display: 'flex' }, fontIcon: { fontSize: '1.3em', paddingLeft: 10 } }; const renderIcon = () => ( <IconButton iconClassName="synicon-link-variant" style={style} iconStyle={iconStyle} tooltip={tooltip} /> ); const renderButton = () => ( <FlatButton {...other} primary={true} /> ); const renderLink = () => ( <div> <Tooltip label={tooltip}> <div style={styles.tooltipInnerDiv}> <Truncate text={text || copyText} /> <FontIcon color="#b8c0c9" style={styles.fontIcon} className="synicon-link-variant" /> </div> </Tooltip> </div> ); const renderListItem = () => ( <div style={styles.listItem}> <Truncate text={text || copyText} /> </div> ); const renderContent = () => { const actions = { icon: renderIcon(), button: renderButton(), link: renderLink(), list: renderListItem() }; return actions[type] || <div>{children}</div>; }; return ( <CopyToClipboard text={copyText} onCopy={onCopy} > {renderContent()} </CopyToClipboard> ); }; export default Clipboard;
src/components/Contact/ContactPage.js
liutongchen/liutong-chen-website
import React from 'react'; import { Col, Row, Tooltip, OverlayTrigger } from 'react-bootstrap'; import personalInfo from '../../../src/info'; import ScrollToTopOnMount from '../commons/ScrollToTopOnMount'; const ContactPage = () => { const gmailTooltip = ( <Tooltip id="tooltip">Gmail</Tooltip> ); const linkedinTooltip = ( <Tooltip id="tooltip">Linkedin</Tooltip> ); const githubTooltip = ( <Tooltip id="tooltip">Github</Tooltip> ); return ( <div> <ScrollToTopOnMount /> <h2 id="contactPageTitle">Let's get in touch!</h2> <Row id="contactIcon"> <Col xs={4} sm={2} smOffset={3} md={2} mdOffset={3}> <OverlayTrigger placement="bottom" overlay={gmailTooltip}> <a href={"mailto:" + personalInfo.basicInfo.email}> <img src="http://res.cloudinary.com/dla0ocfbw/image/upload/v1500355125/personalWebsite/email-icon.ico" alt="email" /> </a> </OverlayTrigger> </Col> <Col xs={4} sm={2} md={2}> <OverlayTrigger placement="bottom" overlay={linkedinTooltip}> <a href={personalInfo.basicInfo.linkedin}> <img src="http://res.cloudinary.com/dla0ocfbw/image/upload/v1500355124/personalWebsite/linkedin-icon.png" alt="linkedin" /> </a> </OverlayTrigger> </Col> <Col xs={4} sm={2} md={2}> <OverlayTrigger placement="bottom" overlay={githubTooltip}> <a href={personalInfo.basicInfo.github}> <img src="http://res.cloudinary.com/dla0ocfbw/image/upload/v1500353959/personalWebsite/github-icon.png" alt="github" /> </a> </OverlayTrigger> </Col> </Row> </div> ); }; export default ContactPage;
src/components/page/Page.js
Ca1YuChen/Lottery
import React from 'react'; import LotteryList from '../LotteryList/LotteryList'; import ButtonAppBar from '../ButtonAppBar/ButtonAppBar'; import AlertDialog from '../AlertDialog/AlertDialog'; import './Page.css'; export default class Page extends React.Component { constructor(props) { super(props); this.state = { 'max': 100, 'start':false, 'reset':false }; this.handleChangeMax = this.handleChangeMax.bind(this); } handleChangeMax(max) { this.setState({ 'max':max, 'start':false, 'reset':false }); } render() { return ( <div className='page'> <ButtonAppBar className='app-bar' handler={this.handleChangeMax}/> <LotteryList max={this.state.max} start={this.state.start} reset={this.state.reset}/> </div> ); } }
actor-apps/app-web/src/app/utils/require-auth.js
hzy87email/actor-platform
import React from 'react'; import LoginStore from 'stores/LoginStore'; export default (Component) => { return class Authenticated extends React.Component { static willTransitionTo(transition) { if (!LoginStore.isLoggedIn()) { transition.redirect('/auth', {}, {'nextPath': transition.path}); } } render() { return <Component {...this.props}/>; } }; };
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/FormComponents/SingleInput.js
Minoli/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import PropTypes from 'prop-types'; const SingleInput = (props) => ( <div className="form-group label-floating is-empty"> <label className="control-label">{props.title}</label> <input className="form-control" name={props.name} type={props.inputType} value={props.content} onChange={props.controlFunc} placeholder={props.placeholder} /> <p className="help-block">{props.helpText}</p> </div> ); SingleInput.propTypes = { inputType: PropTypes.oneOf(['text', 'number']).isRequired, title: PropTypes.string.isRequired, name: PropTypes.string.isRequired, controlFunc: PropTypes.func.isRequired, content: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]).isRequired, placeholder: PropTypes.string, }; export default SingleInput;
src/screen/RobotArm/RobotArm.js
wavicles/fossasia-pslab-apps
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container, KnobWrapper, PaintWrapper, Spacer, } from './RobotArm.styles'; import PaintArea from './Components/PaintArea'; import KnobControl from './Components/KnobControl'; import range from 'lodash/range'; const electron = window.require('electron'); const { ipcRenderer } = electron; const loadBalancer = window.require('electron-load-balancer'); class RobotArm extends Component { constructor(props) { super(props); this.state = { brush1: 0, brush2: 0, brush3: 0, brush4: 0, servo1: range(60).map(item => null), servo2: range(60).map(item => null), servo3: range(60).map(item => null), servo4: range(60).map(item => null), activeBrush: null, active: false, timeLine: 0, }; this.timer = null; } sendCommand = () => { const { active, timeLine, servo1, servo2, servo3, servo4 } = this.state; if (timeLine < 60) { active && this.setState( prevState => ({ timeLine: prevState.timeLine + 1 }), () => { loadBalancer.sendData(ipcRenderer, 'linker', { command: 'SET_ROBO_ARM', angle1: servo1[timeLine], angle2: servo2[timeLine], angle3: servo3[timeLine], angle4: servo4[timeLine], }); }, ); } else { this.stop(); } }; start = () => { this.setState( { active: true, }, () => { if (this.timer === null) { this.timer = setInterval(this.sendCommand, 1000); } }, ); }; pause = () => { this.setState({ active: false, }); }; stop = () => { clearInterval(this.timer); this.timer = null; this.setState({ active: false, timeLine: 0, }); }; changeBrushValue = brushNumber => value => { this.setState({ [brushNumber]: value, }); }; setActiveBrush = value => { this.setState({ activeBrush: value, }); }; setServoValues = (value, servoType, index) => { let newArray = [...this.state[servoType]]; newArray[index] = value; this.setState({ [servoType]: newArray, }); }; render() { const { brush1, brush2, brush3, brush4, servo1, servo2, servo3, servo4, activeBrush, timeLine, active, } = this.state; const { isConnected } = this.props; return ( <Container> <KnobWrapper> <KnobControl isConnected={isConnected} changeBrushValue={this.changeBrushValue} brush1={brush1} brush2={brush2} brush3={brush3} brush4={brush4} setActiveBrush={this.setActiveBrush} start={this.start} pause={this.pause} stop={this.stop} active={active} /> </KnobWrapper> <Spacer /> <PaintWrapper> <PaintArea timeLine={timeLine} brush1={brush1} brush2={brush2} brush3={brush3} brush4={brush4} servo1={servo1} servo2={servo2} servo3={servo3} servo4={servo4} activeBrush={activeBrush} setServoValues={this.setServoValues} /> </PaintWrapper> </Container> ); } } const mapStateToProps = state => ({ isConnected: state.app.device.isConnected, }); export default connect( mapStateToProps, null, )(RobotArm);
docs/app/Examples/elements/Button/Variations/ButtonExampleCircular.js
koenvg/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleCircular = () => ( <Button circular icon='settings' /> ) export default ButtonExampleCircular
src/svg-icons/image/tonality.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTonality = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93s3.05-7.44 7-7.93v15.86zm2-15.86c1.03.13 2 .45 2.87.93H13v-.93zM13 7h5.24c.25.31.48.65.68 1H13V7zm0 3h6.74c.08.33.15.66.19 1H13v-1zm0 9.93V19h2.87c-.87.48-1.84.8-2.87.93zM18.24 17H13v-1h5.92c-.2.35-.43.69-.68 1zm1.5-3H13v-1h6.93c-.04.34-.11.67-.19 1z"/> </SvgIcon> ); ImageTonality = pure(ImageTonality); ImageTonality.displayName = 'ImageTonality'; ImageTonality.muiName = 'SvgIcon'; export default ImageTonality;
src/render-to-layer.js
XiaonuoGantan/material-ui
import React from 'react'; import ReactDOM from 'react-dom'; import Events from './utils/events'; import Dom from './utils/dom'; import debounce from 'lodash.debounce'; // heavily inspired by https://github.com/Khan/react-components/blob/master/js/layered-component-mixin.jsx const RenderToLayer = React.createClass({ componentDidMount() { this._renderLayer(); }, componentDidUpdate() { this._renderLayer(); }, componentWillUnmount() { this._unbindClickAway(); if (this._layer) { this._unrenderLayer(); } }, _checkClickAway(e) { if (!this.canClickAway) { return; } const el = this._layer; if (e.target !== el && (e.target === window) || (document.documentElement.contains(e.target) && !Dom.isDescendant(el, e.target))) { if (this.props.componentClickAway) { this.props.componentClickAway(e); } } }, _preventClickAway(e) { if (e.detail === this) { return; } this.canClickAway = false; }, _allowClickAway() { this.canClickAway = true; }, getLayer() { return this._layer; }, render() { return null; }, _renderLayer() { if (this.props.open) { if (!this._layer) { this._layer = document.createElement('div'); document.body.appendChild(this._layer); } this._bindClickAway(); if (this.reactUnmount) { this.reactUnmount.cancel(); } } else if (this._layer) { this._unbindClickAway(); this._unrenderLayer(); } else { return; } // By calling this method in componentDidMount() and // componentDidUpdate(), you're effectively creating a "wormhole" that // funnels React's hierarchical updates through to a DOM node on an // entirely different part of the page. const layerElement = this.props.render(); // Renders can return null, but React.render() doesn't like being asked // to render null. If we get null back from renderLayer(), just render // a noscript element, like React does when an element's render returns // null. if (layerElement === null) { this.layerElement = ReactDOM.unstable_renderSubtreeIntoContainer(this, <noscript />, this._layer); } else { this.layerElement = ReactDOM.unstable_renderSubtreeIntoContainer(this, layerElement, this._layer); } }, _unrenderLayer: function() { if (!this.reactUnmount) this.reactUnmount = debounce(() => { if (this._layer) { if (this.layerWillUnmount) { this.layerWillUnmount(this._layer); } ReactDOM.unmountComponentAtNode(this._layer); document.body.removeChild(this._layer); this._layer = null; } }, 1000); this.reactUnmount(); }, _bindClickAway() { if (typeof (this.canClickAway) === 'undefined') { this.canClickAway = true; } Events.on(window, 'focus', this._checkClickAway); Events.on(document, 'mousedown', this._checkClickAway); Events.on(document, 'touchend', this._checkClickAway); }, _unbindClickAway() { Events.off(window, 'focus', this._checkClickAway); Events.off(document, 'mousedown', this._checkClickAway); Events.off(document, 'touchend', this._checkClickAway); }, }); export default RenderToLayer;
src/svg-icons/device/signal-cellular-0-bar.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellular0Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z"/> </SvgIcon> ); DeviceSignalCellular0Bar = pure(DeviceSignalCellular0Bar); DeviceSignalCellular0Bar.displayName = 'DeviceSignalCellular0Bar'; DeviceSignalCellular0Bar.muiName = 'SvgIcon'; export default DeviceSignalCellular0Bar;
login-test/src/App.js
linearworlds/cognito-groups
import React, { Component } from 'react'; import { withRouter, Link } from 'react-router-dom'; import Routes from './Routes'; import RouteNavItem from './components/RouteNavItem'; import AWS from 'aws-sdk'; import {clearAwsCredentials, getCurrentUser, getTokens, testIsAdminUser} from './libs/awsLib'; import config from './config.js'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { userToken: null, accessToken: null, refreshToken: null, isAdminUser: false, isLoadingUserToken: true, }; } updateUserToken = (userToken) => { this.setState({ userToken: userToken }); } updateAccessToken = (accessToken) => { this.setState({ accessToken: accessToken }); } updateRefreshToken = (refreshToken) => { this.setState({ refreshToken: refreshToken }); } setIsAdminUser = (isAdminUser) => { this.setState({ isAdminUser: isAdminUser }); } // TODO: need to factor out code that gets user token and keys so it can be called from multiple places. needs to be called on login as well as componentDidMount async componentDidMount() { AWS.config.region = config.cognito.REGION; const currentUser = getCurrentUser(); if(currentUser === null) { console.log("no current user"); this.setState({isLoadingUserToken: false}); return; } try { console.log("try to get tokens"); const tokens = await getTokens(currentUser); console.log("id token: " + tokens.idToken); console.log("access token: " + tokens.accessToken); this.updateUserToken(tokens.idToken); this.updateAccessToken(tokens.accessToken); this.updateRefreshToken(tokens.refreshToken); const isAdminUser = testIsAdminUser(tokens.idToken, config.admin.admin_group); this.setIsAdminUser(isAdminUser); } catch(e) { if (e.code === "UserNotFoundException") { console.log("JDS user not found"); } else { alert(e); } } this.setState({isLoadingUserToken: false}); } handleNavLink = (event) => { event.preventDefault(); this.props.history.push(event.currentTarget.getAttribute('href')); } handleLogout = (event) => { const currentUser = getCurrentUser(); if(currentUser !== null) { currentUser.signOut(); clearAwsCredentials(); } this.updateUserToken(null); this.updateAccessToken(null); this.updateRefreshToken(null); this.setIsAdminUser(false); this.props.history.push('/login'); } render() { const childProps = { userToken: this.state.userToken, refreshToken: this.state.refreshToken, isAdminUser: this.state.isAdminUser, updateUserToken: this.updateUserToken, updateAccessToken: this.updateAccessToken, updateRefreshToken: this.updateRefreshToken, setIsAdminUser: this.setIsAdminUser, }; return ! this.state.isLoadingUserToken && ( <div className="container-fluid"> <nav className="navbar navbar-default"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-targets="#navbar-collapse-1" aria-expanded="false"> <span className="sr-only">Toggle Navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <Link className="navbar-brand" to="/">Metrics Dashboard Admin</Link> </div> <div className="collapse navbar-collapse" id="navbar-collapse-1"> <ul className="nav navbar-nav navbar-right"> { this.state.userToken ? <li><a onClick={this.handleLogout} href="#" >Logout</a></li> : [<RouteNavItem key={1} onClick={this.handleNavLink} href="/signup">Signup</RouteNavItem>, <RouteNavItem key={2} onClick={this.handleNavLink} href="/login">Login</RouteNavItem> ]} </ul> </div> </nav> <Routes childProps={childProps} /> </div> ); } } export default withRouter(App);
modules/Layout.js
cloudytimemachine/frontend
import React from 'react' import { Link } from 'react-router/lib/Link' import Navbar from './Common/Navbar' import FooterSocialButtons from './Common/FooterSocialButtons' export default React.createClass({ render() { return ( <div> <Navbar /> {this.props.children} <footer className="footer"> <div className="container"> <div className="col-sm-4 pull-left"> <p className="text-muted">&copy; <a href="https://twitter.com/rosskukulinski" target="_blank">Ross Kukulinski</a>, <a href="https://github.com/geojaz" target="_blank">Eric Hole</a> and <a href="https://github.com/orgs/cloudytimemachine/people" target="_blank">Contributors</a></p> </div> {/* <div className="col-sm-4 pull-right"> <FooterSocialButtons className="row content" /> </div> */} </div> </footer> </div> ) } })
demo/dynamic-hexbin.js
joelburget/d4
import React from 'react'; import {range} from 'd3-array'; import {hexbin as d3hexbin} from 'd3-hexbin'; import {randomNormal} from 'd3-random'; import {scaleLinear} from 'd3-scale'; import {interpolateLab} from 'd3-interpolate'; const width = 960; const height = 500; let i = -1; let theta = 0; const deltaTheta = 0.3; const n = 2000; const k = 20; let randomX = randomNormal(width / 2, 80); let randomY = randomNormal(height / 2, 80); let points = range(n).map(function() { return [randomX(), randomY()]; }); const color = scaleLinear() .domain([0, 20]) .range(["rgba(0, 0, 0, 0)", "steelblue"]) .interpolate(interpolateLab); const hexbin = d3hexbin().radius(20); export default class DynamicHexbin extends React.Component { constructor(props) { super(props); this.state = {points}; } componentDidMount() { this.handle = window.setInterval(() => { this._update(); }, 20); } componentWillUnmount() { window.clearInterval(this.handle); } _update() { theta += deltaTheta; randomX = randomNormal(width / 2 + 80 * Math.cos(theta), 80), randomY = randomNormal(height / 2 + 80 * Math.sin(theta), 80); for (let j = 0; j < k; ++j) { i = (i + 1) % n; points[i][0] = randomX(); points[i][1] = randomY(); } this.setState({ points }); } render() { const hexagons = hexbin(this.state.points).map(point => ( <path d={hexbin.hexagon(19.5)} transform={`translate(${point.x}, ${point.y})`} fill={color(point.length)} /> )); return ( <svg width={width} height={height}> <g className="hexagons"> {hexagons} </g> </svg> ); } }
src/App.js
babizhu/you-you
import React, { Component } from 'react'; import { BarChart } from 'react-d3-components'; import { DatePicker } from 'antd'; import { NICE, SUPER_NICE } from './colors'; //import 'antd/style/index.less'; // import less for modifyVars import 'antd/lib/index.css'; //import {buildChartsData} from './milk/data/MilkData' //const x = buildChartsData(); //for( let y of x){ // console.log(y.date + ":" + y.totalTimes + "," + y.drinkAmount + "," + JSON.stringify(y.chartsData)); //} import MilkChartses from './milk/components/DayAndNightCharts'; class Counter extends Component { constructor(props) { super(props); this.state = {counter: 0}; this.interval = setInterval(() => this.tick(), 1000); } tick() { this.setState({ counter: this.state.counter + this.props.increment }); } componentWillUnmount() { clearInterval(this.interval); } /** * 计算吃奶的总量 * @param data * @returns {number} */ calcTotalMl( data ){ //console.log(JSON.stringify(data)); //console.log("data.label - " + (data.label)); //console.log("data.value count = " + (data.values.length)); let total = 0; for( let i = 0; i < data.values.length; i++ ){ //console.log( data.values[i] ); total += data.values[i].y; } return total; } /** * 计算吃奶的总次数 * @param data * @returns {number} */ calcTotalTimes( data ){ //console.log(JSON.stringify(data)); //console.log("data.label - " + (data.label)); //console.log("data.value count = " + (data.values.length)); let total = 0; for( let i = 0; i < data.values.length; i++ ){ if( data.values[i].y !== 0 ){ total++; } } return total; } render() { //var BarChart = ReactD3.BarChart; const data1 = { label: 'chinaideliang', values: [{x: '0', y: 0}, {x: '1', y: 0}, {x: '2', y: 0},{x: '3', y: 70}, {x: '4', y: 0}, {x: '5', y: 0},{x: '6', y: 90}, {x: '7', y: 0}, {x: '8', y: 0}, {x: '9', y: 80}, {x: '10', y:0}, {x: '11', y: 0},{x: '12', y: 0}, {x: '13', y: 80}, {x: '14', y: 0}, {x: '15', y: 20}, {x: '16', y: 50}, {x: '17', y: 0},{x: '18', y: 0}, {x: '19', y: 50}, {x: '20', y: 80}, {x: '21', y: 60}, {x: '22', y: 0}, {x: '23', y: 0}] }; const data2 = { label: 'chinaideliang', values: [{x: '0', y: 70}, {x: '1', y: 0}, {x: '2', y: 0},{x: '3', y: 0}, {x: '4', y: 90}, {x: '5', y: 0},{x: '6', y: 0}, {x: '7', y: 80}, {x: '8', y: 0}, {x: '9', y: 0}, {x: '10', y: 40}, {x: '11', y: 0},{x: '12', y: 110}, {x: '13', y: 0}, {x: '14', y: 0}, {x: '15', y: 90}, {x: '16', y: 0}, {x: '17', y: 0},{x: '18', y: 80}, {x: '19', y: 0}, {x: '20', y: 0}, {x: '21', y: 90}, {x: '22', y: 0}, {x: '23', y: 0}] }; return ( <div> <h2 style={{margin:'30px'}}>2016-01-27( 总量 :<span style={{color:'red'}}> {this.calcTotalMl(data1)}</span>毫升 | 总次数 :<span style={{color:'red'}}> {this.calcTotalTimes(data1)}</span>次)</h2> <BarChart data={data1} width={1000} height={400} yAxis={{label: "毫升"}} margin={{top: 10, bottom: 50, left: 50, right: 10}}/> <h2 style={{margin:'30px'}}>2016-01-28( 总量 :<span style={{color:'red'}}> {this.calcTotalMl(data2)}</span>毫升 | 总次数 :<span style={{color:'red'}}> {this.calcTotalTimes(data2)}</span>次)</h2> <BarChart data={data2} width={1000} height={400} yAxis={{label: "毫升"}} margin={{top: 10, bottom: 50, left: 50, right: 10}}/> </div> ); } } //<Counter increment={1} color={NICE}/> export class App extends Component { render() { return ( <div> <MilkChartses /> </div> ); } }
src/svg-icons/av/playlist-play.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvPlaylistPlay = (props) => ( <SvgIcon {...props}> <path d="M19 9H2v2h17V9zm0-4H2v2h17V5zM2 15h13v-2H2v2zm15-2v6l5-3-5-3z"/> </SvgIcon> ); AvPlaylistPlay = pure(AvPlaylistPlay); AvPlaylistPlay.displayName = 'AvPlaylistPlay'; AvPlaylistPlay.muiName = 'SvgIcon'; export default AvPlaylistPlay;
demo/src/common/routes/Routes.js
misterfresh/react-easy-transition
'use strict' import React from 'react' import { Route, IndexRoute } from 'react-router' import App from 'containers/App' import Home from './Home/Home' import About from './About/About' import Contact from './Contact/Contact' import NoMatch from 'containers/NoMatch' export default ( <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="about" component={About} /> <Route path="contact" component={Contact} /> <Route path="*" component={NoMatch} /> </Route> )
Libraries/Modal/Modal.js
happypancake/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Modal * @flow */ 'use strict'; const AppContainer = require('AppContainer'); const I18nManager = require('I18nManager'); const Platform = require('Platform'); const React = require('React'); const PropTypes = require('prop-types'); const StyleSheet = require('StyleSheet'); const View = require('View'); const deprecatedPropType = require('deprecatedPropType'); const requireNativeComponent = require('requireNativeComponent'); const RCTModalHostView = requireNativeComponent('RCTModalHostView', null); /** * The Modal component is a simple way to present content above an enclosing view. * * _Note: If you need more control over how to present modals over the rest of your app, * then consider using a top-level Navigator._ * * ```javascript * import React, { Component } from 'react'; * import { Modal, Text, TouchableHighlight, View } from 'react-native'; * * class ModalExample extends Component { * * state = { * modalVisible: false, * } * * setModalVisible(visible) { * this.setState({modalVisible: visible}); * } * * render() { * return ( * <View style={{marginTop: 22}}> * <Modal * animationType={"slide"} * transparent={false} * visible={this.state.modalVisible} * onRequestClose={() => {alert("Modal has been closed.")}} * > * <View style={{marginTop: 22}}> * <View> * <Text>Hello World!</Text> * * <TouchableHighlight onPress={() => { * this.setModalVisible(!this.state.modalVisible) * }}> * <Text>Hide Modal</Text> * </TouchableHighlight> * * </View> * </View> * </Modal> * * <TouchableHighlight onPress={() => { * this.setModalVisible(true) * }}> * <Text>Show Modal</Text> * </TouchableHighlight> * * </View> * ); * } * } * ``` */ class Modal extends React.Component { static propTypes = { /** * The `animationType` prop controls how the modal animates. * * - `slide` slides in from the bottom * - `fade` fades into view * - `none` appears without an animation * * Default is set to `none`. */ animationType: PropTypes.oneOf(['none', 'slide', 'fade']), /** * The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background. */ transparent: PropTypes.bool, /** * The `hardwareAccelerated` prop controls whether to force hardware acceleration for the underlying window. * @platform android */ hardwareAccelerated: PropTypes.bool, /** * The `visible` prop determines whether your modal is visible. */ visible: PropTypes.bool, /** * The `onRequestClose` callback is called when the user taps the hardware back button. * @platform android */ onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func, /** * The `onShow` prop allows passing a function that will be called once the modal has been shown. */ onShow: PropTypes.func, animated: deprecatedPropType( PropTypes.bool, 'Use the `animationType` prop instead.' ), /** * The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations. * On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field. * @platform ios */ supportedOrientations: PropTypes.arrayOf(PropTypes.oneOf(['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right'])), /** * The `onOrientationChange` callback is called when the orientation changes while the modal is being displayed. * The orientation provided is only 'portrait' or 'landscape'. This callback is also called on initial render, regardless of the current orientation. * @platform ios */ onOrientationChange: PropTypes.func, }; static defaultProps = { visible: true, hardwareAccelerated: false, }; static contextTypes = { rootTag: PropTypes.number, }; render(): ?React.Element<any> { if (this.props.visible === false) { return null; } const containerStyles = { backgroundColor: this.props.transparent ? 'transparent' : 'white', }; let animationType = this.props.animationType; if (!animationType) { // manually setting default prop here to keep support for the deprecated 'animated' prop animationType = 'none'; if (this.props.animated) { animationType = 'slide'; } } const innerChildren = __DEV__ ? ( <AppContainer rootTag={this.context.rootTag}> {this.props.children} </AppContainer>) : this.props.children; return ( <RCTModalHostView animationType={animationType} transparent={this.props.transparent} hardwareAccelerated={this.props.hardwareAccelerated} onRequestClose={this.props.onRequestClose} onShow={this.props.onShow} style={styles.modal} onStartShouldSetResponder={this._shouldSetResponder} supportedOrientations={this.props.supportedOrientations} onOrientationChange={this.props.onOrientationChange} > <View style={[styles.container, containerStyles]}> {innerChildren} </View> </RCTModalHostView> ); } // We don't want any responder events bubbling out of the modal. _shouldSetResponder(): boolean { return true; } } const side = I18nManager.isRTL ? 'right' : 'left'; const styles = StyleSheet.create({ modal: { position: 'absolute', }, container: { position: 'absolute', [side] : 0, top: 0, } }); module.exports = Modal;
src/routes.js
wearhacks/stark-classroom
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import Intro from './components/Intro'; import CourseContainer from './containers/CourseContainer'; import NotFoundPage from './components/NotFoundPage.js'; export default ( <Route path="/" component={App}> <IndexRoute component={Intro} /> <Route path="course/web" component={CourseContainer}/> <Route path="*" component={NotFoundPage} /> </Route> );
components/Animation.js
andkhong/git-started
import React, { Component } from 'react'; import GitAnimation from './GitAnimation'; import StructureAnimation from './StructureAnimation'; export default class Animation extends Component { constructor(props) { super(props); this.showGit = this.showGit.bind(this); this.showStructure = this.showStructure.bind(this); } showGit() { this.props.setStructureAnimationVisibility(false); } showStructure() { this.props.setStructureAnimationVisibility(true); } buildStyles(structureAnimationVisible) { const styles = {}; styles.padder = { padding: '16px' }; styles.toggle = { float: 'right', border: '1px solid black', textAlign: 'center',position: 'absolute', right: '13px', 'z-index':0 }; styles.git = { borderBottom: '1px solid black', padding: '2px 2px 0px 2px' }; styles.structure = { padding: '2px 2px 0px 2px' }; if (structureAnimationVisible) { styles.git.backgroundColor = 'transparent'; styles.structure.backgroundColor = 'lightBlue'; } else { styles.git.backgroundColor = 'lightBlue'; styles.structure.backgroundColor = 'transparent'; } return styles; } // Images from https://www.iconfinder.com/icons/172515/folder_opened_icon#size=32 // and https://www.iconfinder.com/icons/83306/git_icon#size=32 render() { const selectedAnimation = this.props.structureAnimationVisible ? <StructureAnimation sidebarVisible={this.props.sidebarVisible} /> : <GitAnimation />; const styles = this.buildStyles(this.props.structureAnimationVisible); return ( <div id="Animation"> <div style={ styles.padder }> <div style={ styles.toggle }> <div style={ styles.git } onClick={this.showGit}> <img src="assets/git-icon.png" alt="Git view" height="12" width="12" /> </div> <div style={ styles.structure } onClick={this.showStructure}> <img src="assets/folder-icon.png" alt="Directory view" height="12" width="12" /> </div> </div> {selectedAnimation} </div> </div> ); } } Animation.propTypes = { padderStyle: React.PropTypes.object, setStructureAnimationVisibility: React.PropTypes.func, sidebarVisible: React.PropTypes.bool, structureAnimationVisible: React.PropTypes.bool, };
src/components/SimilarItems/SimilarItems.js
expdevelop/d812
import React from 'react' import { Carousel, InitCatalog } from 'components' import { ItemContainer } from 'containers' import s from './SimilarItems.sass' const SimilarItems = ({title, init, data}) => { const empty = !data || !data.length; return ( <div className={s.recommended}> {!empty && <h3 className={s.recommended__title}>{title}</h3>} {!empty && <Carousel className={s.recommended__content}> {data.map(item => ( <ItemContainer noSpecial data={item} key={item.id || item.link}/> ))} </Carousel>} {empty && <InitCatalog />} </div> ) }; export default SimilarItems;
src/components/layer/layer.js
hhj679/mybition-web
import { Modal, message } from 'antd' import React from 'react' import ReactDOM from 'react-dom' import classnames from 'classnames' import styles from './layer.less' const { info, success, error, warning, confirm } = Modal const layer = { prefixCls: 'ant-layer', index: 1, info, success, error, warning, confirm, } layer.close = (index) => new Promise((resolve, reject) => { const { prefixCls } = layer let div = document.getElementById(`${prefixCls}-reference-${index}`) if (index === undefined) { const references = document.querySelectorAll(`.${prefixCls}-reference`) div = references[references.length - 1] } if (!div) { message.error('关闭失败,未找到Dom') return } const unmountResult = ReactDOM.unmountComponentAtNode(div) if (unmountResult && div.parentNode) { div.parentNode.removeChild(div) resolve(index) } else { reject(index) } }) layer.closeAll = () => { const { prefixCls } = layer const references = document.querySelectorAll(`.${prefixCls}-reference`) let i = 0 while (i < references.length) { layer.close() i++ } } layer.open = (config) => { const props = Object.assign({}, config) const { content, ...modalProps } = props const { className, wrapClassName = '', verticalCenter = true } = modalProps const { prefixCls } = layer const index = layer.index++ let div = document.createElement('div') div.id = `${prefixCls}-reference-${index}` div.className = `${prefixCls}-reference` document.body.appendChild(div) ReactDOM.render( <Modal visible title="Title" transitionName="zoom" maskTransitionName="fade" onCancel={() => { layer.close(index) }} onOk={() => { layer.close(index) }} {...modalProps} wrapClassName={classnames({ [styles.verticalCenter]: verticalCenter, [wrapClassName]: true })} className={classnames(prefixCls, className, [`${prefixCls}-${index}`])} > <div className={`${prefixCls}-body-wrapper`} style={{ maxHeight: document.body.clientHeight - 256 }}> {content} </div> </Modal>, div) return index } export default layer
examples/counter/containers/App.js
AprilArcus/redux
import React, { Component } from 'react'; import CounterApp from './CounterApp'; import { createRedux } from 'redux'; import { Provider } from 'redux/react'; import * as stores from '../stores'; const redux = createRedux(stores); export default class App extends Component { render() { return ( <Provider redux={redux}> {() => <CounterApp />} </Provider> ); } }
docs/src/CodeExample.js
victorzhang17/react-bootstrap
import React from 'react'; export default class CodeExample extends React.Component { render() { return ( <pre className="cm-s-solarized cm-s-light"> <code> {this.props.codeText} </code> </pre> ); } componentDidMount() { if (CodeMirror === undefined) { return; } CodeMirror.runMode( this.props.codeText, this.props.mode, React.findDOMNode(this).children[0] ); } }
src/routes/Speeds/components/DashboardSpeedsView.js
liuyaoao/omnyiq-sc1-server-render
import React from 'react'; import axios from 'axios' import Helmet from 'react-helmet' import TimeSelectionTab from '../../../components/TimeSelectionTab' import ReactTabBar from '../../../components/ReactTabBar' import {getSpeedsDownloadChartData, getSpeedsUploadChartData, getSpeedsDL_ULChartData} from './SpeedsChartData' import {backImg,scoreState0,scoreState1,scoreState2,scoreState3} from '../../../components/ImagesAssets' import './DashboardSpeedsView.scss' var DashboardSpeedsView = React.createClass({ contextTypes: { router: React.PropTypes.object.isRequired }, getInitialState:function(){ return { scoreState0, scoreState1, scoreState2, scoreState3, deviceInfo:null, tabKeyList:['dl_ul','download','upload'], isNeedRender:{'dl_ul':true,'download':true,'upload':true}, downloadChartData:null, uploadChartData:null, uploadAndDownload:null } }, componentWillMount:function(){ this.props.setTabBarIsShow(true); this.props.setTabBarState('/Dashboard'); this.props.setCurTabIndex(0); //初始化数据 this.props.setCurTabKey(this.state.tabKeyList[0]); }, componentDidMount:function(){ let deviceInfo = JSON.parse(localStorage.getItem('deviceInfo')); this.setState({deviceInfo:deviceInfo}); let deviceListUrl = APPCONFING.deviceListUrl; let _this = this; let _id = deviceInfo.deviceId.substr(deviceInfo.deviceId.length-4); $('.navbarDiv .navTitleText .deviceInfoTitle').text(deviceInfo.deviceName+" "+deviceInfo.deviceN+" "+_id); this.getServerData(); }, getServerData:function(){ var _this = this; var spinner = new Spinner({zIndex:999}).spin($('.loadingSpinContainer')[0]); let tempUrl = APPCONFING.deviceListUrl+'/GetInternetSpeedsByIdServlet'; let CancelToken = axios.CancelToken; axios.get(tempUrl,{ cancelToken:new CancelToken((c) => { _this.axiosCancel = c; }) }).then(({data}) => { spinner.stop(); // console.log('DashboardSpeeds ajax--->',data); $('.loadingSpinContainer').remove(); _this.updateStateProps(data); }).catch((error) => {}); }, updateStateProps:function(data){ var _this = this,props = this.props; if(!data.value4 || data.value4.length<=0){ $('.noDataContainer').removeClass('hide'); return; } let dataList = data.value4; let avg_download = [];//下载速度 let avg_wan_Latency = [];//延迟 let avg_upload = [];//上传速度 let avg_isp_Avg_Download = [];//下载平均(灰色线条) let avg_isp_Avg_Upload = [];//上传平均(灰色线条) let dateList = []; let lastValue = data.value4[data.value4.length-1]; let newDownload = parseInt(lastValue.avg_download || 0); let newUpload = parseInt(lastValue.avg_wan_Latency || 0); let newLatency = parseInt(lastValue.avg_wan_Latency || 0); for(let v of data.value4){ if(v.avg_download == null){ avg_download.push(null); avg_wan_Latency.push(null); avg_upload.push(null); avg_isp_Avg_Download.push(null); avg_isp_Avg_Upload.push(null); dateList.push(null); }else{ avg_download.push(parseInt(v.avg_download)); avg_wan_Latency.push(parseInt(v.avg_wan_Latency)); avg_upload.push(parseInt(v.avg_upload)); avg_isp_Avg_Download.push(parseInt(v.avg_isp_Avg_Download)); avg_isp_Avg_Upload.push(parseInt(v.avg_isp_Avg_Upload)); let date = new Date(v.savetime); dateList.push(date.getHours()); } } let downloadChartData = getSpeedsDownloadChartData(dateList,avg_download,avg_wan_Latency,avg_isp_Avg_Download); let uploadChartData = getSpeedsUploadChartData(dateList,avg_upload,avg_isp_Avg_Upload,avg_wan_Latency); let uploadAndDownload = getSpeedsDL_ULChartData(dateList,avg_upload,avg_download,avg_isp_Avg_Download,avg_isp_Avg_Upload,avg_wan_Latency); _this.setState({newDownload:newDownload,newUpload:newUpload,newLatency:newLatency}); _this.setState({downloadChartData,uploadChartData,uploadAndDownload}); }, _changeCurrentTab:function(curTabIndex){ $('.speedsUl li p.current').removeClass('current'); $('.speedsUl li[data-index='+curTabIndex+'] p').addClass('current'); }, _onClickChartCall:function(e){ var data = zingchart.exec(e.id, 'getseriesvalues', {}); switch(e.id){ case "downloadChart": $('.download_Mbps').text(data[0][e.nodeindex]); $('.download_Latency').text(data[2][e.nodeindex]); break; case "uploadChart": $('.upload_Mbps').text(data[0][e.nodeindex]); $('.upload_Latency').text(data[2][e.nodeindex]); break; case "UploadAndDownload": $('.DLUL_download_Mbps').text(data[1][e.nodeindex]); $('.DLUL_upload_Mbps').text(data[0][e.nodeindex]); $('.DLUL_Latency').text(data[4][e.nodeindex]); break; default:break; } }, _showSpeedsDiv:function(e){ let that = $(e.currentTarget); if(that.find('p').hasClass('current')) { return; } let index = +that.data('index'); let tabKey = this.state.tabKeyList[index]; this.props.setCurTabIndex(index); this.props.setCurTabKey(tabKey); var timeNodeType = this.props.curTimeNodeTypes[tabKey]; this._updateState(index,timeNodeType); }, _updateState:function(index,timeNodeType){ }, shouldComponentUpdate:function(nextProps, nextState){ let _this = this; if(nextState.downloadChartData && nextState.isNeedRender['download']){ zingchart.render({id : 'downloadChart',data : nextState.downloadChartData,height: '100%',width: "98%"}); } if(nextState.uploadChartData && nextState.isNeedRender['upload']){ zingchart.render({id : 'uploadChart',data : nextState.uploadChartData,height: '100%',width: "98%"}); } if(nextState.uploadChartData&&nextState.downloadChartData && nextState.isNeedRender['dl_ul']){ zingchart.render({id : 'UploadAndDownload',data : nextState.uploadAndDownload,height: '100%',width: "98%"}); zingchart.node_click = function(e){ _this._onClickChartCall(e); } this.setState({'isNeedRender':{'download':false,'upload':false,'dl_ul':false}}); } return true; }, _onClickRightIcon:function(){ this.context.router.push('/Locations'); }, componentWillUnmount:function(){ this.axiosCancel && this.axiosCancel(); }, render:function(){ let iconImg = this.state.deviceInfo?this.state['scoreState'+this.state.deviceInfo.deviceScoreLevel]:''; return ( <div> <Helmet title='speeds'/> <div className='scrollBackground'></div> <div className='navbarDiv'> <div className='navbarLeft'> <a href='javascript:history.go(-1)'><img src={backImg} /></a> </div> <div className='navTitle navTitleText'> <p>Internet Speeds</p> <p className='deviceInfoTitle'></p> </div> <div className='navbarRight' onClick={this._onClickRightIcon}> <img src={iconImg} /> </div> </div> <div className='dashboardSpeedsContent contentFixed' style={{height:this.props.screenHeight-110}}> <ul className="speedsUl"> <li className='speedsDLUL' onClick={this._showSpeedsDiv} data-index='0'> <p className={this.props.curTabIndex == 0 ? 'current' : ''}>DL+UL</p> </li> <li className='speedsDownload' onClick={this._showSpeedsDiv} data-index='1'> <p className={this.props.curTabIndex == 1 ? 'current' : ''}>Download</p> </li> <li className='speedsUpload' onClick={this._showSpeedsDiv} data-index='2'> <p className={this.props.curTabIndex == 2 ? 'current' : ''}>Upload</p> </li> </ul> <div className='swiper-container' style={{height:this.props.screenHeight-140}}> <div className={this.props.curTabIndex == 0 ? 'speedsContentBox current' : 'speedsContentBox'} data-index='0'> <div className='noDataContainer hide' style={{position:'absolute'}}><p style={{top:'40%'}}>No Speeds Data!!</p></div> <div className='speedsUploadAndDownloadTitle'> <div> <p><span>DL:<span className='DLUL_download_Mbps'>{this.state.newDownload}</span> Mbps</span> <span>UL:<span className='DLUL_upload_Mbps'>{this.state.newUpload}</span> Mbps</span> </p> <p><span className='DLUL_Latency'>{this.state.newLatency}</span>ms latency</p> </div> </div> <div className='loadingSpinContainer' style={{marginTop:'40%'}}></div> <div id='UploadAndDownload' style={{marginTop:'65px',marginBottom:'70px',height:this.props.screenHeight-240}}></div> <div className='timeSelectTab_speeds'><TimeSelectionTab/></div> </div> <div className={this.props.curTabIndex == 1 ? 'speedsContentBox current' : 'speedsContentBox'} data-index='1'> <div className='noDataContainer hide' style={{position:'absolute'}}><p style={{top:'40%'}}>No Speeds Data!!</p></div> <div className='speedsDownloadTitle'> <div> <p><span className='download_Mbps'>{this.state.newDownload}</span> Mbps</p><p><span className='download_Latency'>{this.state.newLatency}</span>ms latency</p> </div> </div> <div id='downloadChart' style={{marginTop:'65px',marginBottom:'70px',height:this.props.screenHeight-240}}></div> <div className='timeSelectTab_speeds'><TimeSelectionTab/></div> </div> <div className={this.props.curTabIndex == 2 ? 'speedsContentBox current' : 'speedsContentBox'} data-index='2' > <div className='noDataContainer hide' style={{position:'absolute'}}><p style={{top:'40%'}}>No Speeds Data!!</p></div> <div className='speedsDownloadTitle'><div><p><span className='upload_Mbps'>{this.state.newUpload}</span> Mbps</p><p><span className='upload_Latency'>{this.state.newLatency}</span>ms latency</p></div></div> <div id='uploadChart' style={{marginTop:'65px',marginBottom:'70px',height:this.props.screenHeight-240}}></div> <div className='timeSelectTab_speeds'><TimeSelectionTab/></div> </div> </div> </div> <ReactTabBar setTabBarState={this.props.setTabBarState} setTabBarIsShow={this.props.setTabBarIsShow} setScreenHeight={this.props.setScreenHeight} tabBarState={this.props.tabBarState} tabBarIsShow={this.props.tabBarIsShow} /> </div> ); } }); module.exports = DashboardSpeedsView;
src/BurgerIcon.js
Lafinboy/react-burger-nav
import React from 'react' const BurgerIcon = React.createClass({ propTypes: { onClick: React.PropTypes.func.isRequired }, getInitialState() { return {hover: false} }, getLineStyle(index) { return { position: 'absolute', height: '20%', left: 0, right: 0, top: 20 * (index * 2) + '%', opacity: this.state.hover ? 0.6 : 1 } }, handleHover() { this.setState({hover: !this.state.hover}) }, render() { const buttonStyle = { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, margin: 0, padding: 0, border: 'none', fontSize: 14, color: 'transparent', background: 'transparent', outline: 'none', cursor: 'pointer' } return ( <div className="rbn-burger-button" style={{zIndex: 1}}> <span className="rbn-burger-bars" style={this.getLineStyle(0)}></span> <span className="rbn-burger-bars" style={this.getLineStyle(1)}></span> <span className="rbn-burger-bars" style={this.getLineStyle(2)}></span> <button onClick={this.props.onClick} onMouseEnter={this.handleHover} onMouseLeave={this.handleHover} style={buttonStyle}> Open Menu </button> </div> ) } }) export default BurgerIcon
jest-integration/baseTemplate/src/ClickCounter.js
bruderstein/unexpected-react
import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class ClickCounter extends Component { constructor() { super(); this.state = { count: 0 }; this.onClick = this.onClick.bind(this); } onClick() { this.setState({ count: this.state.count + 1 }); } render() { return ( <button className={'foo bar' + (this.props.className || '')} onClick={this.onClick}>Clicked {this.state.count} times</button> ); } } ClickCounter.propTypes = { className: PropTypes.string };
ajax/libs/react-instantsearch/4.3.0-beta.0/Connectors.js
joeyparrish/cdnjs
/*! ReactInstantSearch 4.3.0-beta.0 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Connectors = {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; /** * 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; } var _baseTimes = baseTimes; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** 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')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto$2 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto$2.toString; /** Built-in value references. */ var symToStringTag$1 = _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$2.call(value, symToStringTag$1), tag = value[symToStringTag$1]; try { value[symToStringTag$1] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag$1] = tag; } else { delete value[symToStringTag$1]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$3.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$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]'; var 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); } var _baseGetTag = baseGetTag; /** * 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'; } var isObjectLike_1 = isObjectLike; /** `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_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$1.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$1.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_1(value) && hasOwnProperty$1.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * 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; var isArray_1 = isArray; /** * 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; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == '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_1; module.exports = isBuffer; }); /** 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); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 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$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]'; var arrayTag = '[object Array]'; var boolTag = '[object Boolean]'; var dateTag = '[object Date]'; var errorTag = '[object Error]'; var funcTag = '[object Function]'; var mapTag = '[object Map]'; var numberTag = '[object Number]'; var objectTag = '[object Object]'; var regexpTag = '[object RegExp]'; var setTag = '[object Set]'; var stringTag = '[object String]'; var weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]'; var dataViewTag = '[object DataView]'; var float32Tag = '[object Float32Array]'; var float64Tag = '[object Float64Array]'; var int8Tag = '[object Int8Array]'; var int16Tag = '[object Int16Array]'; var int32Tag = '[object Int32Array]'; var uint8Tag = '[object Uint8Array]'; var uint8ClampedTag = '[object Uint8ClampedArray]'; var uint16Tag = '[object Uint16Array]'; var 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$1] = 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_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * 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); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == '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; }); /* 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; var isTypedArray_1 = isTypedArray; /** 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_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(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; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$5 = 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$5; return value === proto; } var _isPrototype = isPrototype; /** * 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)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$4.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$3.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * 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'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]'; var funcTag$1 = '[object Function]'; var genTag = '[object GeneratorFunction]'; var 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_1(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$1 || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** * 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_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * 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_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** 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); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto$1 = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.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$1.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * 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; var objectProto$6 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$6.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty$4).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_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * 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]; } var _getValue = getValue; /** * 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; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * 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; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$7.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$5.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$8.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$6.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__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$1 : value; return this; } var _hashSet = hashSet; /** * 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; var _Hash = Hash; /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * 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); } var eq_1 = eq; /** * 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_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** 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; } var _listCacheDelete = listCacheDelete; /** * 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]; } var _listCacheGet = listCacheGet; /** * 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; } var _listCacheHas = listCacheHas; /** * 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; } var _listCacheSet = listCacheSet; /** * 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; var _ListCache = ListCache; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /** * 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 }; } var _mapCacheClear = mapCacheClear; /** * 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); } var _isKeyable = isKeyable; /** * 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; } var _getMapData = getMapData; /** * 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; } var _mapCacheDelete = mapCacheDelete; /** * 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); } var _mapCacheGet = mapCacheGet; /** * 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); } var _mapCacheHas = mapCacheHas; /** * 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; } var _mapCacheSet = mapCacheSet; /** * 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; var _MapCache = MapCache; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__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$2); return this; } var _setCacheAdd = setCacheAdd; /** * 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); } var _setCacheHas = setCacheHas; /** * * 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; var _SetCache = SetCache; /** * 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; } var _baseFindIndex = baseFindIndex; /** * 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; } var _baseIsNaN = baseIsNaN; /** * 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; } var _strictIndexOf = strictIndexOf; /** * 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); } var _baseIndexOf = baseIndexOf; /** * 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; } var _arrayIncludes = arrayIncludes; /** * 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; } var _arrayIncludesWith = arrayIncludesWith; /** * 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; } var _arrayMap = arrayMap; /** * 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); } var _cacheHas = cacheHas; /** 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; } var _baseDifference = baseDifference; /** * 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; } var _arrayPush = arrayPush; /** 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_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * 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; } var _baseFlatten = baseFlatten; /** * 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; } var identity_1 = identity; /** * 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); } var _apply = apply; /* 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); }; } var _overRest = overRest; /** * 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; }; } var constant_1 = constant; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty = defineProperty; /** * 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_1 : function(func, string) { return _defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800; var 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); }; } var _shortOut = shortOut; /** * 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); var _setToString = setToString; /** * 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_1), func + ''); } var _baseRest = baseRest; /** * 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_1(value) && isArrayLike_1(value); } var isArrayLikeObject_1 = isArrayLikeObject; /** * 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_1(array) ? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true)) : []; }); var difference_1 = difference; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * 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; } var _stackDelete = stackDelete; /** * 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); } var _stackGet = stackGet; /** * 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); } var _stackHas = stackHas; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE$1 = 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 - 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; } var _stackSet = stackSet; /** * 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; var _Stack = Stack; /** * 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; } var _arrayEach = arrayEach; /** * 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; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$9.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$7.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * 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; } var _copyObject = copyObject; /** * 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_1(source), object); } var _baseAssign = baseAssign; /** * 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; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$10 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$10.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_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$8.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * 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$1(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn$1; /** * 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_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == '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; }); /** * 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; } var _copyArray = copyArray; /** * 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; } var _arrayFilter = arrayFilter; /** * 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 []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$11 = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$11.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_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable$1.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * 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); } var _copySymbols = copySymbols; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = 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$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * 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); } var _copySymbolsIn = copySymbolsIn; /** * 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_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * 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_1, _getSymbols); } var _getAllKeys = getAllKeys; /** * 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_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag$2 = '[object Map]'; var objectTag$2 = '[object Object]'; var promiseTag = '[object Promise]'; var setTag$2 = '[object Set]'; var weakMapTag$2 = '[object WeakMap]'; var dataViewTag$2 = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = _toSource(_DataView); var mapCtorString = _toSource(_Map); var promiseCtorString = _toSource(_Promise); var setCtorString = _toSource(_Set); var 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$2) || (_Map && getTag(new _Map) != mapTag$2) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag$2) || (_WeakMap && getTag(new _WeakMap) != weakMapTag$2)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag$2 ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$2; case mapCtorString: return mapTag$2; case promiseCtorString: return promiseTag; case setCtorString: return setTag$2; case weakMapCtorString: return weakMapTag$2; } } return result; }; } var _getTag = getTag; /** Used for built-in method references. */ var objectProto$12 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$12.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$9.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * 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; } var _cloneArrayBuffer = cloneArrayBuffer; /** * 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); } var _cloneDataView = cloneDataView; /** * 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; } var _addMapEntry = addMapEntry; /** * 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; } var _arrayReduce = arrayReduce; /** * 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; } var _mapToArray = mapToArray; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$2 = 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$2) : _mapToArray(map); return _arrayReduce(array, _addMapEntry, new map.constructor); } var _cloneMap = cloneMap; /** 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; } var _cloneRegExp = cloneRegExp; /** * 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; } var _addSetEntry = addSetEntry; /** * 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; } var _setToArray = setToArray; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$3 = 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$3) : _setToArray(set); return _arrayReduce(array, _addSetEntry, new set.constructor); } var _cloneSet = cloneSet; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined; var 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)) : {}; } var _cloneSymbol = cloneSymbol; /** * 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); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$2 = '[object Boolean]'; var dateTag$2 = '[object Date]'; var mapTag$3 = '[object Map]'; var numberTag$2 = '[object Number]'; var regexpTag$2 = '[object RegExp]'; var setTag$3 = '[object Set]'; var stringTag$2 = '[object String]'; var symbolTag$1 = '[object Symbol]'; var arrayBufferTag$2 = '[object ArrayBuffer]'; var dataViewTag$3 = '[object DataView]'; var float32Tag$2 = '[object Float32Array]'; var float64Tag$2 = '[object Float64Array]'; var int8Tag$2 = '[object Int8Array]'; var int16Tag$2 = '[object Int16Array]'; var int32Tag$2 = '[object Int32Array]'; var uint8Tag$2 = '[object Uint8Array]'; var uint8ClampedTag$2 = '[object Uint8ClampedArray]'; var uint16Tag$2 = '[object Uint16Array]'; var uint32Tag$2 = '[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$2: return _cloneArrayBuffer(object); case boolTag$2: case dateTag$2: return new Ctor(+object); case dataViewTag$3: return _cloneDataView(object, isDeep); case float32Tag$2: case float64Tag$2: case int8Tag$2: case int16Tag$2: case int32Tag$2: case uint8Tag$2: case uint8ClampedTag$2: case uint16Tag$2: case uint32Tag$2: return _cloneTypedArray(object, isDeep); case mapTag$3: return _cloneMap(object, isDeep, cloneFunc); case numberTag$2: case stringTag$2: return new Ctor(object); case regexpTag$2: return _cloneRegExp(object); case setTag$3: return _cloneSet(object, isDeep, cloneFunc); case symbolTag$1: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** 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_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * 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)) : {}; } var _initCloneObject = initCloneObject; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1; var CLONE_FLAT_FLAG$1 = 2; var CLONE_SYMBOLS_FLAG$1 = 4; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]'; var arrayTag$1 = '[object Array]'; var boolTag$1 = '[object Boolean]'; var dateTag$1 = '[object Date]'; var errorTag$1 = '[object Error]'; var funcTag$2 = '[object Function]'; var genTag$1 = '[object GeneratorFunction]'; var mapTag$1 = '[object Map]'; var numberTag$1 = '[object Number]'; var objectTag$1 = '[object Object]'; var regexpTag$1 = '[object RegExp]'; var setTag$1 = '[object Set]'; var stringTag$1 = '[object String]'; var symbolTag = '[object Symbol]'; var weakMapTag$1 = '[object WeakMap]'; var arrayBufferTag$1 = '[object ArrayBuffer]'; var dataViewTag$1 = '[object DataView]'; var float32Tag$1 = '[object Float32Array]'; var float64Tag$1 = '[object Float64Array]'; var int8Tag$1 = '[object Int8Array]'; var int16Tag$1 = '[object Int16Array]'; var int32Tag$1 = '[object Int32Array]'; var uint8Tag$1 = '[object Uint8Array]'; var uint8ClampedTag$1 = '[object Uint8ClampedArray]'; var uint16Tag$1 = '[object Uint16Array]'; var uint32Tag$1 = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] = cloneableTags[boolTag$1] = cloneableTags[dateTag$1] = cloneableTags[float32Tag$1] = cloneableTags[float64Tag$1] = cloneableTags[int8Tag$1] = cloneableTags[int16Tag$1] = cloneableTags[int32Tag$1] = cloneableTags[mapTag$1] = cloneableTags[numberTag$1] = cloneableTags[objectTag$1] = cloneableTags[regexpTag$1] = cloneableTags[setTag$1] = cloneableTags[stringTag$1] = cloneableTags[symbolTag] = cloneableTags[uint8Tag$1] = cloneableTags[uint8ClampedTag$1] = cloneableTags[uint16Tag$1] = cloneableTags[uint32Tag$1] = true; cloneableTags[errorTag$1] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$1] = 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$1, isFlat = bitmask & CLONE_FLAT_FLAG$1, isFull = bitmask & CLONE_SYMBOLS_FLAG$1; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$1 || tag == argsTag$2 || (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_1); 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; } var _baseClone = baseClone; /** `Object#toString` result references. */ var symbolTag$2 = '[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_1(value) && _baseGetTag(value) == symbolTag$2); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; var 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_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** 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; var memoize_1 = memoize; /** 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_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var reLeadingDot = /^\./; var 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; }); var _stringToPath = stringToPath; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined; var symbolToString = symbolProto$1 ? symbolProto$1.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_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * 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); } var toString_1 = toString; /** * 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_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** * 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; } var last_1 = last; /** Used as references for various `Number` constants. */ var INFINITY$1 = 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_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * 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; } var _baseGet = baseGet; /** * 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; } var _baseSlice = baseSlice; /** * 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)); } var _parent = parent; /** * 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_1(path))]; } var _baseUnset = baseUnset; /** `Object#toString` result references. */ var objectTag$3 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype; var objectProto$13 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$10 = objectProto$13.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.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_1(value) || _baseGetTag(value) != objectTag$3) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$10.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** * 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_1(value) ? undefined : value; } var _customOmitClone = customOmitClone; /** * 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) : []; } var flatten_1 = flatten; /** * 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_1), func + ''); } var _flatRest = flatRest; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; var CLONE_FLAT_FLAG = 2; var 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; }); var omit_1 = omit; var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } 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); } function nextTick(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); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd() { return '/'; } function chdir(dir) { throw new Error('process.chdir is not supported'); } function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { return new Date().getTime(); }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp) { var clocktime = performanceNow.call(performance) * 1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor(clocktime % 1 * 1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds < 0) { seconds--; nanoseconds += 1e9; } } return [seconds, nanoseconds]; } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; /** * 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; } var _arraySome = arraySome; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1; var 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$1, 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; } var _equalArrays = equalArrays; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; var COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag$3 = '[object Boolean]'; var dateTag$3 = '[object Date]'; var errorTag$2 = '[object Error]'; var mapTag$4 = '[object Map]'; var numberTag$3 = '[object Number]'; var regexpTag$3 = '[object RegExp]'; var setTag$4 = '[object Set]'; var stringTag$3 = '[object String]'; var symbolTag$3 = '[object Symbol]'; var arrayBufferTag$3 = '[object ArrayBuffer]'; var dataViewTag$4 = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined; var symbolValueOf$1 = symbolProto$2 ? symbolProto$2.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$4: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag$3: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag$3: case dateTag$3: case numberTag$3: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag$2: return object.name == other.name && object.message == other.message; case regexpTag$3: case stringTag$3: // 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$4: var convert = _mapToArray; case setTag$4: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2; 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$1; // 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$3: if (symbolValueOf$1) { return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); } } return false; } var _equalByTag = equalByTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** Used for built-in method references. */ var objectProto$15 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$12 = objectProto$15.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$3, 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$12.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; } var _equalObjects = equalObjects; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]'; var arrayTag$2 = '[object Array]'; var objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var objectProto$14 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$11 = objectProto$14.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_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$2 : _getTag(object), othTag = othIsArr ? arrayTag$2 : _getTag(other); objTag = objTag == argsTag$3 ? objectTag$4 : objTag; othTag = othTag == argsTag$3 ? objectTag$4 : othTag; var objIsObj = objTag == objectTag$4, othIsObj = othTag == objectTag$4, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(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$11.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$11.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); } var _baseIsEqualDeep = baseIsEqualDeep; /** * 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_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** * 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); } var isEqual_1 = isEqual; /** Used for built-in method references. */ var objectProto$16 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$13 = objectProto$16.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$13.call(object, key); } var _baseHas = baseHas; /** * 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_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * 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); } var has_1 = has; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ 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; }; var emptyFunction_1 = emptyFunction; function invariant(condition, format, a, b, c, d, e, f) { 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; } } var invariant_1 = invariant; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty$14 = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty$14.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // It is still safe when called from React. return; } invariant_1( 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, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = factoryWithThrowingShims(); } }); /** `Object#toString` result references. */ var mapTag$5 = '[object Map]'; var setTag$5 = '[object Set]'; /** Used for built-in method references. */ var objectProto$17 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$15 = objectProto$17.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_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$5 || tag == setTag$5) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$15.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; // 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 getDisplayName(Component$$1) { return Component$$1.displayName || Component$$1.name || 'UnknownComponent'; } function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; } var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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; }; }(); var defineProperty$2 = function (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 _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 inherits = function (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; }; var possibleConstructorReturn = function (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; }; 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 toConsumableArray = function (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); } }; /** * @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 = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(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; 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 })) }); } }); if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget(_this); } return _this; } createClass(Connector, [{ key: 'getMetadata', value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: 'transitionState', value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { 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 (!isEqual_1(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(removeEmptyKey(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !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) { _this2.searchForFacetValues(facetName, query); } } : {}; return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.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; }; } /** * 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$1(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get$1; 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 { /* If we have a multi index page with shared widgets we should also reset their page to 1 see: https://github.com/algolia/react-instantsearch/issues/310 */ if (searchState.indices) { Object.keys(searchState.indices).forEach(function (targetedIndex) { searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace); }); } 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 = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, defineProperty$2({}, 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 _babelHelpers$extends3; var index = getIndex(context); var page = resetPage ? { page: 1 } : undefined; var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], (_babelHelpers$extends3 = {}, defineProperty$2(_babelHelpers$extends3, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), defineProperty$2(_babelHelpers$extends3, 'page', 1), _babelHelpers$extends3)))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends(defineProperty$2({}, namespace, nextRefinement), page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, defineProperty$2({}, 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] && has_1(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && has_1(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndex(context) && has_1(searchState, id); if (refinements) { var currentRefinement = void 0; if (hasMultipleIndex(context)) { currentRefinement = namespace ? get_1(searchState.indices['' + index][namespace], attributeName) : get_1(searchState.indices[index], id); } else { currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(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$2({}, index, _extends({}, searchState.indices[index], defineProperty$2({}, namespace, omit_1(searchState.indices[index][namespace], '' + attributeName))))) }) : omit_1(searchState, 'indices.' + index + '.' + id); } else { return namespace ? _extends({}, searchState, defineProperty$2({}, namespace, omit_1(searchState[namespace], '' + attributeName))) : omit_1(searchState, '' + id); } } function getId() { return 'configure'; } var connectConfigure = createConnector({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = omit_1(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = omit_1(props, 'children'); var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : []; this._props = props; var nextValue = defineProperty$2({}, id, _extends({}, omit_1(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var index = getIndex(this.context); var subState = 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$2({}, id, configureState); return refineValue(searchState, nextValue, this.context); } }); /** * 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 */ var connectCurrentRefinements = createConnector({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: propTypes.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); } }); /* 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; } var _baseIntersection = baseIntersection; /** * 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_1(value) ? value : []; } var _castArrayLikeObject = castArrayLikeObject; /** * 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) : []; }); var intersection_1 = intersection; /** * 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; }; } var _createBaseFor = createBaseFor; /** * 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(); var _baseFor = baseFor; /** * 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_1); } var _baseForOwn = baseForOwn; /** * 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_1; } var _castFunction = castFunction; /** * 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)); } var forOwn_1 = forOwn; /** * 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_1(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; }; } var _createBaseEach = createBaseEach; /** * 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); var _baseEach = baseEach; /** * 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_1(collection) ? _arrayEach : _baseEach; return func(collection, _castFunction(iteratee)); } var forEach_1 = forEach; /** * 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; } var _baseFilter = baseFilter; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1; var COMPARE_UNORDERED_FLAG$2 = 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$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * 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_1(value); } var _isStrictComparable = isStrictComparable; /** * 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_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * 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))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * 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); }; } var _baseMatches = baseMatches; /** * 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); } var _baseHasIn = baseHasIn; /** * 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); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1; var COMPARE_UNORDERED_FLAG$3 = 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_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * 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]; }; } var _baseProperty = baseProperty; /** * 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); }; } var _basePropertyDeep = basePropertyDeep; /** * 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); } var property_1 = property; /** * 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_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * 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_1(collection) ? _arrayFilter : _baseFilter; return func(collection, _baseIteratee(predicate, 3)); } var filter_1 = filter; /** * 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_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * 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_1(collection) ? _arrayMap : _baseMap; return func(collection, _baseIteratee(iteratee, 3)); } var map_1 = map; /** * 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; } var _baseReduce = baseReduce; /** * 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_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3; return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach); } var reduce_1 = reduce; /** 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_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(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); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0; var 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_1(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * 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_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = 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_1(fromIndex); if (index < 0) { index = nativeMax$1(length + index, 0); } return _baseIndexOf(array, value, index); } var indexOf_1 = indexOf; /** `Object#toString` result references. */ var numberTag$4 = '[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_1(value) && _baseGetTag(value) == numberTag$4); } var isNumber_1 = isNumber; /** * 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$1(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_1(value) && value != +value; } var _isNaN = isNaN$1; /** * 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; } var isUndefined_1 = isUndefined; /** `Object#toString` result references. */ var stringTag$4 = '[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_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4); } var isString_1 = isString; /** * 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_1(collection)) { var iteratee = _baseIteratee(predicate, 3); collection = keys_1(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; }; } var _createFind = createFind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$2 = 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_1(fromIndex); if (index < 0) { index = nativeMax$2(length + index, 0); } return _baseFindIndex(array, _baseIteratee(predicate, 3), index); } var findIndex_1 = findIndex; /** * 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_1); var find_1 = find; /** * 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); } var _castSlice = castSlice; /** * 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; } var _charsEndIndex = charsEndIndex; /** * 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; } var _charsStartIndex = charsStartIndex; /** * 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(''); } var _asciiToArray = asciiToArray; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff'; var rsComboMarksRange = '\\u0300-\\u036f'; var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; var rsComboSymbolsRange = '\\u20d0-\\u20ff'; var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; var 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); } var _hasUnicode = hasUnicode; /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff'; var rsComboMarksRange$1 = '\\u0300-\\u036f'; var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; var rsVarRange$1 = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']'; var rsCombo = '[' + rsComboRange$1 + ']'; var rsFitz = '\\ud83c[\\udffb-\\udfff]'; var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; var rsNonAstral = '[^' + rsAstralRange$1 + ']'; var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; var rsZWJ$1 = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?'; var rsOptVar = '[' + rsVarRange$1 + ']?'; var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; var rsSeq = rsOptVar + reOptMod + rsOptJoin; var 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) || []; } var _unicodeToArray = unicodeToArray; /** * 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); } var _stringToArray = stringToArray; /** Used to match leading and trailing whitespace. */ var reTrim$1 = /^\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_1(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim$1, ''); } 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(''); } var trim_1 = trim; /** * 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_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** * 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; }); } var _createAssigner = createAssigner; /** * 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_1(source), object, customizer); }); var assignInWith_1 = assignInWith; /** Used for built-in method references. */ var objectProto$18 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$16 = objectProto$18.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_1(objValue, objectProto$18[key]) && !hasOwnProperty$16.call(object, key))) { return srcValue; } return objValue; } var _customDefaultsAssignIn = customDefaultsAssignIn; /** * 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$1 = _baseRest(function(args) { args.push(undefined, _customDefaultsAssignIn); return _apply(assignInWith_1, undefined, args); }); var defaults_1 = defaults$1; /** * 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_1(object[key], value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignMergeValue = assignMergeValue; /** * 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_1(value)); } var toPlainObject_1 = toPlainObject; /** * 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_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_1(objValue)) { newValue = objValue; } else if (isArrayLikeObject_1(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_1(srcValue) || isArguments_1(srcValue)) { newValue = objValue; if (isArguments_1(objValue)) { newValue = toPlainObject_1(objValue); } else if (!isObject_1(objValue) || (srcIndex && isFunction_1(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); } var _baseMergeDeep = baseMergeDeep; /** * 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_1(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_1); } var _baseMerge = baseMerge; /** * 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); }); var merge_1 = merge; function valToNumber(v) { if (isNumber_1(v)) { return v; } else if (isString_1(v)) { return parseFloat(v); } else if (isArray_1(v)) { return map_1(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } var valToNumber_1 = valToNumber; function filterState(state, filters) { var partialState = {}; var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf_1(attributes, '*') === -1) { forEach_1(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_1(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty_1(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty_1(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty_1(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter_1( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach_1( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } var filterState_1 = filterState; /** * 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 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_1({}, 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_1(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_1(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_1(attribute)) { return {}; } else if (isString_1(attribute)) { return omit_1(refinementList, attribute); } else if (isFunction_1(attribute)) { return reduce_1(refinementList, function(memo, values, key) { var facetList = filter_1(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty_1(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 = indexOf_1; var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined_1(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * 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_1(array, function(currentValue) { return isEqual_1(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_1(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_1(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_1(numberKeys, function(k) { var value = partialState[k]; if (isString_1(value)) { var parsedValue = parseFloat(value); numbers[k] = _isNaN(parsedValue) ? value : parsedValue; } }); if (partialState.numericRefinements) { var numericRefinements = {}; forEach_1(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach_1(operators, function(values, operator) { var parsedValues = map_1(values, function(v) { if (isArray_1(v)) { return map_1(v, function(vPrime) { if (isString_1(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString_1(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge_1({}, 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_1(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_1(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_1(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_1(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge_1({}, this.numericRefinements); mod[attribute] = merge_1({}, 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_1(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_1(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_1(attribute)) { return {}; } else if (isString_1(attribute)) { return omit_1(this.numericRefinements, attribute); } else if (isFunction_1(attribute)) { return reduce_1(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach_1(operators, function(values, operator) { var outValues = []; forEach_1(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty_1(outValues)) operatorList[operator] = outValues; }); if (!isEmpty_1(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_1(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_1(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_1(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_1(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_1({}, 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_1({}, 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_1({}, 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_1(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_1(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_1(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_1(value) && isUndefined_1(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined_1(this.numericRefinements[attribute][operator]); if (isUndefined_1(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = !isUndefined_1( 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_1(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_1( keys_1(this.numericRefinements), this.disjunctiveFacets ); return keys_1(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_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map_1(this.hierarchicalFacets, 'name'), keys_1(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter_1(this.disjunctiveFacets, function(f) { return indexOf_1(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn_1(this, function(paramValue, paramName) { if (indexOf_1(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_1(params); forEach_1(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_1(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_1( 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_1(path, trim_1); } }; /** * 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. */ var SearchParameters_1 = SearchParameters; /** * 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; } var compact_1 = compact; /** * 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; } var _baseSum = baseSum; /** * 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; } var sumBy_1 = sumBy; /** * 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]; }); } var _baseValues = baseValues; /** * 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_1(object)); } var values_1 = values; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$3 = 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_1(collection) ? collection : values_1(collection); fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$3(length + fromIndex, 0); } return isString_1(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && _baseIndexOf(collection, value, fromIndex) > -1); } var includes_1 = includes; /** * 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; } var _baseSortBy = baseSortBy; /** * 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_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(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; } var _compareAscending = compareAscending; /** * 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; } var _compareMultiple = compareMultiple; /** * 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_1], _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); }); } var _baseOrderBy = baseOrderBy; /** * 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_1(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray_1(orders)) { orders = orders == null ? [] : [orders]; } return _baseOrderBy(collection, iteratees, orders); } var orderBy_1 = orderBy; /** Used to store function metadata. */ var metaMap = _WeakMap && new _WeakMap; var _metaMap = metaMap; /** * 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_1 : function(func, data) { _metaMap.set(func, data); return func; }; var _baseSetData = baseSetData; /** * 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_1(result) ? result : thisBinding; }; } var _createCtor = createCtor; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$1 = 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$1, Ctor = _createCtor(func); function wrapper() { var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } var _createBind = createBind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$5 = 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$5(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; } var _composeArgs = composeArgs; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$6 = 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$6(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; } var _composeArgsRight = composeArgsRight; /** * 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; } var _countHolders = countHolders; /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } var _baseLodash = baseLodash; /** 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; var _LazyWrapper = LazyWrapper; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop$1() { // No operation performed. } var noop_1 = noop$1; /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !_metaMap ? noop_1 : function(func) { return _metaMap.get(func); }; var _getData = getData; /** Used to lookup unminified function names. */ var realNames = {}; var _realNames = realNames; /** Used for built-in method references. */ var objectProto$19 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$17 = objectProto$19.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$17.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; } var _getFuncName = getFuncName; /** * 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; var _LodashWrapper = LodashWrapper; /** * 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; } var _wrapperClone = wrapperClone; /** Used for built-in method references. */ var objectProto$20 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$18 = objectProto$20.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_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) { if (value instanceof _LodashWrapper) { return value; } if (hasOwnProperty$18.call(value, '__wrapped__')) { return _wrapperClone(value); } } return new _LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = _baseLodash.prototype; lodash.prototype.constructor = lodash; var wrapperLodash = lodash; /** * 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 = wrapperLodash[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]; } var _isLaziable = isLaziable; /** * 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); var _setData = setData; /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/; var 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) : []; } var _getWrapDetails = getWrapDetails; /** 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'); } var _insertWrapDetails = insertWrapDetails; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$4 = 1; var WRAP_BIND_KEY_FLAG$3 = 2; var WRAP_CURRY_FLAG$3 = 8; var WRAP_CURRY_RIGHT_FLAG$2 = 16; var WRAP_PARTIAL_FLAG$3 = 32; var WRAP_PARTIAL_RIGHT_FLAG$2 = 64; var WRAP_ARY_FLAG$1 = 128; var WRAP_REARG_FLAG = 256; var WRAP_FLIP_FLAG$1 = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG$1], ['bind', WRAP_BIND_FLAG$4], ['bindKey', WRAP_BIND_KEY_FLAG$3], ['curry', WRAP_CURRY_FLAG$3], ['curryRight', WRAP_CURRY_RIGHT_FLAG$2], ['flip', WRAP_FLIP_FLAG$1], ['partial', WRAP_PARTIAL_FLAG$3], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2], ['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(); } var _updateWrapDetails = updateWrapDetails; /** * 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))); } var _setWrapToString = setWrapToString; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$3 = 1; var WRAP_BIND_KEY_FLAG$2 = 2; var WRAP_CURRY_BOUND_FLAG = 4; var WRAP_CURRY_FLAG$2 = 8; var WRAP_PARTIAL_FLAG$2 = 32; var WRAP_PARTIAL_RIGHT_FLAG$1 = 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$2, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$2 : WRAP_PARTIAL_RIGHT_FLAG$1); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$2); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG$3 | WRAP_BIND_KEY_FLAG$2); } 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); } var _createRecurry = createRecurry; /** * 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; } var _getHolder = getHolder; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$1 = 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$1(indexes.length, arrLength), oldArray = _copyArray(array); while (length--) { var index = indexes[length]; array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } var _reorder = reorder; /** 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; } var _replaceHolders = replaceHolders; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$2 = 1; var WRAP_BIND_KEY_FLAG$1 = 2; var WRAP_CURRY_FLAG$1 = 8; var WRAP_CURRY_RIGHT_FLAG$1 = 16; var WRAP_ARY_FLAG = 128; var 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$2, isBindKey = bitmask & WRAP_BIND_KEY_FLAG$1, isCurried = bitmask & (WRAP_CURRY_FLAG$1 | WRAP_CURRY_RIGHT_FLAG$1), 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; } var _createHybrid = createHybrid; /** * 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; } var _createCurry = createCurry; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$5 = 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$5, 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; } var _createPartial = createPartial; /** Used as the internal argument placeholder. */ var PLACEHOLDER$1 = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$6 = 1; var WRAP_BIND_KEY_FLAG$4 = 2; var WRAP_CURRY_BOUND_FLAG$1 = 4; var WRAP_CURRY_FLAG$4 = 8; var WRAP_ARY_FLAG$2 = 128; var WRAP_REARG_FLAG$1 = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$2 = 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$6 | WRAP_BIND_KEY_FLAG$4 | WRAP_ARY_FLAG$2); var isCombo = ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$4)) || ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$4)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG$6) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG$6 ? 0 : WRAP_CURRY_BOUND_FLAG$1; } // 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$1) : 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$1) : 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$2) { data[8] = data[8] == null ? source[8] : nativeMin$2(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; } var _mergeData = mergeData; /** Error message constants. */ var FUNC_ERROR_TEXT$1 = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; var WRAP_BIND_KEY_FLAG = 2; var WRAP_CURRY_FLAG = 8; var WRAP_CURRY_RIGHT_FLAG = 16; var WRAP_PARTIAL_FLAG$1 = 32; var WRAP_PARTIAL_RIGHT_FLAG = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$4 = 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$1); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG$1 | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax$4(toInteger_1(ary), 0); arity = arity === undefined ? arity : toInteger_1(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$4(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$1 || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG$1)) && !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); } var _createWrap = createWrap; /** 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 = {}; var partial_1 = partial; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG$3 = 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$3, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; var partialRight_1 = partialRight; /** * 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; } var _baseClamp = baseClamp; /** * 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_1(string); position = position == null ? 0 : _baseClamp(toInteger_1(position), 0, string.length); target = _baseToString(target); return string.slice(position, position + target.length) == target; } var startsWith_1 = startsWith; /** * 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 */ var formatSort = function formatSort(sortBy, defaults) { return reduce_1(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find_1(defaults, function(predicate) { return startsWith_1(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /** * 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_1(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_1(objValue) ? objValue : (_isIndex(path[index + 1]) ? [] : {}); } } _assignValue(nested, key, newValue); nested = nested[key]; } return object; } var _baseSet = baseSet; /** * 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; } var _basePickBy = basePickBy; /** * 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]); }); } var pickBy_1 = pickBy; var generateHierarchicalTree_1 = generateTrees; 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 = formatSort(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_1(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_1(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_1( map_1( pickBy_1(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_1(last_1(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /** * @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} name 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_1(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_1( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes_1(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_1(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; /** * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/). * @member {object[]} */ this.userData = mainSubResponse.userData; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map_1(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_1(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_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf_1(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_1(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach_1(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach_1(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(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_1( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults_1({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf_1(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_1(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_1(result.facets, function(facetResults, dfacet) { var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(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_1( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach_1(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach_1(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_1(this.hierarchicalFacets, generateHierarchicalTree_1(state)); this.facets = compact_1(this.facets); this.disjunctiveFacets = compact_1(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_1(this.facets, predicate) || find_1(this.disjunctiveFacets, predicate) || find_1(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_1(results.facets, predicate); if (!facet) return []; return map_1(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_1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map_1(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find_1(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_1(node.data, partial_1(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge_1({}, 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_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (isArray_1(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (isArray_1(facetValues)) { return orderBy_1(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues); } else if (isFunction_1(options.sortBy)) { if (isArray_1(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial_1(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_1(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_1(state.facetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach_1(state.facetsExcludes, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach_1(state.numericRefinements, function(operators, attributeName) { forEach_1(operators, function(values, operator) { forEach_1(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach_1(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var count = get_1(facet, 'data[' + name + ']'); var exhaustive = get_1(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find_1(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_1(facet.data, {name: splitted[i]}); } var count = get_1(facet, 'count'); var exhaustive = get_1(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } var SearchResults_1 = SearchResults; var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; var inherits_browser = createCommonjsModule(function (module) { 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; }; } }); var util = createCommonjsModule(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. 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(commonjsGlobal.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 = isBufferBrowser; 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 = inherits_browser; 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); } }); var util_1 = util.format; var util_2 = util.deprecate; var util_3 = util.debuglog; var util_4 = util.inspect; var util_5 = util.isArray; var util_6 = util.isBoolean; var util_7 = util.isNull; var util_8 = util.isNullOrUndefined; var util_9 = util.isNumber; var util_10 = util.isString; var util_11 = util.isSymbol; var util_12 = util.isUndefined; var util_13 = util.isRegExp; var util_14 = util.isObject; var util_15 = util.isDate; var util_16 = util.isError; var util_17 = util.isFunction; var util_18 = util.isPrimitive; var util_19 = util.isBuffer; var util_20 = util.log; var util_21 = util.inherits; var util_22 = util._extend; // 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; } var events = 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$2(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$2(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$2(handler)) return false; if (isFunction$2(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$2(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$2(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$2(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$2(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$2(this._events[type]) && !this._events[type].warned) { if (!isUndefined$2(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$2(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$2(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$2(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject$2(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$2(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$2(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$2(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction$2(arg) { return typeof arg === 'function'; } function isNumber$2(arg) { return typeof arg === 'number'; } function isObject$2(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined$2(arg) { return arg === void 0; } /** * 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); }; var DerivedHelper_1 = DerivedHelper; 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_1(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_1(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_1(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, analytics: false }; 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_1(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_1(state.numericRefinements, function(operators, attribute) { forEach_1(operators, function(values, operator) { if (facetName !== attribute) { forEach_1(values, function(value) { if (isArray_1(value)) { var vs = map_1(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_1(state.facetsRefinements, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach_1(state.facetsExcludes, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach_1(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach_1(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_1( 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_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); return queries; } }; var requestBuilder_1 = requestBuilder; /** * 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; } var _baseInverter = baseInverter; /** * 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), {}); }; } var _createInverter = createInverter; /** * 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_1(identity_1)); var invert_1 = invert; 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_1(keys2Short); var shortener = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys_1(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]; } }; var utils = createCommonjsModule(function (module, exports) { 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; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; exports.arrayToObject = function arrayToObject(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 merge(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 encode(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 compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; exports.isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; }); var utils_1 = utils.arrayToObject; var utils_2 = utils.merge; var utils_3 = utils.assign; var utils_4 = utils.decode; var utils_5 = utils.encode; var utils_6 = utils.compact; var utils_7 = utils.isRegExp; var utils_8 = utils.isBuffer; var replace = String.prototype.replace; var percentTwenties = /%20/g; var formats = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; 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$3 = { 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$3.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$3.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$3.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; }; var stringify_1 = 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$3.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$3.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$3.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults$3.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$3.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$3.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$3.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 : ''; }; var has$1 = Object.prototype.hasOwnProperty; var defaults$4 = { 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$4.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults$4.decoder); val = options.decoder(part.slice(pos + 1), defaults$4.decoder); } if (has$1.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = obj.concat(leaf); } 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] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; 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$1.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$1.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); }; var parse = 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$4.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults$4.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$4.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$4.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$4.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$4.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$4.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$4.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$4.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); }; var lib$1 = { formats: formats, parse: parse, stringify: stringify_1 }; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$7 = 1; var WRAP_PARTIAL_FLAG$4 = 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$7; if (partials.length) { var holders = _replaceHolders(partials, _getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG$4; } return _createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; var bind_1 = bind; /** * 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_1(object, path); }); } var _basePick = basePick; /** * 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); }); var pick_1 = pick; /** * 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; } var mapKeys_1 = mapKeys; /** * 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; } var mapValues_1 = mapValues; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var encode = utils.encode; function recursiveEncode(input) { if (isPlainObject_1(input)) { return mapValues_1(input, recursiveEncode); } if (isArray_1(input)) { return map_1(input, recursiveEncode); } if (isString_1(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) */ var getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var partialStateWithPrefix = lib$1.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys_1( 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_1._parseNumbers(partialState); return pick_1(partialStateWithParsedNumbers, SearchParameters_1.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 */ var getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var foreignConfig = {}; var config = lib$1.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach_1(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach_1(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 */ var 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_1(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys_1( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (!isEmpty_1(moreAttributes)) { var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = lib$1.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return lib$1.stringify(encodedState, {encode: safe, sort: sort}); }; var url = { getStateFromQueryString: getStateFromQueryString, getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString, getQueryStringFromState: getQueryStringFromState }; var version$1 = '2.22.0'; /** * 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$1); this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters_1.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_1._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_1._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_1(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_1(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_1.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_1(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 = SearchParameters_1.make(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_1(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_1(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_1(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach_1(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach_1(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach_1(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_1._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder_1._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_1(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_1(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_1(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$1); 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_1(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; } var algoliasearch_helper = AlgoliaSearchHelper; /** * 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 algoliasearch_helper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = version$1; /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters_1; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults_1; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = url; var algoliasearchHelper_1 = algoliasearchHelper; var algoliasearchHelper_4 = algoliasearchHelper_1.SearchParameters; var getId$1 = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace + '.' + getId$1(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$2(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_4({ 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, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue$2(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue(v.data, props, searchState, context) }; }); } var truncate = function truncate() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return items.slice(0, limit).map(function () { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return Array.isArray(item.items) ? _extends({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine(props, searchState, nextRefinement, context) { var id = getId$1(props); var nextValue = defineProperty$2({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return cleanUpValue(searchState, context, namespace + '.' + getId$1(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. */ var connectHierarchicalMenu = createConnector({ 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: propTypes.string, rootPath: propTypes.string, showParentLevel: propTypes.bool, defaultRefinement: propTypes.string, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, transformItems: propTypes.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$1(props); var results = 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, props, searchState, this.context) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, limit), 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$1(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$1(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attributeName: rootAttribute, value: function value(nextState) { return _refine(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); /** * 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 = get_1(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; } var highlightTags = { highlightPreTag: "<ais-highlight-0000000000>", highlightPostTag: "</ais-highlight-0000000000>" }; var highlight = function highlight(_ref) { var attributeName = _ref.attributeName, hit = _ref.hit, highlightProperty = _ref.highlightProperty; return parseAlgoliaHit({ attributeName: attributeName, hit: hit, preTag: highlightTags.highlightPreTag, postTag: highlightTags.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> * ); * } */ var connectHighlight = createConnector({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /** * 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. * * **Warning:** you will need to use the **objectID** property available on every hit as a key * when iterating over them. This will ensure you have the best possible UI experience * especially on slow networks. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @example * import React from 'react'; * * import { Highlight, InstantSearch } from 'react-instantsearch/dom'; * import { connectHits } from 'react-instantsearch/connectors'; * const CustomHits = connectHits(({ hits }) => * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attributeName="description" hit={hit} /> * </p> * )} * </div> * ); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ var connectHits = createConnector({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = 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; } }); var getId$2 = function getId() { return 'query'; }; function getCurrentRefinement$1(props, searchState, context) { var id = getId$2(); return 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$1(props, searchState, nextRefinement, context) { var id = getId$2(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, getId$2()); } /** * 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. */ var connectAutoComplete = createConnector({ displayName: 'AlgoliaAutoComplete', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { hits: getHits(searchResults), currentRefinement: getCurrentRefinement$1(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(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$1(props, searchState, this.context)); } }); function getId$3() { return 'hitsPerPage'; } function getCurrentRefinement$2(props, searchState, context) { var id = getId$3(); return 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. */ var connectHitsPerPage = createConnector({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: propTypes.number.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.number.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$2(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$3(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$3()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$2(props, searchState, this.context)); }, getMetadata: function getMetadata() { return { id: getId$3() }; } }); function getId$4() { return 'page'; } function getCurrentRefinement$3(props, searchState, context) { var id = getId$4(); var page = 1; return 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 */ var connectInfiniteHits = createConnector({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = 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$3(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId$4(); var nextPage = getCurrentRefinement$3(props, searchState, this.context) + 1; var nextValue = defineProperty$2({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, this.context, resetPage); } }); var namespace$1 = 'menu'; function getId$5(props) { return props.attributeName; } function getCurrentRefinement$4(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$1 + '.' + getId$5(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$3(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$4(props, searchState, context); return name === currentRefinement ? '' : name; } function _refine$2(props, searchState, nextRefinement, context) { var id = getId$5(props); var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, namespace$1 + '.' + getId$5(props)); } var sortBy$1 = ['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. */ var connectMenu = createConnector({ displayName: 'AlgoliaMenu', propTypes: { attributeName: propTypes.string.isRequired, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, defaultRefinement: propTypes.string, transformItems: propTypes.func, withSearchBox: propTypes.bool, searchForFacetValues: propTypes.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 = 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 (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$4(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue$3(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy$1 }).map(function (v) { return { label: v.name, value: getValue$3(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = withSearchBox && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement$4(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$2(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(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$4(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$5(props); var currentRefinement = getCurrentRefinement$4(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: props.attributeName + ': ' + currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _refine$2(props, nextState, '', _this2.context); }, currentRefinement: currentRefinement }] }; } }); 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$2 = 'multiRange'; function getId$6(props) { return props.attributeName; } function getCurrentRefinement$5(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$2 + '.' + getId$6(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$3(props, searchState, nextRefinement, context) { var nextValue = defineProperty$2({}, getId$6(props, searchState), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$3(props, searchState, context) { return cleanUpValue(searchState, context, namespace$2 + '.' + getId$6(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. */ var connectMultiRange = createConnector({ displayName: 'AlgoliaMultiRange', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node, start: propTypes.number, end: propTypes.number })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement$5(props, searchState, this.context); var results = 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$6(props), results, value) : false }; }); var stats = results && results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var refinedItem = find_1(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: isEmpty_1(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$3(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var _parseItem = parseItem(getCurrentRefinement$5(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$6(props); var value = getCurrentRefinement$5(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (value !== '') { var _find2 = find_1(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$3(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); function getId$7() { return 'page'; } function getCurrentRefinement$6(props, searchState, context) { var id = getId$7(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } function _refine$4(props, searchState, nextPage, context) { var id = getId$7(); var nextValue = defineProperty$2({}, id, nextPage); var resetPage = false; return 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 */ var connectPagination = createConnector({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$6(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$4(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$7()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$6(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId$7() }; } }); /** * 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 */ var connectPoweredBy = createConnector({ 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 }; } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = _root.isFinite; /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } var _isFinite = isFinite; /** * 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. * @propType {number} [precision=2] - Number of digits after decimal point to use. * @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$8(props) { return props.attributeName; } var namespace$3 = 'range'; function getCurrentRange(boundaries, stats, precision) { var pow = Math.pow(10, precision); var min = void 0; if (_isFinite(boundaries.min)) { min = boundaries.min; } else if (_isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max = void 0; if (_isFinite(boundaries.max)) { max = boundaries.max; } else if (_isFinite(stats.max)) { max = stats.max; } else { max = undefined; } return { min: min !== undefined ? Math.floor(min * pow) / pow : min, max: max !== undefined ? Math.ceil(max * pow) / pow : max }; } function getCurrentRefinement$7(props, searchState, currentRange, context) { var refinement = getCurrentRefinementValue(props, searchState, context, namespace$3 + '.' + getId$8(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 }; }); var hasMinBound = props.min !== undefined; var hasMaxBound = props.max !== undefined; var hasMinRefinment = refinement.min !== undefined; var hasMaxRefinment = refinement.max !== undefined; if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) { throw Error("You can't provide min value lower than range."); } if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) { throw Error("You can't provide max value greater than range."); } if (hasMinBound && !hasMinRefinment) { refinement.min = currentRange.min; } if (hasMaxBound && !hasMaxRefinment) { refinement.max = currentRange.max; } return refinement; } function nextValueForRefinement(hasBound, isReset, range, value) { var next = void 0; if (!hasBound && range === value) { next = undefined; } else if (hasBound && isReset) { next = range; } else { next = value; } return next; } function _refine$5(props, searchState, nextRefinement, currentRange, context) { var nextMin = nextRefinement.min, nextMax = nextRefinement.max; var currentMinRange = currentRange.min, currentMaxRange = currentRange.max; var isMinReset = nextMin === undefined || nextMin === ''; var isMaxReset = nextMax === undefined || nextMax === ''; var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined; var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined; var isNextMinValid = isMinReset || _isFinite(nextMinAsNumber); var isNextMaxValid = isMaxReset || _isFinite(nextMaxAsNumber); if (!isNextMinValid || !isNextMaxValid) { throw Error("You can't provide non finite values to the range connector."); } if (nextMinAsNumber < currentMinRange) { throw Error("You can't provide min value lower than range."); } if (nextMaxAsNumber > currentMaxRange) { throw Error("You can't provide max value greater than range."); } var id = getId$8(props); var resetPage = true; var nextValue = defineProperty$2({}, id, { min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber), max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber) }); return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$4(props, searchState, context) { return cleanUpValue(searchState, context, namespace$3 + '.' + getId$8(props)); } var connectRange = createConnector({ displayName: 'AlgoliaRange', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, defaultRefinement: propTypes.shape({ min: propTypes.number.isRequired, max: propTypes.number.isRequired }), min: propTypes.number, max: propTypes.number, precision: propTypes.number }, defaultProps: { precision: 2 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName, precision = props.precision, minBound = props.min, maxBound = props.max; var results = getResults(searchResults, this.context); var stats = results ? results.getFacetStats(attributeName) || {} : {}; var count = results ? results.getFacetValues(attributeName).map(function (v) { return { value: v.name, count: v.count }; }) : []; var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision), rangeMin = _getCurrentRange.min, rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example // when we set boundaries on the first render the searchState don't have // the correct refinement. If this behaviour change in the upcoming version // we could store the range inside the searchState instead of rely on `this`. this._currentRange = { min: rangeMin, max: rangeMax }; var _getCurrentRefinement = getCurrentRefinement$7(props, searchState, this._currentRange, this.context), valueMin = _getCurrentRefinement.min, valueMax = _getCurrentRefinement.max; return { min: rangeMin, max: rangeMax, canRefine: count.length > 0, currentRefinement: { min: valueMin === undefined ? rangeMin : valueMin, max: valueMax === undefined ? rangeMax : valueMax }, count: count, precision: precision }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$5(props, searchState, nextRefinement, this._currentRange, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attributeName = props.attributeName; var _getCurrentRefinement2 = getCurrentRefinement$7(props, searchState, this._currentRange, this.context), min = _getCurrentRefinement2.min, max = _getCurrentRefinement2.max; params = params.addDisjunctiveFacet(attributeName); if (min !== undefined) { params = params.addNumericRefinement(attributeName, '>=', min); } if (max !== undefined) { params = params.addNumericRefinement(attributeName, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var _currentRange = this._currentRange, minRange = _currentRange.min, maxRange = _currentRange.max; var _getCurrentRefinement3 = getCurrentRefinement$7(props, searchState, this._currentRange, this.context), minValue = _getCurrentRefinement3.min, maxValue = _getCurrentRefinement3.max; var items = []; var hasMin = minValue !== undefined; var hasMax = maxValue !== undefined; var shouldDisplayMinLabel = hasMin && minValue !== minRange; var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange; if (shouldDisplayMinLabel || shouldDisplayMaxLabel) { var fragments = [hasMin ? minValue + ' <= ' : '', props.attributeName, hasMax ? ' <= ' + maxValue : '']; items.push({ label: fragments.join(''), attributeName: props.attributeName, value: function value(nextState) { return _refine$5(props, nextState, {}, _this._currentRange, _this.context); }, currentRefinement: { min: minValue, max: maxValue } }); } return { id: getId$8(props), index: getIndex(this.context), items: items }; } }); var namespace$4 = 'refinementList'; function getId$9(props) { return props.attributeName; } function getCurrentRefinement$8(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$4 + '.' + getId$9(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$4(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$8(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$6(props, searchState, nextRefinement, context) { var id = getId$9(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$2({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$4); } function _cleanUp$5(props, searchState, context) { return cleanUpValue(searchState, context, namespace$4 + '.' + getId$9(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$2 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnector({ displayName: 'AlgoliaRefinementList', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, operator: propTypes.oneOf(['and', 'or']), showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), withSearchBox: propTypes.bool, searchForFacetValues: propTypes.bool, // @deprecated transformItems: propTypes.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 = 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 (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$8(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, withSearchBox: withSearchBox }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue$4(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy$2 }).map(function (v) { return { label: v.name, value: getValue$4(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$8(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$6(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(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$8(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attributeName, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$9(props); var context = this.context; return { id: id, index: getIndex(this.context), items: getCurrentRefinement$8(props, searchState, context).length > 0 ? [{ attributeName: props.attributeName, label: props.attributeName + ': ', currentRefinement: getCurrentRefinement$8(props, searchState, context), value: function value(nextState) { return _refine$6(props, nextState, [], context); }, items: getCurrentRefinement$8(props, searchState, context).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement$8(props, nextState, context).filter(function (other) { return other !== item; }); return _refine$6(props, searchState, nextSelectedItems, context); } }; }) }] : [] }; } }); /** * 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) */ var connectScrollTo = createConnector({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = 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 (hasMultipleIndex(this.context)) { var index = 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 = omit_1(omit_1(searchState, 'configure'), id); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); var getId$10 = function getId(props) { return props.attributes[0]; }; var namespace$5 = 'hierarchicalMenu'; function _refine$7(props, searchState, nextRefinement, context) { var id = getId$10(props); var nextValue = defineProperty$2({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$5); } function transformValue$1(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$1(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. */ var connectBreadcrumb = createConnector({ 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: propTypes.string, separator: propTypes.oneOfType([propTypes.string, propTypes.element]), transformItems: propTypes.func }, defaultProps: { rootURL: null, separator: ' > ' }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var id = getId$10(props); var results = 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$1(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$7(props, searchState, nextRefinement, this.context); } }); function getId$11() { return 'query'; } function getCurrentRefinement$9(props, searchState, context) { var id = getId$11(props); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function _refine$8(props, searchState, nextRefinement, context) { var id = getId$11(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$6(props, searchState, context) { return cleanUpValue(searchState, context, getId$11()); } /** * 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. */ var connectSearchBox = createConnector({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState) { return { currentRefinement: getCurrentRefinement$9(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$9(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$11(props); var currentRefinement = getCurrentRefinement$9(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: id + ': ' + currentRefinement, value: function value(nextState) { return _refine$8(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); function getId$12() { return 'sortBy'; } function getCurrentRefinement$10(props, searchState, context) { var id = getId$12(props); return 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. */ var connectSortBy = createConnector({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: propTypes.string, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$10(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$12(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$12()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$10(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$12() }; } }); /** * 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. */ var connectStats = createConnector({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function getId$13(props) { return props.attributeName; } var namespace$6 = 'toggle'; function getCurrentRefinement$11(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$6 + '.' + getId$13(props), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return false; }); } function _refine$9(props, searchState, nextRefinement, context) { var id = getId$13(props); var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$6); } function _cleanUp$7(props, searchState, context) { return cleanUpValue(searchState, context, namespace$6 + '.' + getId$13(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 * @requirements To use this widget, you'll need an attribute to toggle on. * * You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an * extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details. * * @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 */ var connectToggle = createConnector({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string, filter: propTypes.func, attributeName: propTypes.string, value: propTypes.any, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$11(props, searchState, this.context); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$9(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$7(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, value = props.value, filter = props.filter; var checked = getCurrentRefinement$11(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$13(props); var checked = getCurrentRefinement$11(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (checked) { items.push({ label: props.label, currentRefinement: props.label, attributeName: props.attributeName, value: function value(nextState) { return _refine$9(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); /** * The `connectStateResults` connector provides a way to access the `searchState` and the `searchResults` * of InstantSearch. * For instance this connector allows you to create results/noResults or query/noQuery pages. * @name connectStateResults * @kind connector * @providedPropType {object} searchState - The search state of the instant search component. <br/><br/> See: [Search state structure](https://community.algolia.com/react-instantsearch/guide/Search_state.html) * @providedPropType {object} searchResults - The search results. <br/><br/> In case of multiple indices: if used under `<Index>`, results will be those of the corresponding index otherwise it'll be those of the root index See: [Search results structure](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults) * @providedPropType {object} allSearchResults - In case of multiple indices you can retrieve all the results * @providedPropType {string} error - If the search failed, the error will be logged here. * @providedPropType {boolean} searching - If there is a search in progress. * @providedPropType {boolean} searchingForFacetValues - If there is a search in a list in progress. * @providedPropType {boolean} props - component props. * @example * import React from 'react'; * * import { InstantSearch, Hits } from 'react-instantsearch/dom'; * import { connectStateResults } from 'react-instantsearch/connectors'; * * const Content = connectStateResults( * ({ searchState, searchResults }) => * searchResults && searchResults.nbHits !== 0 * ? <Hits/> * : <div> * No results has been found for {searchState.query} * </div> * ); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Content /> * </InstantSearch> * ); * } */ var connectStateResults = createConnector({ displayName: 'AlgoliaStateResults', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); return { searchState: searchState, searchResults: results, allSearchResults: searchResults.results, searching: searchResults.searching, error: searchResults.error, searchingForFacetValues: searchResults.searchingForFacetValues, props: props }; } }); exports.connectConfigure = connectConfigure; exports.connectCurrentRefinements = connectCurrentRefinements; exports.connectHierarchicalMenu = connectHierarchicalMenu; exports.connectHighlight = connectHighlight; exports.connectHits = connectHits; exports.connectAutoComplete = connectAutoComplete; exports.connectHitsPerPage = connectHitsPerPage; exports.connectInfiniteHits = connectInfiniteHits; exports.connectMenu = connectMenu; exports.connectMultiRange = connectMultiRange; exports.connectPagination = connectPagination; exports.connectPoweredBy = connectPoweredBy; exports.connectRange = connectRange; exports.connectRefinementList = connectRefinementList; exports.connectScrollTo = connectScrollTo; exports.connectBreadcrumb = connectBreadcrumb; exports.connectSearchBox = connectSearchBox; exports.connectSortBy = connectSortBy; exports.connectStats = connectStats; exports.connectToggle = connectToggle; exports.connectStateResults = connectStateResults; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=Connectors.js.map
src/svg-icons/action/delete-forever.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDeleteForever = (props) => ( <SvgIcon {...props}> <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zm2.46-7.12l1.41-1.41L12 12.59l2.12-2.12 1.41 1.41L13.41 14l2.12 2.12-1.41 1.41L12 15.41l-2.12 2.12-1.41-1.41L10.59 14l-2.13-2.12zM15.5 4l-1-1h-5l-1 1H5v2h14V4z"/> </SvgIcon> ); ActionDeleteForever = pure(ActionDeleteForever); ActionDeleteForever.displayName = 'ActionDeleteForever'; ActionDeleteForever.muiName = 'SvgIcon'; export default ActionDeleteForever;
automatic-test-evaluation/src/Blanks/ClassMarksBarChart.js
hris11/AutomaticTestEvaluation
import React, { Component } from 'react'; import { BarChart, Bar, XAxis} from 'recharts'; const CustomBar = (props) => { const { x, y, width, height, fill } = props; if (x === +x && y === +y) { const path = `M${x},${y + height} C${x + width / 3},${y + height} ${x + width / 2},${y + height / 3} ${x + width / 2}, ${y} C${x + width / 2},${y + height / 3} ${x + 2 * width / 3},${y + height} ${x + width}, ${y + height} Z`; return <path d={path} stroke='none' fill={fill}/>; } return null; }; export default class Demo extends Component { constructor(props) { super(props); this.state = {}; } static displayName = 'BarChartDemo'; generateDataset() { let classes = Object.assign([], this.props.marks); let result = []; result.push({ name: '6', uv: 6, atm: 6, pv: 6, time: 0, uvError: [100, 50], pvError: [110, 20] }); classes.map(function (aClass, index) { result.push({ name: (aClass.className.length >= 7) ? aClass.className.slice(0, 2) + '...' + aClass.className.slice(aClass.className.length - 2, aClass.className.length) : aClass.className, pv: 6, atm: 6, time: index + 1, uvError: [100, 50], pvError: [110, 20], uv: (aClass.averageMark === 0)? 1 : aClass.averageMark }); }); return result; } render() { const data = this.generateDataset(); return ( <div className="bar-charts"> <div className="bar-chart-wrapper"> <BarChart width={500} height={250} barCategoryGap={0} data={data} margin={{ top: 20, right: 20, bottom: 0, left: 20 }}> <XAxis dataKey="name" /> <Bar dataKey="uv" barGap={0} fill="#54509e" shape={CustomBar} /> </BarChart> </div> </div> ); } }
packages/material-ui-icons/src/Texture.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Texture = props => <SvgIcon {...props}> <path d="M19.51 3.08L3.08 19.51c.09.34.27.65.51.9.25.24.56.42.9.51L20.93 4.49c-.19-.69-.73-1.23-1.42-1.41zM11.88 3L3 11.88v2.83L14.71 3h-2.83zM5 3c-1.1 0-2 .9-2 2v2l4-4H5zm14 18c.55 0 1.05-.22 1.41-.59.37-.36.59-.86.59-1.41v-2l-4 4h2zm-9.71 0h2.83L21 12.12V9.29L9.29 21z" /> </SvgIcon>; Texture = pure(Texture); Texture.muiName = 'SvgIcon'; export default Texture;
packages/material-ui-icons/src/CardGiftcard.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let CardGiftcard = props => <SvgIcon {...props}> <path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z" /> </SvgIcon>; CardGiftcard = pure(CardGiftcard); CardGiftcard.muiName = 'SvgIcon'; export default CardGiftcard;
packages/kalama/src/containers/MainWindow.js
corporateanon/kalama
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { getRoute } from '../ducks/router'; import Label from '../components/Label'; import { getTasksSummary, STATUS_SCHEDULED, STATUS_FAILED, STATUS_COMPLETED } from '../ducks/download'; import { getCurrentTrack, getParentResource } from '../ducks/tracks'; import { getMessage } from '../ducks/flashMessages'; import chalk from 'chalk'; const mapStateToProps = state => { return { route: getRoute(state), parentResource: getParentResource(state), tasksSummary: getTasksSummary(state), currentTrack: getCurrentTrack(state), message: getMessage(state) }; }; const mapDispatchToProps = dispatch => { return bindActionCreators({}, dispatch); }; const getTitle = (route, playlist, tasksSummary, currentTrack, message) => { if (message) { return message; } const screenName = route ? route.screen : null; const playlistName = playlist ? playlist.label : null; let part0, part1, part2; if (screenName === 'Search') { part0 = 'kalama (press Ctrl+L to help)'; } else { part0 = screenName; } const tasksLeft = tasksSummary[STATUS_SCHEDULED]; const tasksFailed = tasksSummary[STATUS_FAILED]; const tasksCompleted = tasksSummary[STATUS_COMPLETED]; if (tasksLeft > 0) { part1 = `Download: ${tasksLeft} (${chalk.green( tasksCompleted || 0 )}|${chalk.red(tasksFailed || 0)})`; } else { part1 = playlistName; } if (currentTrack) { part2 = currentTrack.suffix; } return [part0, part1, part2].filter(_ => _).join(' / '); }; class MainWindow extends Component { boxStyle = { border: { fg: 'blue' } }; borderOptions = { type: 'line' }; titleStyle = { bg: 'blue' }; render() { const { boxStyle, borderOptions, titleStyle, props: { children, route, parentResource, tasksSummary, currentTrack, message } } = this; return ( <element> <box border={borderOptions} style={boxStyle} width="100%" height="100%" > {children} </box> <Label style={titleStyle} top={0} text={getTitle( route, parentResource, tasksSummary, currentTrack, message )} /> </element> ); } } export default connect( mapStateToProps, mapDispatchToProps )(MainWindow);
examples/with-custom-reverse-proxy/pages/index.js
BlancheXu/test
import React from 'react' export default class extends React.Component { constructor (props) { super(props) this.state = { response: '' } } static async getInitialProps ({ pathname, query }) { return { pathname, query, queryString: Object.keys(query).join('') } } async componentDidMount () { const response = JSON.stringify( await window .fetch(`/api/${this.props.queryString}`) .then(response => response.json().then(data => data)), null, 2 ) this.setState({ response }) } render () { return ( <content> <p> /api/{this.props.queryString} routed to https://swapi.co/api/ {this.props.queryString} </p> <p> <a href='?people/2'>Try</a> &nbsp; <a href='/'>Reset</a> </p> <pre>{this.state.response ? this.state.response : 'Loading...'}</pre> </content> ) } }
packages/react-devtools-shared/src/devtools/views/ButtonIcon.js
rickbeerendonk/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import styles from './ButtonIcon.css'; export type IconType = | 'add' | 'cancel' | 'clear' | 'close' | 'collapsed' | 'copy' | 'delete' | 'down' | 'expanded' | 'export' | 'filter' | 'import' | 'log-data' | 'more' | 'next' | 'previous' | 'record' | 'reload' | 'save' | 'search' | 'settings' | 'suspend' | 'undo' | 'up' | 'view-dom' | 'view-source'; type Props = {| className?: string, type: IconType, |}; export default function ButtonIcon({className = '', type}: Props) { let pathData = null; switch (type) { case 'add': pathData = PATH_ADD; break; case 'cancel': pathData = PATH_CANCEL; break; case 'clear': pathData = PATH_CLEAR; break; case 'close': pathData = PATH_CLOSE; break; case 'collapsed': pathData = PATH_COLLAPSED; break; case 'copy': pathData = PATH_COPY; break; case 'delete': pathData = PATH_DELETE; break; case 'down': pathData = PATH_DOWN; break; case 'expanded': pathData = PATH_EXPANDED; break; case 'export': pathData = PATH_EXPORT; break; case 'filter': pathData = PATH_FILTER; break; case 'import': pathData = PATH_IMPORT; break; case 'log-data': pathData = PATH_LOG_DATA; break; case 'more': pathData = PATH_MORE; break; case 'next': pathData = PATH_NEXT; break; case 'previous': pathData = PATH_PREVIOUS; break; case 'record': pathData = PATH_RECORD; break; case 'reload': pathData = PATH_RELOAD; break; case 'save': pathData = PATH_SAVE; break; case 'search': pathData = PATH_SEARCH; break; case 'settings': pathData = PATH_SETTINGS; break; case 'suspend': pathData = PATH_SUSPEND; break; case 'undo': pathData = PATH_UNDO; break; case 'up': pathData = PATH_UP; break; case 'view-dom': pathData = PATH_VIEW_DOM; break; case 'view-source': pathData = PATH_VIEW_SOURCE; break; default: console.warn(`Unsupported type "${type}" specified for ButtonIcon`); break; } return ( <svg xmlns="http://www.w3.org/2000/svg" className={`${styles.ButtonIcon} ${className}`} width="24" height="24" viewBox="0 0 24 24"> <path d="M0 0h24v24H0z" fill="none" /> <path fill="currentColor" d={pathData} /> </svg> ); } const PATH_ADD = 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z'; const PATH_CANCEL = ` M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z `; const PATH_CLEAR = ` M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z `; const PATH_CLOSE = 'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'; const PATH_COLLAPSED = 'M10 17l5-5-5-5v10z'; const PATH_COPY = ` M3 13h2v-2H3v2zm0 4h2v-2H3v2zm2 4v-2H3a2 2 0 0 0 2 2zM3 9h2V7H3v2zm12 12h2v-2h-2v2zm4-18H9a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 12H9V5h10v10zm-8 6h2v-2h-2v2zm-4 0h2v-2H7v2z `; const PATH_DELETE = ` M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z `; const PATH_DOWN = 'M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z'; const PATH_EXPANDED = 'M7 10l5 5 5-5z'; const PATH_EXPORT = 'M15.82,2.14v7H21l-9,9L3,9.18H8.18v-7ZM3,20.13H21v1.73H3Z'; const PATH_FILTER = 'M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z'; const PATH_IMPORT = 'M8.18,18.13v-7H3l9-8.95,9,9H15.82v7ZM3,20.13H21v1.73H3Z'; const PATH_LOG_DATA = ` M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z `; const PATH_MORE = ` M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z `; const PATH_NEXT = 'M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z'; const PATH_PREVIOUS = 'M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z'; const PATH_RECORD = 'M4,12a8,8 0 1,0 16,0a8,8 0 1,0 -16,0'; const PATH_RELOAD = ` M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z `; const PATH_SAVE = ` M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z `; const PATH_SEARCH = ` M8.5,22H3.7l-1.4-1.5V3.8l1.3-1.5h17.2l1,1.5v4.9h-1.3V4.3l-0.4-0.6H4.2L3.6,4.3V20l0.7,0.7h4.2V22z M23,13.9l-4.6,3.6l4.6,4.6l-1.1,1.1l-4.7-4.4l-3.3,4.4l-3.2-12.3L23,13.9z `; const PATH_SETTINGS = ` M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z `; const PATH_SUSPEND = ` M15 1H9v2h6V1zm-4 13h2V8h-2v6zm8.03-6.61l1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM12 20c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z `; const PATH_UNDO = ` M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z `; const PATH_UP = 'M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z'; const PATH_VIEW_DOM = ` M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z `; const PATH_VIEW_SOURCE = ` M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z `;
src/client/components/pages/parts/add-entity-to-collection-modal.js
bookbrainz/bookbrainz-site
/* * Copyright (C) 2020 Prabal Singh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import * as bootstrap from 'react-bootstrap'; import {faPlus, faTimes} from '@fortawesome/free-solid-svg-icons'; import {lowerCase, uniqBy} from 'lodash'; import EntitySearchFieldOption from '../../../entity-editor/common/entity-search-field-option'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import PropTypes from 'prop-types'; import React from 'react'; import request from 'superagent'; const {Alert, Badge, Button, ButtonGroup, Col, Modal, Row} = bootstrap; class AddEntityToCollectionModal extends React.Component { constructor(props) { super(props); this.state = { entities: [], error: null }; this.handleAddEntity = this.handleAddEntity.bind(this); this.handleRemoveEntity = this.handleRemoveEntity.bind(this); this.handleChangeEntity = this.handleChangeEntity.bind(this); this.getCleanedEntities = this.getCleanedEntities.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleAlertDismiss = this.handleAlertDismiss.bind(this); } getCleanedEntities() { return uniqBy(this.state.entities.filter(entity => entity && entity.id !== null), 'id'); } handleAddEntity() { this.setState(prevState => ({ entities: [...prevState.entities, {id: null, name: ''}] })); } handleChangeEntity(newEnt, index) { let newEntity; if (!newEnt) { newEntity = { id: null, name: '' }; } else { newEntity = newEnt; } this.setState((prevState) => { const newEntities = prevState.entities; newEntities[index] = newEntity; return { entities: newEntities }; }); } handleRemoveEntity(index) { this.setState(prevState => ({ entities: prevState.entities.splice(index, 1) && prevState.entities })); } handleAlertDismiss() { this.setState({error: null}); } handleSubmit() { const cleanedEntities = this.getCleanedEntities(); const bbids = cleanedEntities.map(entity => entity.id); if (bbids.length) { request.post(`/collection/${this.props.collectionId}/add`) .send({bbids}) .then((res) => { this.setState({ entities: [], error: null }, () => { this.props.closeModalAndShowMessage({ text: `Added ${bbids.length} ${lowerCase(this.props.collectionType)}${bbids.length > 1 ? 's' : ''}`, type: 'success' }); }); }, (error) => { this.setState({ error: 'Something went wrong! Please try again later' }); }); } else { this.setState({ error: `No ${lowerCase(this.props.collectionType)} selected` }); } } render() { if (this.state.entities.length === 0) { this.handleAddEntity(); } let errorComponent = null; if (this.state.error) { errorComponent = ( <div className="text-center margin-top-1"> <Alert bsStyle="danger" onDismiss={this.handleAlertDismiss}>{this.state.error}</Alert> </div> ); } const cleanedEntities = this.getCleanedEntities(); /* eslint-disable react/jsx-no-bind */ const addEntityToCollectionForm = ( <Row> <Col id="addEntityToCollection" md={12} > <form className="padding-sides-0" > { this.state.entities.map((entity, index) => { const buttonAfter = ( <Button bsSize="small" bsStyle="danger" type="button" onClick={() => this.handleRemoveEntity(index)} > <FontAwesomeIcon icon={faTimes}/>&nbsp;Remove </Button> ); return ( <div key={entity.id}> <EntitySearchFieldOption buttonAfter={buttonAfter} instanceId="entitySearchField" label={`Select ${this.props.collectionType}`} name={this.props.collectionType} type={this.props.collectionType} value={entity} onChange={(newEntity) => this.handleChangeEntity(newEntity, index)} /> </div> ); }) } </form> </Col> </Row> ); return ( <Modal bsSize="large" show={this.props.show} onHide={this.props.onCloseModal} > <Modal.Header closeButton> <Modal.Title> Add {lowerCase(this.props.collectionType)}s to the collection </Modal.Title> </Modal.Header> <Modal.Body> {addEntityToCollectionForm} {errorComponent} </Modal.Body> <Modal.Footer> <ButtonGroup> <Button bsStyle="primary" type="button" onClick={this.handleAddEntity} > <FontAwesomeIcon icon={faPlus}/> &nbsp;Add another {lowerCase(this.props.collectionType)} </Button> <Button bsStyle="success" disabled={!cleanedEntities.length} onClick={this.handleSubmit} > <FontAwesomeIcon icon={faPlus}/> &nbsp;Add <Badge>{cleanedEntities.length}</Badge>&nbsp; {lowerCase(this.props.collectionType)}{cleanedEntities.length > 1 ? 's' : ''} to the collection </Button> </ButtonGroup> </Modal.Footer> </Modal> ); } } AddEntityToCollectionModal.displayName = 'AddEntityToCollectionModal'; AddEntityToCollectionModal.propTypes = { closeModalAndShowMessage: PropTypes.func.isRequired, collectionId: PropTypes.string.isRequired, collectionType: PropTypes.string.isRequired, onCloseModal: PropTypes.func.isRequired, show: PropTypes.bool.isRequired }; export default AddEntityToCollectionModal;
docs/src/app/components/pages/components/Menu/ExampleIcons.js
rhaedes/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import RemoveRedEye from 'material-ui/svg-icons/image/remove-red-eye'; import PersonAdd from 'material-ui/svg-icons/social/person-add'; import ContentLink from 'material-ui/svg-icons/content/link'; import Divider from 'material-ui/Divider'; import ContentCopy from 'material-ui/svg-icons/content/content-copy'; import Download from 'material-ui/svg-icons/file/file-download'; import Delete from 'material-ui/svg-icons/action/delete'; import FontIcon from 'material-ui/FontIcon'; const style = { paper: { display: 'inline-block', float: 'left', margin: '16px 32px 16px 0', }, rightIcon: { textAlign: 'center', lineHeight: '24px', }, }; const MenuExampleIcons = () => ( <div> <Paper style={style.paper}> <Menu> <MenuItem primaryText="Preview" leftIcon={<RemoveRedEye />} /> <MenuItem primaryText="Share" leftIcon={<PersonAdd />} /> <MenuItem primaryText="Get links" leftIcon={<ContentLink />} /> <Divider /> <MenuItem primaryText="Make a copy" leftIcon={<ContentCopy />} /> <MenuItem primaryText="Download" leftIcon={<Download />} /> <Divider /> <MenuItem primaryText="Remove" leftIcon={<Delete />} /> </Menu> </Paper> <Paper style={style.paper}> <Menu> <MenuItem primaryText="Clear Config" /> <MenuItem primaryText="New Config" rightIcon={<PersonAdd />} /> <MenuItem primaryText="Project" rightIcon={<FontIcon className="material-icons">settings</FontIcon>} /> <MenuItem primaryText="Workspace" rightIcon={ <FontIcon className="material-icons" style={{color: '#559'}}>settings</FontIcon> } /> <MenuItem primaryText="Paragraph" rightIcon={<b style={style.rightIcon}>¶</b>} /> <MenuItem primaryText="Section" rightIcon={<b style={style.rightIcon}>§</b>} /> </Menu> </Paper> </div> ); export default MenuExampleIcons;
admin/client/App/screens/Home/index.js
vokal/keystone
/** * The Home view is the view one sees at /keystone. It shows a list of all lists, * grouped by their section. */ import React from 'react'; import { Container, Spinner } from '../../elemental'; import { connect } from 'react-redux'; import Lists from './components/Lists'; import Section from './components/Section'; import AlertMessages from '../../shared/AlertMessages'; import { loadCounts, } from './actions'; var HomeView = React.createClass({ displayName: 'HomeView', getInitialState () { return { modalIsOpen: true, }; }, // When everything is rendered, start loading the item counts of the lists // from the API componentDidMount () { this.props.dispatch(loadCounts()); }, getSpinner () { if (this.props.counts && Object.keys(this.props.counts).length === 0 && (this.props.error || this.props.loading)) { return ( <Spinner /> ); } return null; }, render () { const spinner = this.getSpinner(); return ( <Container data-screen-id="home"> <div className="dashboard-header"> <div className="dashboard-heading">{Keystone.brand}</div> </div> <div className="dashboard-groups"> {(this.props.error) && ( <AlertMessages alerts={{ error: { error: "There is a problem with the network, we're trying to reconnect...", } }} /> )} {/* Render flat nav */} {Keystone.nav.flat ? ( <Lists counts={this.props.counts} lists={Keystone.lists} spinner={spinner} /> ) : ( <div> {/* Render nav with sections */} {Keystone.nav.sections.map((navSection) => { return ( <Section key={navSection.key} id={navSection.key} label={navSection.label}> <Lists counts={this.props.counts} lists={navSection.lists} spinner={spinner} /> </Section> ); })} {/* Render orphaned lists */} {Keystone.orphanedLists.length ? ( <Section label="Other" icon="octicon-database"> <Lists counts={this.props.counts} lists={Keystone.orphanedLists} spinner={spinner} /> </Section> ) : null} </div> )} </div> </Container> ); }, }); export { HomeView, }; export default connect((state) => ({ counts: state.home.counts, loading: state.home.loading, error: state.home.error, }))(HomeView);
src/js/components/InfiniteScroll/stories/ShowBefore.js
grommet/grommet
import React from 'react'; import { Box, InfiniteScroll, Text } from 'grommet'; const allItems = Array(240) .fill() .map((_, i) => `item ${i + 1}`); const Example = (props) => ( // Uncomment <Grommet> lines when using outside of storybook // <Grommet theme={...}> <InfiniteScroll items={allItems} {...props}> {(item) => ( <Box key={item} pad="medium" border={{ side: 'bottom' }} align="center"> <Text>{item}</Text> </Box> )} </InfiniteScroll> // </Grommet> ); export const ShowBefore = () => <Example replace show={27} />; ShowBefore.storyName = 'Replace, show before step'; ShowBefore.parameters = { chromatic: { disable: true }, }; export default { title: 'Utilities/InfiniteScroll/Replace, show before step', };
src/templates/index.js
calpa/blog
/* eslint react/prop-types: 0 */ import React from 'react'; import Link from 'gatsby-link'; import Card from '../components/Card'; import Sidebar from '../components/Sidebar'; import ShareBox from '../components/ShareBox'; import './index.scss'; const NavLinkText = ({ color, text }) => ( <div className="navlink" style={{ color, }} > {text} </div> ); const NavLink = ({ test, url, text }) => { if (!test) { return <NavLinkText color="#7d7d7d" text={text} />; } return ( <Link to={`${url}`}> <NavLinkText color="#66ccff" text={text} /> </Link> ); }; const Page = ({ pageContext, location }) => { const { group, index, first, last, pathPrefix, } = pageContext; const previousUrl = index - 1 === 1 ? '' : `/${pathPrefix}/${index - 1}`; const nextUrl = `/${pathPrefix}/${index + 1}`; return ( <React.Fragment> <div className="row homepage" style={{ marginTop: 20, }} > <Sidebar /> <div className="col-xl-6 col-lg-7 col-md-12 col-xs-12 order-2"> {group.map(({ node }) => ( <Card {...node.frontmatter} url={node.frontmatter.slug ? node.frontmatter.slug : node.fields.slug} key={node.fields.slug} /> ))} <div className="row" style={{ justifyContent: 'space-around', marginBottom: '20px', }} > <div className="previousLink"> <NavLink test={!first} url={previousUrl} text="Previous" /> </div> <div className="nextLink"> <NavLink test={!last} url={nextUrl} text="Next" /> </div> </div> </div> <div className="col-xl-2 col-lg-1 order-3" /> </div> <ShareBox url={location.href} hasCommentBox={false} /> </React.Fragment> ); }; export default Page;
docs/src/app/components/pages/components/Toolbar/Page.js
tan-jerene/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import toolbarReadmeText from './README'; import toolbarExampleSimpleCode from '!raw!./ExampleSimple'; import ToolbarExampleSimple from './ExampleSimple'; import toolbarCode from '!raw!material-ui/Toolbar/Toolbar'; import toolbarText from './Toolbar'; import toolbarGroupCode from '!raw!material-ui/Toolbar/ToolbarGroup'; import toolbarGroupText from './ToolbarGroup'; import toolbarSeparatorCode from '!raw!material-ui/Toolbar/ToolbarSeparator'; import toolbarSeparatorText from './ToolbarSeparator'; import toolbarTitleCode from '!raw!material-ui/Toolbar/ToolbarTitle'; import toolbarTitleText from './ToolbarTitle'; const description = 'An example Toolbar demonstrating the use of the available sub-components, and including a ' + 'number of other Material-UI components, such as [Drop Down Menu](/#/components/dropdown-menu), [Font Icon]' + '(/#/components/font-icon), [Icon Menu](/#/components/icon-menu) and [Raised Button](/#/components/raised-button) .'; const ToolbarPage = () => ( <div> <Title render={(previousTitle) => `Toolbar - ${previousTitle}`} /> <MarkdownElement text={toolbarReadmeText} /> <CodeExample description={description} code={toolbarExampleSimpleCode}> <ToolbarExampleSimple /> </CodeExample> <PropTypeDescription code={toolbarCode} header={toolbarText} /> <PropTypeDescription code={toolbarGroupCode} header={toolbarGroupText} /> <PropTypeDescription code={toolbarSeparatorCode} header={toolbarSeparatorText} /> <PropTypeDescription code={toolbarTitleCode} header={toolbarTitleText} /> </div> ); export default ToolbarPage;
actor-apps/app-web/src/app/components/modals/Preferences.react.js
nguyenhongson03/actor-platform
import React from 'react'; import Modal from 'react-modal'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import PreferencesActionCreators from 'actions/PreferencesActionCreators'; import PreferencesStore from 'stores/PreferencesStore'; const appElement = document.getElementById('actor-web-app'); Modal.setAppElement(appElement); const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { isOpen: PreferencesStore.isModalOpen() }; }; @ReactMixin.decorate(IntlMixin) class PreferencesModal extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ button: { minWidth: 60 } }); PreferencesStore.addChangeListener(this.onChange); document.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { PreferencesStore.removeChangeListener(this.onChange); document.removeEventListener('keydown', this.onKeyDown, false); } onChange = () => { this.setState(getStateFromStores()); }; onClose = () => { PreferencesActionCreators.hide(); }; onKeyDown = event => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; render() { let menuItems = [ { payload: '1', text: 'English' }, { payload: '2', text: 'Russian' } ]; if (this.state.isOpen === true) { return ( <Modal className="modal-new modal-new--preferences" closeTimeoutMS={150} isOpen={this.state.isOpen} style={{width: 760}}> <div className="modal-new__header"> <i className="modal-new__header__icon material-icons">settings</i> <h3 className="modal-new__header__title"> <FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/> </h3> <div className="pull-right"> <FlatButton hoverColor="rgba(81,145,219,.17)" label="Done" labelStyle={{padding: '0 8px'}} onClick={this.onClose} secondary={true} style={{marginTop: -6}}/> </div> </div> <div className="modal-new__body"> <div className="preferences"> <aside className="preferences__tabs"> <a className="preferences__tabs__tab preferences__tabs__tab--active">General</a> <a className="preferences__tabs__tab">Notifications</a> <a className="preferences__tabs__tab">Sidebar colors</a> <a className="preferences__tabs__tab">Security</a> <a className="preferences__tabs__tab">Other Options</a> </aside> <div className="preferences__body"> <div className="preferences__list"> <div className="preferences__list__item preferences__list__item--general"> <ul> <li> <i className="icon material-icons">keyboard</i> <RadioButtonGroup defaultSelected="default" name="send"> <RadioButton label="Enter – send message, Shift + Enter – new line" style={{marginBottom: 12}} value="default"/> <RadioButton label="Cmd + Enter – send message, Enter – new line" //style={{marginBottom: 16}} value="alt"/> </RadioButtonGroup> </li> <li className="language"> <i className="icon material-icons">menu</i> Language: <DropDownMenu labelStyle={{color: '#5191db'}} menuItemStyle={{height: '40px', lineHeight: '40px'}} menuItems={menuItems} style={{verticalAlign: 'top', height: 52}} underlineStyle={{display: 'none'}}/> </li> </ul> </div> <div className="preferences__list__item preferences__list__item--notifications"> <ul> <li> <i className="icon material-icons">notifications</i> <RadioButtonGroup defaultSelected="all" name="notifications"> <RadioButton label="Notifications for activity of any kind" style={{marginBottom: 12}} value="all"/> <RadioButton label="Notifications for Highlight Words and direct messages" style={{marginBottom: 12}} value="quiet"/> <RadioButton label="Never send me notifications" style={{marginBottom: 12}} value="disable"/> </RadioButtonGroup> <p className="hint"> You can override your desktop notification preference on a case-by-case basis for channels and groups from the channel or group menu. </p> </li> </ul> </div> </div> </div> </div> </div> </Modal> ); } else { return null; } } } export default PreferencesModal;