path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/components/FlightTracker/DatePicker.js | elstgav/stair-climber | import React from 'react'
import moment from 'moment'
import { Icon } from 'src/components'
const DatePicker = ({ selected, onChange }) => {
function onPrevDay() {
const newDate = selected.clone().subtract(1, 'days')
onChange(newDate)
}
function onNextDay() {
const newDate = selected.clone().add(1, 'days')
onChange(newDate)
}
function onTodayClicked() {
onChange(moment())
}
return (
<div>
<div className="input-group">
<button className="btn btn-secondary" onClick={onPrevDay}>
<Icon name="chevron-left" />
</button>
<span> {selected.format('ddd, MMM D')} </span>
<button className="btn btn-secondary" onClick={onNextDay}>
<Icon name="chevron-right" />
</button>
</div>
<button onClick={onTodayClicked}>Today</button>
</div>
)
}
DatePicker.propTypes = {
selected: React.PropTypes.object,
onChange: React.PropTypes.func.isRequired,
}
DatePicker.defaultProps = {
selected: moment(),
onChange() {},
}
export { DatePicker }
|
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js | supertanglang/actor-platform | import _ from 'lodash';
import React from 'react';
import { Styles, RaisedButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ContactStore from 'stores/ContactStore';
import ContactActionCreators from 'actions/ContactActionCreators';
import AddContactStore from 'stores/AddContactStore';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import ContactsSectionItem from './ContactsSectionItem.react';
import AddContactModal from 'components/modals/AddContact.react.js';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isAddContactModalOpen: AddContactStore.isModalOpen(),
contacts: ContactStore.getContacts()
};
};
class ContactsSection extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
ContactActionCreators.hideContactList();
ContactStore.removeChangeListener(this.onChange);
AddContactStore.removeChangeListener(this.onChange);
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ContactActionCreators.showContactList();
ContactStore.addChangeListener(this.onChange);
AddContactStore.addChangeListener(this.onChange);
ThemeManager.setTheme(ActorTheme);
}
onChange = () => {
this.setState(getStateFromStores());
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
render() {
let contacts = this.state.contacts;
let contactList = _.map(contacts, (contact, i) => {
return (
<ContactsSectionItem contact={contact} key={i}/>
);
});
let addContactModal;
if (this.state.isAddContactModalOpen) {
addContactModal = <AddContactModal/>;
}
return (
<section className="sidebar__contacts">
<ul className="sidebar__list sidebar__list--contacts">
{contactList}
</ul>
<footer>
<RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/>
{addContactModal}
</footer>
</section>
);
}
}
export default ContactsSection;
|
test/integration/image-component/default/pages/missing-src.js | JeromeFitz/next.js | import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<Image width={200}></Image>
</div>
)
}
export default Page
|
client/modules/questions/components/questionsSelect.js | johngonzalez/abcdapp | import React from 'react';
import {Pagination} from 'react-bootstrap';
const QuestionsSelect = ({currentQuestion, questionsCount, select, children}) => (
<div className="text-center">
<Pagination
bsSize="big"
activePage={currentQuestion.questionSeq + 1}
items={questionsCount}
onSelect={select}
/>
{
children ?
React.cloneElement(children, {questionId: currentQuestion._id}) :
null
}
</div>
);
QuestionsSelect.propTypes = {
select: React.PropTypes.func.isRequired,
currentQuestion: React.PropTypes.object.isRequired,
questionsCount: React.PropTypes.number.isRequired,
children: React.PropTypes.element
};
export default QuestionsSelect;
|
example/examples/StaticMap.js | phantomlds/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
ScrollView,
} from 'react-native';
import MapView from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
class StaticMap extends React.Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
};
}
render() {
return (
<View style={styles.container}>
<ScrollView
style={StyleSheet.absoluteFill}
contentContainerStyle={styles.scrollview}
>
<Text>Clicking</Text>
<Text>and</Text>
<Text>dragging</Text>
<Text>the</Text>
<Text>map</Text>
<Text>will</Text>
<Text>cause</Text>
<Text>the</Text>
<MapView
provider={this.props.provider}
style={styles.map}
scrollEnabled={false}
zoomEnabled={false}
pitchEnabled={false}
rotateEnabled={false}
initialRegion={this.state.region}
>
<MapView.Marker
title="This is a title"
description="This is a description"
coordinate={this.state.region}
/>
</MapView>
<Text>parent</Text>
<Text>ScrollView</Text>
<Text>to</Text>
<Text>scroll.</Text>
<Text>When</Text>
<Text>using</Text>
<Text>a Google</Text>
<Text>Map</Text>
<Text>this only</Text>
<Text>works</Text>
<Text>if you</Text>
<Text>disable:</Text>
<Text>scroll,</Text>
<Text>zoom,</Text>
<Text>pitch,</Text>
<Text>rotate.</Text>
<Text>...</Text>
<Text>It</Text>
<Text>would</Text>
<Text>be</Text>
<Text>nice</Text>
<Text>to</Text>
<Text>have</Text>
<Text>an</Text>
<Text>option</Text>
<Text>that</Text>
<Text>still</Text>
<Text>allows</Text>
<Text>zooming.</Text>
</ScrollView>
</View>
);
}
}
StaticMap.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
scrollview: {
alignItems: 'center',
paddingVertical: 40,
},
map: {
width: 250,
height: 250,
},
});
module.exports = StaticMap;
|
src/components/Dashboard/DashBoardIndex.js | RegOpz/RegOpzWebApp | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import RightPane from './RightPane';
export default class DashboardIndex extends Component {
render() {
return (
<div>
<RightPane />
</div>
)
}
componentDidMount() {
document.title = "RegOpz Dashboard | Capture Report Template ";
}
}
|
src/views/notifications/alerts/Alerts.js | mrholek/CoreUI-React | import React from 'react'
import {
CAlert,
CAlertHeading,
CAlertLink,
CCard,
CCardBody,
CCardHeader,
CCol,
CRow,
} from '@coreui/react'
import { DocsCallout, DocsExample } from 'src/components'
const Alerts = () => {
return (
<CRow>
<CCol xs={12}>
<DocsCallout name="Alert" href="components/alert" />
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>React Alert</strong>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
React Alert is prepared for any length of text, as well as an optional close button.
For a styling, use one of the <strong>required</strong> contextual <code>color</code>{' '}
props (e.g., <code>primary</code>). For inline dismissal, use the{' '}
<a href="https://coreui.io/react/docs/4.0/components/alert#dismissing">
dismissing prop
</a>
.
</p>
<DocsExample href="components/alert">
<CAlert color="primary">A simple primary alert—check it out!</CAlert>
<CAlert color="secondary">A simple secondary alert—check it out!</CAlert>
<CAlert color="success">A simple success alert—check it out!</CAlert>
<CAlert color="danger">A simple danger alert—check it out!</CAlert>
<CAlert color="warning">A simple warning alert—check it out!</CAlert>
<CAlert color="info">A simple info alert—check it out!</CAlert>
<CAlert color="light">A simple light alert—check it out!</CAlert>
<CAlert color="dark">A simple dark alert—check it out!</CAlert>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>React Alert</strong> <small>Link color</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
Use the <code><CAlertLink></code> component to immediately give matching colored
links inside any alert.
</p>
<DocsExample href="components/alert#link-color">
<CAlert color="primary">
A simple primary alert with <CAlertLink href="#">an example link</CAlertLink>. Give
it a click if you like.
</CAlert>
<CAlert color="secondary">
A simple secondary alert with <CAlertLink href="#">an example link</CAlertLink>.
Give it a click if you like.
</CAlert>
<CAlert color="success">
A simple success alert with <CAlertLink href="#">an example link</CAlertLink>. Give
it a click if you like.
</CAlert>
<CAlert color="danger">
A simple danger alert with <CAlertLink href="#">an example link</CAlertLink>. Give
it a click if you like.
</CAlert>
<CAlert color="warning">
A simple warning alert with <CAlertLink href="#">an example link</CAlertLink>. Give
it a click if you like.
</CAlert>
<CAlert color="info">
A simple info alert with <CAlertLink href="#">an example link</CAlertLink>. Give it
a click if you like.
</CAlert>
<CAlert color="light">
A simple light alert with <CAlertLink href="#">an example link</CAlertLink>. Give it
a click if you like.
</CAlert>
<CAlert color="dark">
A simple dark alert with <CAlertLink href="#">an example link</CAlertLink>. Give it
a click if you like.
</CAlert>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>React Alert</strong> <small>Additional content</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
Alert can also incorporate supplementary components & elements like heading,
paragraph, and divider.
</p>
<DocsExample href="components/alert#additional-content">
<CAlert color="success">
<CAlertHeading tag="h4">Well done!</CAlertHeading>
<p>
Aww yeah, you successfully read this important alert message. This example text is
going to run a bit longer so that you can see how spacing within an alert works
with this kind of content.
</p>
<hr />
<p className="mb-0">
Whenever you need to, be sure to use margin utilities to keep things nice and
tidy.
</p>
</CAlert>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>React Alert</strong> <small>Dismissing</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
Alerts can also be easily dismissed. Just add the <code>dismissible</code> prop.
</p>
<DocsExample href="components/alert#dismissing">
<CAlert
color="warning"
dismissible
onClose={() => {
alert('👋 Well, hi there! Thanks for dismissing me.')
}}
>
<strong>Go right ahead</strong> and click that dimiss over there on the right.
</CAlert>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
</CRow>
)
}
export default Alerts
|
pages/api/input.js | cherniavskii/material-ui | import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './input.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
|
test/regressions/tests/List/IconListItem.js | cherniavskii/material-ui | // @flow
import React from 'react';
import Icon from 'material-ui/Icon';
import { ListItem, ListItemText, ListItemIcon } from 'material-ui/List';
export default function IconListItem() {
return (
<div style={{ backgroundColor: '#fff', width: 300 }}>
<ListItem>
<ListItemIcon>
<Icon>phone</Icon>
</ListItemIcon>
<ListItemText primary="Icon" />
</ListItem>
<ListItem>
<ListItemText inset primary="Inset" secondary="Secondary" />
</ListItem>
<ListItem dense>
<ListItemIcon>
<Icon>phone</Icon>
</ListItemIcon>
<ListItemText primary="Icon" />
</ListItem>
<ListItem dense>
<ListItemText inset primary="Inset" secondary="Secondary" />
</ListItem>
</div>
);
}
|
react-src/catalog/components/voyages/layouts/VoyageImageMinimalist.js | gabzon/experiensa | import React from 'react';
export default class CatalogVoyageMinimalist extends React.Component {
constructor(){
super()
}
render() {
let voyageImage
let imgSrc
if(this.props.voyage.cover_image){
let imageFeatureImage = this.props.voyage.cover_image.feature_image
let imageGallery = this.props.voyage.cover_image.gallery
if(imageFeatureImage){
imgSrc = imageFeatureImage
voyageImage = <img src={imgSrc}/>
}else{
if(typeof imageGallery !== 'undefined' && imageGallery.length > 0 ){
imgSrc = imageGallery[0]
voyageImage = <img src={imgSrc}/>
}else{
imgSrc = sage_vars.stylesheet_directory_uri + '/assets/images/travel-no-image.jpg'
voyageImage = <img src={imgSrc}/>
}
}
}else{
imgSrc = sage_vars.stylesheet_directory_uri + '/assets/images/travel-no-image.jpg'
voyageImage = <img src={imgSrc}/>
}
return (
<div className="image catalog-image">
{voyageImage}
</div>
);
}
}
|
fields/types/relationship/RelationshipColumn.js | frontyard/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
const moreIndicatorStyle = {
color: '#bbb',
fontSize: '.8rem',
fontWeight: 500,
marginLeft: 8,
};
var RelationshipColumn = React.createClass({
displayName: 'RelationshipColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderMany (value) {
if (!value || !value.length) return;
const refList = this.props.col.field.refList;
const items = [];
for (let i = 0; i < 3; i++) {
if (!value[i]) break;
if (i) {
items.push(<span key={'comma' + i}>, </span>);
}
items.push(
<ItemsTableValue interior truncate={false} key={'anchor' + i} to={Keystone.adminPath + '/' + refList.path + '/' + value[i].id}>
{value[i].name}
</ItemsTableValue>
);
}
if (value.length > 3) {
items.push(<span key="more" style={moreIndicatorStyle}>[...{value.length - 3} more]</span>);
}
return (
<ItemsTableValue field={this.props.col.type}>
{items}
</ItemsTableValue>
);
},
renderValue (value) {
if (!value) return;
const refList = this.props.col.field.refList;
return (
<ItemsTableValue to={Keystone.adminPath + '/' + refList.path + '/' + value.id} padded interior field={this.props.col.type}>
{value.name}
</ItemsTableValue>
);
},
render () {
const value = this.props.data.fields[this.props.col.path];
const many = this.props.col.field.many;
return (
<ItemsTableCell>
{many ? this.renderMany(value) : this.renderValue(value)}
</ItemsTableCell>
);
},
});
module.exports = RelationshipColumn;
|
src/svg-icons/content/text-format.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentTextFormat = (props) => (
<SvgIcon {...props}>
<path d="M5 17v2h14v-2H5zm4.5-4.2h5l.9 2.2h2.1L12.75 4h-1.5L6.5 15h2.1l.9-2.2zM12 5.98L13.87 11h-3.74L12 5.98z"/>
</SvgIcon>
);
ContentTextFormat = pure(ContentTextFormat);
ContentTextFormat.displayName = 'ContentTextFormat';
ContentTextFormat.muiName = 'SvgIcon';
export default ContentTextFormat;
|
src/components/Context.js | lolatravel/realm-react-redux | import React from 'react';
export const ReactReduxContext = React.createContext('realm');
export default ReactReduxContext;
|
client/src/javascript/components/icons/Limits.js | jfurrow/flood | import React from 'react';
import BaseIcon from './BaseIcon';
export default class Limits extends BaseIcon {
render() {
return (
<svg className={`icon icon--limits ${this.props.className}`} viewBox={this.getViewBox()}>
<path
className="limits__bars--bottom"
d="M24.4,48.5c0,3.3,2.5,6,5.6,6s5.6-2.7,5.6-6V18.6H24.4V48.5z M4.4,48.2c0,3.5,2.5,6.3,5.6,6.3 s5.6-2.8,5.6-6.3v-9.3H4.4V48.2z M44.4,30v18.2c0,3.5,2.5,6.3,5.6,6.3s5.6-2.8,5.6-6.3V30H44.4z"
/>
<path className="limits__bars--top" d="M24.4,18.7v-7.6c0-3.1,2.5-5.5,5.6-5.5s5.6,2.5,5.6,5.5v7.6H24.4z" />
<path className="limits__bars--top" d="M4.4,38.9v-27c0-3.5,2.5-6.3,5.6-6.3s5.6,2.8,5.6,6.3v27H4.4z" />
<path className="limits__bars--top" d="M44.4,29.9V11.8c0-3.5,2.5-6.3,5.6-6.3s5.6,2.8,5.6,6.3v18.1H44.4z" />
<path
className="limits__bars--middle"
d="M22.2,16.4h15.6c1.2,0,2.2,1,2.2,2.2c0,1.2-1,2.2-2.2,2.2H22.2c-1.2,0-2.2-1-2.2-2.2 C20,17.4,21,16.4,22.2,16.4z"
/>
<path
className="limits__bars--middle"
d="M2.2,36.7h15.6c1.2,0,2.2,1,2.2,2.2c0,1.2-1,2.2-2.2,2.2H2.2c-1.2,0-2.2-1-2.2-2.2C0,37.7,1,36.7,2.2,36.7z"
/>
<path
className="limits__bars--middle"
d="M42.2,27.8h15.6c1.2,0,2.2,1,2.2,2.2s-1,2.2-2.2,2.2H42.2c-1.2,0-2.2-1-2.2-2.2S41,27.8,42.2,27.8z"
/>
</svg>
);
}
}
|
pnpm-cached/.pnpm-store/1/registry.npmjs.org/react-bootstrap/0.31.0/es/PageHeader.js | Akkuma/npm-cache-benchmark | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var PageHeader = function (_React$Component) {
_inherits(PageHeader, _React$Component);
function PageHeader() {
_classCallCheck(this, PageHeader);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
PageHeader.prototype.render = function render() {
var _props = this.props,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['className', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(
'div',
_extends({}, elementProps, {
className: classNames(className, classes)
}),
React.createElement(
'h1',
null,
children
)
);
};
return PageHeader;
}(React.Component);
export default bsClass('page-header', PageHeader); |
app/javascript/mastodon/components/autosuggest_emoji.js | pixiv/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import unicodeMapping from '../features/emoji/emoji_unicode_mapping_light';
const assetHost = process.env.CDN_HOST || '';
export default class AutosuggestEmoji extends React.PureComponent {
static propTypes = {
emoji: PropTypes.object.isRequired,
};
render () {
const { emoji } = this.props;
let url;
if (emoji.custom) {
url = emoji.imageUrl;
} else {
const mapping = unicodeMapping[emoji.native] || unicodeMapping[emoji.native.replace(/\uFE0F$/, '')];
if (!mapping) {
return null;
}
url = `${assetHost}/emoji/${mapping.filename}.svg`;
}
return (
<div className='autosuggest-emoji'>
<img
className='emojione'
src={url}
alt={emoji.native || emoji.colons}
/>
{emoji.colons}
</div>
);
}
}
|
src/svg-icons/av/volume-mute.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVolumeMute = (props) => (
<SvgIcon {...props}>
<path d="M7 9v6h4l5 5V4l-5 5H7z"/>
</SvgIcon>
);
AvVolumeMute = pure(AvVolumeMute);
AvVolumeMute.displayName = 'AvVolumeMute';
export default AvVolumeMute;
|
RN/ImageDemo/NewComponent/Find.js | puyanLiu/LPYFramework | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
class Find extends Component {
render() {
return (
<View></View>
);
}
}
module.exports = Find; |
app/components/AuthForm/index.js | prudhvisays/newsb | import React from 'react';
import { changeForm } from '../../containers/AuthPage/actions';
import { connect } from 'react-redux';
import ErrorStyle from './ErrorStyle';
class AuthForm extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.changeUsername = this.changeUsername.bind(this);
this.changePassword = this.changePassword.bind(this);
this.emitChange = this.emitChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
changeUsername(e) {
this.emitChange({ ...this.props.data, username: e.target.value });
}
changePassword(e) {
this.emitChange({ ...this.props.data, password: e.target.value });
}
emitChange(newFormState) {
this.props.onChangeForm(newFormState);
}
onSubmit(e){
e.preventDefault();
this.props.onSubmit(this.props.data.username, this.props.data.password, this.props.userRole);
}
render() {
return (
<div className="ink-flex push-center form-style">
{ this.props.stateError && <ErrorStyle>{this.props.stateError.message}</ErrorStyle>}
<div className="all-70">
<form onSubmit={this.onSubmit}>
<div className="ink-flex push-middle vertical">
<div className="input-div"><input type="text" placeholder="Username" onChange={this.changeUsername}></input></div>
<div className="input-div"><input type="password" placeholder="Password" onChange={this.changePassword}></input></div>
<button type="submit">Login</button>
</div>
</form>
</div>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return {
onChangeForm: (newFormState) => { dispatch(changeForm(newFormState)); },
};
}
export default connect(null, mapDispatchToProps)(AuthForm);
|
assets/jqwidgets/demos/react/app/complexinput/righttoleftlayout/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxComplexInput from '../../../jqwidgets-react/react_jqxcomplexinput.js';
class App extends React.Component {
render() {
return (
<JqxComplexInput ref='myComplexInput'
width={250} height={25} value={'15 + 7.2i'}
spinButtons={true} rtl={true}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
react-dixie-memory-considerate-loading/src/components/Header/index.js | GoogleChromeLabs/adaptive-loading | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 './header.css';
import logo from '../../assets/images/logo.webp';
import hamburger from '../../assets/icons/hamburger.svg';
const Header = () => {
return (
<div className='header'>
<div className='bottom-left'>
<button className='menu-button'><img src={hamburger} width='24' height='18' alt='hamburger menu' /></button>
<nav className='header-nav'>
<a href='/' className='header-nav-item'>Home</a>
<a href='https://dixiemech.store/' className='header-nav-item'>Shop</a>
<a href='/groupbuys' className='header-nav-item'>GroupBuys</a>
<a href='/news' className='header-nav-item'>News</a>
<a href='https://dixiemech.store/pages/faq' className='header-nav-item'>Help</a>
</nav>
</div>
<div className='bottom-center'>
<a href='https://dixiemech.com/gmkdracula/' className='header-branding'>
<img src={logo} alt='Dixie Mech' className='header-branding-logo' />
</a>
</div>
<div className='bottom-right'>
<nav className='header-nav'>
<a href='https://discordapp.com/invite/KaZjphH' target='_blank' rel='noopener noreferrer' className='header-nav-item'>Discord</a>
<a href='https://dixiemech.store/account/login' className='header-nav-item'>Account</a>
<a href='https://dixiemech.store/search' className='header-nav-item'>Search</a>
<a href='https://dixiemech.store/cart' className='header-nav-item'>Cart</a>
</nav>
</div>
</div>
);
};
export default Header;
|
src/Game/UI/Updating.js | digijin/space-station-sim | //@flow
import React from 'react';
export default class Updating extends React.Component {
componentDidMount() {
setInterval(() => {
this.forceUpdate();
}, 1000)
}
}
|
fields/types/html/editor/info-box/info-box-editing-block.js | nickhsine/keystone | 'use strict';
import { convertToRaw } from 'draft-js';
import DraftConverter from '../draft-converter';
import EntityEditingBlockMixin from '../mixins/entity-editing-block-mixin';
import React from 'react';
class InfoBoxEditingBlock extends EntityEditingBlockMixin(React.Component) {
constructor (props) {
super(props);
this.state.editorState = this._initEditorState(props.draftRawObj);
}
// overwrite EntityEditingBlock._composeEditingFields
_composeEditingFields (props) {
return {
title: {
type: 'text',
value: props.title,
},
body: {
type: 'html',
value: props.body,
},
};
}
// overwrite EntityEditingBlock._decomposeEditingFields
_decomposeEditingFields (fields) {
let { editorState } = this.state;
const content = convertToRaw(editorState.getCurrentContent());
const cHtml = DraftConverter.convertToHtml(content);
return {
title: fields.title.value,
body: cHtml,
draftRawObj: content,
};
}
// overwrite EntityEditingBlock._handleEditingFieldChange
_handleEditingFieldChange (field, e) {
if (field === 'body') {
return;
}
return super._handleEditingFieldChange(field, e);
}
};
InfoBoxEditingBlock.displayName = 'InfoBoxEditingBlock';
InfoBoxEditingBlock.propTypes = {
body: React.PropTypes.string,
draftRawObj: React.PropTypes.object,
isModalOpen: React.PropTypes.bool,
onToggle: React.PropTypes.func.isRequired,
title: React.PropTypes.string,
toggleModal: React.PropTypes.func,
};
InfoBoxEditingBlock.defaultProps = {
body: '',
draftRawObj: null,
isModalOpen: false,
title: '',
};
export default InfoBoxEditingBlock;
|
src/components/ContactForm.js | benruehl/gatsby-kruemelkiste | import React from 'react'
import ReactDOM from 'react-dom';
import styled from 'styled-components'
import Button from '../components/Button'
import strings from '../../data/strings'
const InputGroup = styled.div`
display: flex;
flex-direction: row;
align-items: center;
width: 100%;
margin-bottom: 1.5em;
input, textarea {
flex: 1 1 auto;
margin-left: 1em;
border: 0 solid transparent;
padding: .5em;
:hover {
box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
}
:focus {
box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
outline: none;
}
}
label {
text-align: right;
flex-basis: 4.6em;
}
@media (max-width: 500px) {
flex-direction: column;
align-items: stretch;
input, textarea {
margin-left: 0;
}
label {
text-align: left;
flex-basis: auto;
}
}
`
class Contact extends React.Component {
submit() {
var formData = {
name: ReactDOM.findDOMNode(this.refs.nameInput).value,
mail: ReactDOM.findDOMNode(this.refs.mailInput).value,
message: ReactDOM.findDOMNode(this.refs.messageInput).value,
}
if (formData.message != '' && formData.message.trim() == '') {
return false;
}
this.submitElement.click()
}
render() {
return (
<form
action={'https://formspree.io/' + strings.emailAddress}
method="POST">
<input type="hidden" name="_language" value="de" />
<input type="hidden" name="_subject" value="Interesse an der Krümelkiste" />
<input type="hidden" name="_next" value="//steffis-kruemelkiste.netlify.com/contact-success" />
<div
css={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}>
<InputGroup>
<label htmlFor='nameInput'>
Name
</label>
<input
className='materialCard1'
type='text'
id='nameInput'
name='name'
ref='nameInput'/>
</InputGroup>
<InputGroup>
<label htmlFor='mailInput'>
E-Mail
</label>
<input
className='materialCard1'
type='email'
id='mailInput'
name='_replyto'
ref='mailInput'/>
</InputGroup>
<InputGroup>
<label
htmlFor='messageInput'
css={{
alignSelf: 'flex-start',
marginTop: '.5em',
}}>
Nachricht
</label>
<textarea
className='materialCard1'
type='text'
id='messageInput'
name='message'
ref='messageInput'
rows='5'
maxlength='1000'
required/>
</InputGroup>
<p
css={{
color: '#a0a0a0',
textAlign: 'justify',
marginTop: '1em',
}}>
Beim Abschicken werden Sie zum Schutz vor Spam kurzzeitig an den externen Dienst Formspree weitergeleitet. Danach kehren Sie automatisch hierher zurück. Die eingegebenen Daten werden von mir nicht an Dritte weitergegeben.
</p>
<div
css={{
marginTop: '2em',
}}>
<input
type='submit'
ref={input => this.submitElement = input}
value='Abschicken'
style={{ display: 'none' }}/>
<Button
caption='Abschicken'
onClick={this.submit.bind(this)}/>
</div>
</div>
</form>
)
}
}
export default Contact |
src/index.js | D-TUCKER/react-fartscroll | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
app/javascript/mastodon/features/account_timeline/components/moved_note.js | increments/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import AvatarOverlay from '../../../components/avatar_overlay';
import DisplayName from '../../../components/display_name';
export default class MovedNote extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
from: ImmutablePropTypes.map.isRequired,
to: ImmutablePropTypes.map.isRequired,
};
handleAccountClick = e => {
if (e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/accounts/${this.props.to.get('id')}`);
}
e.stopPropagation();
}
render () {
const { from, to } = this.props;
const displayNameHtml = { __html: from.get('display_name_html') };
return (
<div className='account__moved-note'>
<div className='account__moved-note__message'>
<div className='account__moved-note__icon-wrapper'><i className='fa fa-fw fa-suitcase account__moved-note__icon' /></div>
<FormattedMessage id='account.moved_to' defaultMessage='{name} has moved to:' values={{ name: <bdi><strong dangerouslySetInnerHTML={displayNameHtml} /></bdi> }} />
</div>
<a href={to.get('url')} onClick={this.handleAccountClick} className='detailed-status__display-name'>
<div className='detailed-status__display-avatar'><AvatarOverlay account={to} friend={from} /></div>
<DisplayName account={to} />
</a>
</div>
);
}
}
|
client/extensions/woocommerce/app/store-stats/referrers/index.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { find } from 'lodash';
import { localize } from 'i18n-calypso';
import page from 'page';
/**
* Internal dependencies
*/
import QuerySiteStats from 'components/data/query-site-stats';
import { getSelectedSiteId, getSelectedSiteSlug } from 'state/ui/selectors';
import { getEndPeriod, getWidgetPath } from 'woocommerce/app/store-stats/utils';
import StoreStatsPeriodNav from 'woocommerce/app/store-stats/store-stats-period-nav';
import JetpackColophon from 'components/jetpack-colophon';
import Main from 'components/main';
import Module from 'woocommerce/app/store-stats/store-stats-module';
import SearchCard from 'components/search-card';
import StoreStatsReferrerWidget from 'woocommerce/app/store-stats/store-stats-referrer-widget';
import StoreStatsReferrerConvWidget from 'woocommerce/app/store-stats/store-stats-referrer-conv-widget';
import { sortBySales } from 'woocommerce/app/store-stats/referrers/helpers';
import PageViewTracker from 'lib/analytics/page-view-tracker';
import titlecase from 'to-title-case';
import getStoreReferrersByDate from 'state/selectors/get-store-referrers-by-date';
import Chart from './chart';
import { UNITS, noDataMsg } from 'woocommerce/app/store-stats/constants';
const STAT_TYPE = 'statsStoreReferrers';
const LIMIT = 10;
class Referrers extends Component {
static propTypes = {
siteId: PropTypes.number,
query: PropTypes.object.isRequired,
data: PropTypes.array.isRequired,
selectedDate: PropTypes.string,
unit: PropTypes.oneOf( [ 'day', 'week', 'month', 'year' ] ),
slug: PropTypes.string,
limit: PropTypes.number,
};
state = {
filter: '',
selectedReferrer: {},
};
UNSAFE_componentWillReceiveProps( nextProps ) {
this.setData( nextProps, this.state.filter );
}
UNSAFE_componentWillMount() {
this.setData( this.props, this.state.filter );
}
onSearch = str => {
const trimmedStr = str.trim();
if ( trimmedStr === '' ) {
const { unit, slug } = this.props;
const basePath = '/store/stats/referrers';
const {
queryParams: { referrer, ...queryParams },
} = this.props; // eslint-disable-line no-unused-vars
const widgetPath = getWidgetPath( unit, slug, queryParams );
this.state.filter = '';
this.state.selectedReferrer = {};
page( `${ basePath }${ widgetPath }` );
}
this.setData( this.props, trimmedStr );
};
getFilteredData = ( filter, { data } ) => {
const filteredData = filter
? data.filter( d => d.referrer.toLowerCase().match( filter.toLowerCase() ) )
: data;
return {
filteredSortedData: sortBySales( filteredData ),
unfilteredDataLength: data.length,
};
};
getSelectedReferrer = ( filteredSortedData, { queryParams } ) => {
let selectedReferrerIndex = null;
if ( queryParams.referrer ) {
const selectedReferrer = find( filteredSortedData, ( d, idx ) => {
if ( queryParams.referrer === d.referrer ) {
selectedReferrerIndex = idx;
return true;
}
return false;
} );
return {
selectedReferrer: selectedReferrer || {},
selectedReferrerIndex,
};
}
return {
selectedReferrer: {},
selectedReferrerIndex,
};
};
setData( props, filter ) {
const { filteredSortedData, unfilteredDataLength } = this.getFilteredData( filter, props );
const { selectedReferrer, selectedReferrerIndex } = this.getSelectedReferrer(
filteredSortedData,
props
);
this.setState( {
filter,
filteredSortedData,
unfilteredDataLength,
selectedReferrer,
selectedReferrerIndex,
} );
}
render() {
const { siteId, query, selectedDate, unit, slug, translate, queryParams } = this.props;
const { filter, filteredSortedData, selectedReferrer, selectedReferrerIndex } = this.state;
const endSelectedDate = getEndPeriod( selectedDate, unit );
const title = `${ translate( 'Store Referrers' ) }: ${ queryParams.referrer ||
translate( 'All' ) }`;
const chartFormat = UNITS[ unit ].chartFormat;
const periodNavQueryParams = Object.assign(
{ referrer: selectedReferrer.referrer },
queryParams
);
const selectOrFilter = selectedReferrer ? selectedReferrer.referrer : filter;
return (
<Main className="referrers woocommerce" wideLayout>
<PageViewTracker
path={ `/store/stats/referrers/${ unit }/:site` }
title={ `Store > Stats > Referrers > ${ titlecase( unit ) }` }
/>
{ siteId && <QuerySiteStats statType={ STAT_TYPE } siteId={ siteId } query={ query } /> }
<StoreStatsPeriodNav
type="referrers"
selectedDate={ selectedDate }
unit={ unit }
slug={ slug }
query={ query }
statType={ STAT_TYPE }
title={ title }
queryParams={ periodNavQueryParams }
/>
<Module
className="referrers__search"
siteId={ siteId }
emptyMessage={ noDataMsg }
query={ query }
statType={ STAT_TYPE }
>
<SearchCard
className={ 'referrers__search-filter' }
onSearch={ this.onSearch }
placeholder="Filter Store Referrers"
value={ selectOrFilter }
initialValue={ selectOrFilter }
/>
<div className="referrers__widgets">
<StoreStatsReferrerWidget
fetchedData={ filteredSortedData }
unit={ unit }
siteId={ siteId }
query={ query }
statType={ STAT_TYPE }
endSelectedDate={ endSelectedDate }
queryParams={ queryParams }
slug={ slug }
limit={ 5 }
pageType="referrers"
paginate
selectedIndex={ selectedReferrerIndex }
selectedReferrer={ selectedReferrer.referrer }
/>
</div>
</Module>
<Module
className="referrers__chart"
siteId={ siteId }
emptyMessage={ noDataMsg }
query={ query }
statType={ STAT_TYPE }
>
<Chart
selectedDate={ endSelectedDate }
selectedReferrer={ selectedReferrer.referrer }
chartFormat={ chartFormat }
unit={ unit }
slug={ slug }
siteId={ siteId }
statType
query={ query }
/>
</Module>
<Module
className="referrers__search"
siteId={ siteId }
emptyMessage={ noDataMsg }
query={ query }
statType={ STAT_TYPE }
>
<div className="referrers__widgets">
<StoreStatsReferrerConvWidget
fetchedData={ filteredSortedData }
unit={ unit }
siteId={ siteId }
query={ query }
statType={ STAT_TYPE }
endSelectedDate={ endSelectedDate }
queryParams={ queryParams }
slug={ slug }
limit={ LIMIT }
pageType="referrers"
paginate
selectedIndex={ selectedReferrerIndex }
selectedReferrer={ selectedReferrer.referrer }
/>
</div>
</Module>
<JetpackColophon />
</Main>
);
}
}
export default connect( ( state, { query, selectedDate, unit } ) => {
const siteId = getSelectedSiteId( state );
return {
slug: getSelectedSiteSlug( state ),
siteId,
data: getStoreReferrersByDate( state, {
query,
siteId,
statType: STAT_TYPE,
endSelectedDate: getEndPeriod( selectedDate, unit ),
} ),
};
} )( localize( Referrers ) );
|
examples/js/custom/insert-modal/default-custom-insert-modal-footer.js | powerhome/react-bootstrap-table | /* eslint max-len: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-alert: 0 */
/* eslint no-console: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn, InsertModalFooter } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
export default class DefaultCustomInsertModalFooterTable extends React.Component {
beforeClose(e) {
alert(`[Custom Event]: Modal close event triggered!`);
}
beforeSave(e) {
alert(`[Custom Event]: Modal save event triggered!`);
}
handleModalClose(closeModal) {
// Custom your onCloseModal event here,
// it's not necessary to implement this function if you have no any process before modal close
console.log('This is my custom function for modal close event');
closeModal();
}
handleSave(save) {
// Custom your onSave event here,
// it's not necessary to implement this function if you have no any process before save
console.log('This is my custom function for save event');
save();
}
createCustomModalFooter = (closeModal, save) => {
return (
<InsertModalFooter
className='my-custom-class'
saveBtnText='CustomSaveText'
closeBtnText='CustomCloseText'
closeBtnContextual='btn-warning'
saveBtnContextual='btn-success'
closeBtnClass='my-close-btn-class'
saveBtnClass='my-save-btn-class'
beforeClose={ this.beforeClose }
beforeSave={ this.beforeSave }
onModalClose={ () => this.handleModalClose(closeModal) }
onSave={ () => this.handleSave(save) }/>
);
// If you want have more power to custom the child of InsertModalFooter,
// you can do it like following
// return (
// <InsertModalFooter
// onModalClose={ () => this.handleModalClose(closeModal) }
// onSave={ () => this.handleSave(save) }>
// { ... }
// </InsertModalFooter>
// );
}
render() {
const options = {
insertModalFooter: this.createCustomModalFooter
};
return (
<BootstrapTable data={ products } options={ options } insertRow>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/client/admin/routes.js | Restuta/rcn.io | import React from 'react'
import { Route } from 'react-router'
import AdminRoot from './AdminRoot.js'
import CreateEventId from 'admin/events/CreateEventId.jsx'
import UploadFlyer from 'admin/events/UploadFlyer.jsx'
//alternative way is to define route root as /widgets and remove root in get-routes.js
const routes = (
<Route path="/" component={AdminRoot}>
<Route path="events/create-id" component={CreateEventId} />
<Route path="events/upload-flyer" component={UploadFlyer} />
</Route>
)
export default routes
|
src/repository/screens/repository.screen.js | Antoine38660/git-point | /* eslint-disable no-shadow */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { StyleSheet, RefreshControl, Share } from 'react-native';
import { ListItem } from 'react-native-elements';
import ActionSheet from 'react-native-actionsheet';
import {
ViewContainer,
LoadingRepositoryProfile,
RepositoryProfile,
MembersList,
SectionList,
ParallaxScroll,
LoadingUserListItem,
UserListItem,
IssueListItem,
LoadingMembersList,
LoadingModal,
} from 'components';
import { translate, openURLInView } from 'utils';
import { colors, fonts } from 'config';
import {
getRepositoryInfo,
changeStarStatusRepo,
forkRepo,
subscribeToRepo,
unSubscribeToRepo,
} from '../repository.action';
const mapStateToProps = state => ({
username: state.auth.user.login,
locale: state.auth.locale,
repository: state.repository.repository,
contributors: state.repository.contributors,
issues: state.repository.issues,
starred: state.repository.starred,
forked: state.repository.forked,
subscribed: state.repository.subscribed,
hasReadMe: state.repository.hasReadMe,
isPendingRepository: state.repository.isPendingRepository,
isPendingContributors: state.repository.isPendingContributors,
isPendingIssues: state.repository.isPendingIssues,
isPendingCheckReadMe: state.repository.isPendingCheckReadMe,
isPendingCheckStarred: state.repository.isPendingCheckStarred,
isPendingFork: state.repository.isPendingFork,
isPendingSubscribe: state.repository.isPendingSubscribe,
});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
getRepositoryInfo,
changeStarStatusRepo,
forkRepo,
subscribeToRepo,
unSubscribeToRepo,
},
dispatch
);
const styles = StyleSheet.create({
listTitle: {
color: colors.black,
...fonts.fontPrimary,
},
listContainerStyle: {
borderBottomColor: colors.greyLight,
borderBottomWidth: 1,
},
});
class Repository extends Component {
props: {
getRepositoryInfo: Function,
changeStarStatusRepo: Function,
forkRepo: Function,
// repositoryName: string,
repository: Object,
contributors: Array,
hasReadMe: boolean,
issues: Array,
starred: boolean,
// forked: boolean,
isPendingRepository: boolean,
isPendingContributors: boolean,
isPendingCheckReadMe: boolean,
isPendingIssues: boolean,
isPendingCheckStarred: boolean,
isPendingFork: boolean,
isPendingSubscribe: boolean,
// isPendingCheckForked: boolean,
navigation: Object,
username: string,
locale: string,
subscribed: boolean,
subscribeToRepo: Function,
unSubscribeToRepo: Function,
};
state: {
refreshing: boolean,
};
constructor(props) {
super(props);
this.state = {
refreshing: false,
};
}
componentDidMount() {
const {
repository: repo,
repositoryUrl: repoUrl,
} = this.props.navigation.state.params;
this.props.getRepositoryInfo(repo ? repo.url : repoUrl);
}
showMenuActionSheet = () => {
this.ActionSheet.show();
};
handlePress = index => {
const {
starred,
subscribed,
repository,
changeStarStatusRepo,
forkRepo,
navigation,
username,
} = this.props;
const showFork = repository.owner.login !== username;
if (index === 0) {
changeStarStatusRepo(repository.owner.login, repository.name, starred);
} else if (index === 1 && showFork) {
forkRepo(repository.owner.login, repository.name).then(json => {
navigation.navigate('Repository', { repository: json });
});
} else if ((index === 2 && showFork) || (index === 1 && !showFork)) {
const subscribeMethod = !subscribed
? this.props.subscribeToRepo
: this.props.unSubscribeToRepo;
subscribeMethod(repository.owner.login, repository.name);
} else if ((index === 3 && showFork) || (index === 2 && !showFork)) {
this.shareRepository(repository);
} else if ((index === 4 && showFork) || (index === 3 && !showFork)) {
openURLInView(repository.html_url);
}
};
fetchRepoInfo = () => {
const {
repository: repo,
repositoryUrl: repoUrl,
} = this.props.navigation.state.params;
this.setState({ refreshing: true });
this.props.getRepositoryInfo(repo ? repo.url : repoUrl).then(() => {
this.setState({ refreshing: false });
});
};
shareRepository = repository => {
const { locale } = this.props;
const title = translate('repository.main.shareRepositoryTitle', locale, {
repoName: repository.name,
});
Share.share(
{
title,
message: translate('repository.main.shareRepositoryMessage', locale, {
repoName: repository.name,
repoUrl: repository.html_url,
}),
url: undefined,
},
{
dialogTitle: title,
excludedActivityTypes: [],
}
);
};
render() {
const {
repository,
contributors,
hasReadMe,
issues,
starred,
locale,
isPendingRepository,
isPendingContributors,
isPendingCheckReadMe,
isPendingIssues,
isPendingCheckStarred,
isPendingFork,
isPendingSubscribe,
navigation,
username,
subscribed,
} = this.props;
const { refreshing } = this.state;
const initalRepository = navigation.state.params.repository;
const pulls = issues.filter(issue => issue.hasOwnProperty('pull_request')); // eslint-disable-line no-prototype-builtins
const pureIssues = issues.filter(issue => {
// eslint-disable-next-line no-prototype-builtins
return !issue.hasOwnProperty('pull_request');
});
const openPulls = pulls.filter(pull => pull.state === 'open');
const openIssues = pureIssues.filter(issue => issue.state === 'open');
const showFork =
repository && repository.owner && repository.owner.login !== username;
const repositoryActions = [
starred
? translate('repository.main.unstarAction', locale)
: translate('repository.main.starAction', locale),
subscribed
? translate('repository.main.unwatchAction', locale)
: translate('repository.main.watchAction', locale),
translate('repository.main.shareAction', locale),
translate('common.openInBrowser', locale),
];
if (showFork) {
repositoryActions.splice(
1,
0,
translate('repository.main.forkAction', locale)
);
}
const loader = isPendingFork ? <LoadingModal /> : null;
const isSubscribed =
isPendingRepository || isPendingSubscribe ? false : subscribed;
const isStarred =
isPendingRepository || isPendingCheckStarred ? false : starred;
const showReadMe = !isPendingCheckReadMe && hasReadMe;
return (
<ViewContainer>
{loader}
<ParallaxScroll
renderContent={() => {
if (isPendingRepository && !initalRepository) {
return <LoadingRepositoryProfile locale={locale} />;
}
return (
<RepositoryProfile
repository={isPendingRepository ? initalRepository : repository}
starred={isStarred}
loading={isPendingRepository}
navigation={navigation}
subscribed={isSubscribed}
locale={locale}
/>
);
}}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={this.fetchRepoInfo}
/>
}
stickyTitle={repository.name}
showMenu={!isPendingRepository && !isPendingCheckStarred}
menuAction={this.showMenuActionSheet}
navigation={navigation}
navigateBack
>
{initalRepository &&
!initalRepository.owner &&
isPendingRepository && (
<SectionList
title={translate('repository.main.ownerTitle', locale)}
>
<LoadingUserListItem />
</SectionList>
)}
{!(initalRepository && initalRepository.owner) &&
(repository && repository.owner) &&
!isPendingRepository && (
<SectionList
title={translate('repository.main.ownerTitle', locale)}
>
<UserListItem user={repository.owner} navigation={navigation} />
</SectionList>
)}
{initalRepository &&
initalRepository.owner && (
<SectionList
title={translate('repository.main.ownerTitle', locale)}
>
<UserListItem
user={initalRepository.owner}
navigation={navigation}
/>
</SectionList>
)}
{(isPendingRepository || isPendingContributors) && (
<LoadingMembersList
title={translate('repository.main.contributorsTitle', locale)}
/>
)}
{!isPendingContributors && (
<MembersList
title={translate('repository.main.contributorsTitle', locale)}
members={contributors}
noMembersMessage={translate(
'repository.main.noContributorsMessage',
locale
)}
navigation={navigation}
/>
)}
<SectionList title={translate('repository.main.sourceTitle', locale)}>
{showReadMe && (
<ListItem
title={translate('repository.main.readMe', locale)}
leftIcon={{
name: 'book',
color: colors.grey,
type: 'octicon',
}}
titleStyle={styles.listTitle}
containerStyle={styles.listContainerStyle}
onPress={() =>
navigation.navigate('ReadMe', {
repository,
})}
underlayColor={colors.greyLight}
/>
)}
<ListItem
title={translate('repository.main.viewSource', locale)}
titleStyle={styles.listTitle}
containerStyle={styles.listContainerStyle}
leftIcon={{
name: 'code',
color: colors.grey,
type: 'octicon',
}}
onPress={() =>
navigation.navigate('RepositoryCodeList', {
title: translate('repository.codeList.title', locale),
topLevel: true,
})}
underlayColor={colors.greyLight}
/>
</SectionList>
{!repository.fork &&
repository.has_issues && (
<SectionList
loading={isPendingIssues}
title={translate('repository.main.issuesTitle', locale)}
noItems={openIssues.length === 0}
noItemsMessage={
pureIssues.length === 0
? translate('repository.main.noIssuesMessage', locale)
: translate('repository.main.noOpenIssuesMessage', locale)
}
showButton
buttonTitle={
pureIssues.length > 0
? translate('repository.main.viewAllButton', locale)
: translate('repository.main.newIssueButton', locale)
}
buttonAction={() => {
if (pureIssues.length > 0) {
navigation.navigate('IssueList', {
title: translate('repository.issueList.title', locale),
type: 'issue',
issues: pureIssues,
});
} else {
navigation.navigate('NewIssue', {
title: translate('issue.newIssue.title', locale),
});
}
}}
>
{openIssues
.slice(0, 3)
.map(item => (
<IssueListItem
key={item.id}
type="issue"
issue={item}
navigation={navigation}
/>
))}
</SectionList>
)}
<SectionList
loading={isPendingIssues}
title={translate('repository.main.pullRequestTitle', locale)}
noItems={openPulls.length === 0}
noItemsMessage={
pulls.length === 0
? translate('repository.main.noPullRequestsMessage', locale)
: translate('repository.main.noOpenPullRequestsMessage', locale)
}
showButton={pulls.length > 0}
buttonTitle={translate('repository.main.viewAllButton', locale)}
buttonAction={() =>
navigation.navigate('PullList', {
title: translate('repository.pullList.title', locale),
type: 'pull',
issues: pulls,
})}
>
{openPulls
.slice(0, 3)
.map(item => (
<IssueListItem
key={item.id}
type="pull"
issue={item}
navigation={navigation}
locale={locale}
/>
))}
</SectionList>
</ParallaxScroll>
<ActionSheet
ref={o => {
this.ActionSheet = o;
}}
title={translate('repository.main.repoActions', locale)}
options={[...repositoryActions, translate('common.cancel', locale)]}
cancelButtonIndex={repositoryActions.length}
onPress={this.handlePress}
/>
</ViewContainer>
);
}
}
export const RepositoryScreen = connect(mapStateToProps, mapDispatchToProps)(
Repository
);
|
src/form/SelectField.js | rodrigocipriani/br-react-utils | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
class SelectFieldInput extends Component {
static propTypes = {
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
label: PropTypes.string,
data: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.number.isRequired,
text: PropTypes.string.isRequired,
})),
};
static defaultProps = {
sizes: '',
};
render() {
const { value, label, data } = this.props;
return (
<SelectField { ...this.props } floatingLabelStyle={ style.label } floatingLabelText={ label } value={ value } >
{data && data.map((item, key) => (
<MenuItem { ...item } value={ item.value } primaryText={ item.text } key={ key } />
))}
</SelectField>
);
}
}
const style = {
label: {
fontSize: '1.5em',
color: '#666',
left: 0,
},
};
export default SelectFieldInput;
|
client/src/lists/fields/helpers.js | Mailtrain-org/mailtrain | 'use strict';
import React from 'react';
export function getFieldTypes(t) {
const fieldTypes = {
text: {
label: t('text')
},
website: {
label: t('website')
},
longtext: {
label: t('multilineText')
},
gpg: {
label: t('gpgPublicKey')
},
number: {
label: t('number')
},
'checkbox-grouped': {
label: t('checkboxesFromOptionFields')
},
'radio-grouped': {
label: t('radioButtonsFromOptionFields')
},
'dropdown-grouped': {
label: t('dropDownFromOptionFields')
},
'radio-enum': {
label: t('radioButtonsEnumerated')
},
'dropdown-enum': {
label: t('dropDownEnumerated')
},
'date': {
label: t('date')
},
'birthday': {
label: t('birthday')
},
json: {
label: t('jsonValueForCustomRendering')
},
option: {
label: t('option')
}
};
return fieldTypes;
}
|
app/components/pipeline/schedules/Form.js | buildkite/frontend | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import FormCheckbox from 'app/components/shared/FormCheckbox';
import FormTextField from 'app/components/shared/FormTextField';
import FormTextarea from 'app/components/shared/FormTextarea';
import ValidationErrors from 'app/lib/ValidationErrors';
class Form extends React.Component {
static propTypes = {
cronline: PropTypes.string,
label: PropTypes.string,
commit: PropTypes.string,
branch: PropTypes.string,
message: PropTypes.string,
enabled: PropTypes.bool,
env: PropTypes.string,
errors: PropTypes.array,
pipeline: PropTypes.shape({
defaultBranch: PropTypes.string.isRequired
}).isRequired
};
static defaultProps = {
enabled: true
};
componentDidMount() {
this.labelTextField.focus();
}
render() {
const errors = new ValidationErrors(this.props.errors);
return (
<div>
<FormTextField
label="Description"
help="The description for the schedule (supports :emoji:)"
required={true}
errors={errors.findForField("label")}
defaultValue={this.props.label}
ref={(labelTextField) => this.labelTextField = labelTextField}
/>
<FormTextField
label="Cron Interval"
help={<span>The interval for when builds will be created, in UTC, using crontab format. See the <a className="lime" href="/docs/builds/scheduled-builds">Scheduled Builds</a> documentation for more information and examples.</span>}
required={true}
errors={errors.findForField("cronline")}
defaultValue={this.props.cronline}
ref={(cronlineTextField) => this.cronlineTextField = cronlineTextField}
/>
<FormTextField
label="Build Message"
help="The message to use for the build."
errors={errors.findForField("message")}
defaultValue={this.props.message || "Scheduled build"}
required={true}
ref={(messageTextField) => this.messageTextField = messageTextField}
/>
<FormTextField
label="Build Commit"
help="The commit ref to use for the build."
errors={errors.findForField("commit")}
defaultValue={this.props.commit || "HEAD"}
required={true}
ref={(commitTextField) => this.commitTextField = commitTextField}
/>
<FormTextField
label="Build Branch"
help="The branch to use for the build."
errors={errors.findForField("branch")}
defaultValue={this.props.branch || this.props.pipeline.defaultBranch}
required={true}
ref={(branchTextField) => this.branchTextField = branchTextField}
/>
<FormTextarea.Autosize
label="Build Environment Variables"
help={<span>The environment variables to use for the build, each on a new line. e.g. <code>FOO=bar</code></span>}
className="input"
rows={2}
errors={errors.findForField("env")}
defaultValue={this.props.env}
ref={(envTextField) => this.envTextField = envTextField}
/>
<FormCheckbox
label="Enabled"
help="Whether the schedule should run."
errors={errors.findForField("enabled")}
defaultChecked={this.props.enabled}
ref={(enabledCheckbox) => this.enabledCheckbox = enabledCheckbox}
/>
</div>
);
}
getFormData() {
return {
cronline: this.cronlineTextField.value,
label: this.labelTextField.value,
message: this.messageTextField.value,
commit: this.commitTextField.value,
branch: this.branchTextField.value,
enabled: this.enabledCheckbox._checkbox.checked, // ugh, I'm sorry
env: this.envTextField.value
};
}
}
export default Relay.createContainer(Form, {
fragments: {
pipeline: () => Relay.QL`
fragment on Pipeline {
defaultBranch
}
`
}
});
|
gatsby-strapi-tutorial/cms/plugins/settings-manager/admin/src/components/ContentHeader/index.js | strapi/strapi-examples | /**
*
* ContentHeader
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import styles from './styles.scss';
/* eslint-disable react/require-default-props */
function ContentHeader({ name, description }) { // eslint-disable-line react/prefer-stateless-function
const title = name ? <FormattedMessage id={`settings-manager.${name}`} /> : <span />;
const subTitle = description ? <FormattedMessage id={`settings-manager.${description}`} /> : <span />;
return (
<div className={styles.contentHeader}>
<div className={styles.title}>
{title}
</div>
<div className={styles.subTitle}>
{subTitle}
</div>
</div>
);
}
ContentHeader.propTypes = {
description: PropTypes.string,
name: PropTypes.string,
};
export default ContentHeader;
|
src/pages/login.js | delta-plus/andsquare | 'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Text,
Image,
TextInput,
View,
dismissKeyboard,
AsyncStorage
} from 'react-native';
import DismissKeyboard from 'dismissKeyboard';
import Button from '../components/button';
import Header from '../components/header';
import Signup from './signup';
import Account from './account';
import Firebase from '../components/firebase.js';
import styles from '../styles/common-styles.js';
export default class login extends Component {
constructor(props){
super(props);
this.state = {
email: '',
password: '',
loaded: true
}
}
render(){
return (
<View style={styles.container}>
<Header text="Login" loaded={this.state.loaded} />
<View style={styles.body}>
<TextInput
style={styles.textinput}
onChangeText={(text) => this.setState({email: text})}
value={this.state.email}
placeholder={"Email Address"}
/>
<TextInput
style={styles.textinput}
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
secureTextEntry={true}
placeholder={"Password"}
/>
<Button
text="Login"
onpress={this.login.bind(this)}
button_styles={styles.button}
button_text_styles={styles.button_text}
/>
<Button
text="Create Account"
onpress={this.goToSignup.bind(this)}
button_styles={styles.transparent_button}
button_text_styles={styles.transparent_button_text}
/>
<Image source={require('../assets/andsquare.jpeg')}
style={{height: 400, width: 400}}/>
</View>
</View>
);
}
async login(){
this.setState({
loaded: false
});
DismissKeyboard();
try {
await Firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password);
Firebase.auth().currentUser.getToken().then(data => AsyncStorage.setItem('user_data', JSON.stringify(data)));
AsyncStorage.setItem('user_email', this.state.email);
this.props.navigator.push({
component: Account
});
} catch (error) {
alert(error.toString());
}
this.setState({
email: '',
password: '',
loaded: true
});
}
goToSignup(){
this.props.navigator.push({
component: Signup
});
}
}
AppRegistry.registerComponent('login', () => login);
|
src/routes.js | abhisharkjangir/nasa | import React from 'react';
import {Route, IndexRoute} from 'react-router';
import App from './App';
import HomePage from './components/home/HomePage';
import AboutPage from './components/about/AboutPage';
import ApodPage from './components/apod/ApodPage';
import EpicPage from './components/epic/EpicPage';
import EarthPage from './components/earth/EarthPage';
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
<Route path="about" component={AboutPage} />
<Route path="apod" component={ApodPage}/>
<Route path="epic" component={EpicPage}/>
<Route path="earth" component={EarthPage}/>
</Route>
);
|
src/js/components/List/stories/Show.js | HewlettPackard/grommet | import React from 'react';
import { Box, List, Menu } from 'grommet';
import { More } from 'grommet-icons';
const data = [];
for (let i = 0; i < 95; i += 1) {
data.push({
entry: `entry-${i + 1}`,
});
}
export const Show = () => (
<Box fill>
<Box margin="large" height="small" overflow="scroll">
<List
data={data}
action={(item, index) => (
<Menu
key={index}
icon={<More />}
hoverIndicator
items={[{ label: 'one' }]}
/>
)}
show={30}
/>
</Box>
</Box>
);
export default {
title: 'Visualizations/List/Show',
};
|
node_modules/rc-select/es/Option.js | yhx0634/foodshopfront | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
var Option = function (_React$Component) {
_inherits(Option, _React$Component);
function Option() {
_classCallCheck(this, Option);
return _possibleConstructorReturn(this, (Option.__proto__ || Object.getPrototypeOf(Option)).apply(this, arguments));
}
return Option;
}(React.Component);
Option.propTypes = {
value: PropTypes.string
};
Option.isSelectOption = true;
export default Option; |
app/components/Home.js | vanHeemstraDesigns/CreationsEcosystemStatic | import React from 'react';
import {Link} from 'react-router';
import HomeStore from '../stores/HomeStore'
import HomeActions from '../actions/HomeActions';
import {first, without, findWhere} from 'underscore';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = HomeStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
HomeStore.listen(this.onChange);
HomeActions.getTwoCharacters();
}
componentWillUnmount() {
HomeStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
handleClick(character) {
var winner = character.characterId;
var loser = first(without(this.state.characters, findWhere(this.state.characters, { characterId: winner }))).characterId;
HomeActions.vote(winner, loser);
}
render() {
var characterNodes = this.state.characters.map((character, index) => {
return (
<div key={character.characterId} className={index === 0 ? 'col-xs-6 col-sm-6 col-md-5 col-md-offset-1' : 'col-xs-6 col-sm-6 col-md-5'}>
<div className='thumbnail fadeInUp animated'>
<img onClick={this.handleClick.bind(this, character)} src={'http://image.eveonline.com/Character/' + character.characterId + '_512.jpg'}/>
<div className='caption text-center'>
<ul className='list-inline'>
<li><strong>Race:</strong> {character.race}</li>
<li><strong>Bloodline:</strong> {character.bloodline}</li>
</ul>
<h4>
<Link to={'/characters/' + character.characterId}><strong>{character.name}</strong></Link>
</h4>
</div>
</div>
</div>
);
});
return (
<div className='container'>
<h3 className='text-center'>Click on the portrait. Select your favorite.</h3>
<div className='row'>
{characterNodes}
</div>
</div>
);
}
}
export default Home; |
newclient/scripts/components/user/dashboard/disclosure-archive-button/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 {Link} from 'react-router';
export function DisclosureArchiveButton({type, className}) {
return (
<Link
to={{pathname: '/coi/new/archiveview', query: {type}}}
className={`${styles.container} ${className}`}
>
<div>
<div className={styles.primary}>View</div>
<div className={styles.secondary}>Disclosure Archives</div>
</div>
</Link>
);
}
|
src/components/app.js | yeshdev1/Everydays-project | import React, { Component } from 'react';
import NavBar from './Generic/nav-bar';
import MemorialsPage from './Memorials/memorials-list';
export default class App extends Component {
constructor(props){
super(props);
}
render() {
return (
<div className="container">
<NavBar />
<MemorialsPage />
</div>
);
}
}
|
blueocean-material-icons/src/js/components/svg-icons/communication/screen-share.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const CommunicationScreenShare = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.11-.9-2-2-2H4c-1.11 0-2 .89-2 2v10c0 1.1.89 2 2 2H0v2h24v-2h-4zm-7-3.53v-2.19c-2.78 0-4.61.85-6 2.72.56-2.67 2.11-5.33 6-5.87V7l4 3.73-4 3.74z"/>
</SvgIcon>
);
CommunicationScreenShare.displayName = 'CommunicationScreenShare';
CommunicationScreenShare.muiName = 'SvgIcon';
export default CommunicationScreenShare;
|
src/main/resources/code/react/Apps/ManageRadars/Pages/ManageRadarTemplatesPage/RadarTemplateDetails/RadarCategoriesComponent/radarCategoryMap/colorMap/index.js | artieac/technologyradar | import React from 'react';
export const colorMap = (handleDropdownSelection, radarCategoryItem) => {
return [
{
key: 'dropdownItem',
render: rowData => {
return <a onClick ={(event) => handleDropdownSelection(event, rowData, radarCategoryItem)}>{ rowData.name }</a>;
},
},
];
}; |
dashboard-ui/test/helpers.js | CloudBoost/cloudboost | import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { mount, render, shallow } from 'enzyme';
import { jsdom } from 'jsdom';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import * as CB from 'cloudboost';
require.extensions['.css'] = () => {
return;
};
var exposedProperties = ['window', 'navigator', 'document'];
global.expect = expect;
global.sinon = sinon;
global.mount = mount;
global.render = render;
global.shallow = shallow;
global.util = {
makeString: function() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
},
makeEmail: function() {
return this.makeString() + '@sample.com';
},
generateRandomString: function() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 8; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
};
global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property];
}
});
// global.navigator = { userAgent: 'all' };
global.__isDevelopment = true
global.__isHosted = process.env["CLOUDBOOST_HOSTED"] || false
global.__isBrowser = false;
if(__isHosted){
global.USER_SERVICE_URL = "https://service.cloudboost.io"
global.SERVER_DOMAIN = "cloudboost.io"
global.SERVER_URL='https://api.cloudboost.io'
global.DASHBOARD_URL='https://dashboard.cloudboost.io'
global.ACCOUNTS_URL='https://accounts.cloudboost.io'
global.SLACK_TOKEN_URL = "https://slack.com/api/oauth.access"
} else {
global.USER_SERVICE_URL = "http://localhost:3000"
global.SERVER_DOMAIN = "localhost:4730"
global.SERVER_URL="http://localhost:4730"
global.DASHBOARD_URL="http://localhost:1440"
global.ACCOUNTS_URL="http://localhost:1447"
}
const muiTheme = getMuiTheme();
global.themeContext = {
context: { muiTheme },
childContextTypes: { muiTheme: React.PropTypes.object }
}
global.CB = CB;
CB.CloudApp.init(SERVER_URL, util.makeString, util.generateRandomString); |
test/always-render-suggestions/AutosuggestApp.js | fresk-nc/react-autosuggest | import React, { Component } from 'react';
import sinon from 'sinon';
import Autosuggest from '../../src/AutosuggestContainer';
import languages from '../plain-list/languages';
import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js';
function getMatchingLanguages(value) {
const escapedValue = escapeRegexCharacters(value.trim());
const regex = new RegExp('^' + escapedValue, 'i');
return languages.filter(language => regex.test(language.name));
}
let app = null;
export const getSuggestionValue = sinon.spy(suggestion => {
return suggestion.name;
});
export const renderSuggestion = sinon.spy(suggestion => {
return (
<span>{suggestion.name}</span>
);
});
export const onChange = sinon.spy((event, { newValue }) => {
app.setState({
value: newValue
});
});
export const onSuggestionSelected = sinon.spy();
export const onSuggestionsUpdateRequested = sinon.spy(({ value }) => {
app.setState({
suggestions: getMatchingLanguages(value)
});
});
export default class AutosuggestApp extends Component {
constructor() {
super();
app = this;
this.state = {
value: '',
suggestions: getMatchingLanguages('')
};
}
render() {
const { value, suggestions } = this.state;
const inputProps = {
value,
onChange
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsUpdateRequested={onSuggestionsUpdateRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
onSuggestionSelected={onSuggestionSelected}
alwaysRenderSuggestions={true} />
);
}
}
|
ajax/libs/primereact/6.5.0/blockui/blockui.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, ZIndexUtils, classNames, ObjectUtils, Portal } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var BlockUI = /*#__PURE__*/function (_Component) {
_inherits(BlockUI, _Component);
var _super = _createSuper(BlockUI);
function BlockUI(props) {
var _this;
_classCallCheck(this, BlockUI);
_this = _super.call(this, props);
_this.state = {
visible: props.blocked
};
_this.block = _this.block.bind(_assertThisInitialized(_this));
_this.unblock = _this.unblock.bind(_assertThisInitialized(_this));
_this.onPortalMounted = _this.onPortalMounted.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(BlockUI, [{
key: "block",
value: function block() {
this.setState({
visible: true
});
}
}, {
key: "unblock",
value: function unblock() {
var _this2 = this;
DomHandler.addClass(this.mask, 'p-blockui-leave');
this.mask.addEventListener('transitionend', function () {
ZIndexUtils.clear(_this2.mask);
_this2.setState({
visible: false
}, function () {
_this2.props.fullScreen && DomHandler.removeClass(document.body, 'p-overflow-hidden');
_this2.props.onUnblocked && _this2.props.onUnblocked();
});
});
}
}, {
key: "onPortalMounted",
value: function onPortalMounted() {
var _this3 = this;
if (this.props.fullScreen) {
DomHandler.addClass(document.body, 'p-overflow-hidden');
document.activeElement.blur();
}
if (this.mask) {
setTimeout(function () {
DomHandler.addClass(_this3.mask, 'p-component-overlay');
}, 1);
}
if (this.props.autoZIndex) {
ZIndexUtils.set(this.props.fullScreen ? 'modal' : 'overlay', this.mask, this.props.baseZIndex);
}
this.props.onBlocked && this.props.onBlocked();
}
}, {
key: "renderMask",
value: function renderMask() {
var _this4 = this;
if (this.state.visible) {
var className = classNames('p-blockui', {
'p-blockui-document': this.props.fullScreen
}, this.props.className);
var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : null;
var mask = /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this4.mask = el;
},
className: className,
style: this.props.style
}, content);
return /*#__PURE__*/React.createElement(Portal, {
element: mask,
appendTo: this.props.fullScreen ? document.body : 'self',
onMounted: this.onPortalMounted
});
}
return null;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.state.visible) {
this.block();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
if (prevProps.blocked !== this.props.blocked) {
this.props.blocked ? this.block() : this.unblock();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.props.fullScreen) {
DomHandler.removeClass(document.body, 'p-overflow-hidden');
}
ZIndexUtils.clear(this.mask);
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var mask = this.renderMask();
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this5.container = el;
},
id: this.props.id,
className: "p-blockui-container"
}, this.props.children, mask);
}
}]);
return BlockUI;
}(Component);
_defineProperty(BlockUI, "defaultProps", {
id: null,
blocked: false,
fullScreen: false,
baseZIndex: 0,
autoZIndex: true,
style: null,
className: null,
template: null,
onBlocked: null,
onUnblocked: null
});
export { BlockUI };
|
ajax/libs/boardgame-io/0.43.2/boardgameio.es.js | cdnjs/cdnjs | import { nanoid } from 'nanoid';
import { applyMiddleware, compose, createStore } from 'redux';
import produce from 'immer';
import { stringify, parse } from 'flatted';
import React from 'react';
import PropTypes from 'prop-types';
import ioNamespace__default from 'socket.io-client';
function noop() { }
const identity = x => x;
function assign(tar, src) {
// @ts-ignore
for (const k in src)
tar[k] = src[k];
return tar;
}
function run(fn) {
return fn();
}
function blank_object() {
return Object.create(null);
}
function run_all(fns) {
fns.forEach(run);
}
function is_function(thing) {
return typeof thing === 'function';
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
function subscribe(store, ...callbacks) {
if (store == null) {
return noop;
}
const unsub = store.subscribe(...callbacks);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function component_subscribe(component, store, callback) {
component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx, $$scope, fn) {
if (definition) {
const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
return definition[0](slot_ctx);
}
}
function get_slot_context(definition, ctx, $$scope, fn) {
return definition[1] && fn
? assign($$scope.ctx.slice(), definition[1](fn(ctx)))
: $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
if (definition[2] && fn) {
const lets = definition[2](fn(dirty));
if ($$scope.dirty === undefined) {
return lets;
}
if (typeof lets === 'object') {
const merged = [];
const len = Math.max($$scope.dirty.length, lets.length);
for (let i = 0; i < len; i += 1) {
merged[i] = $$scope.dirty[i] | lets[i];
}
return merged;
}
return $$scope.dirty | lets;
}
return $$scope.dirty;
}
function update_slot(slot, slot_definition, ctx, $$scope, dirty, get_slot_changes_fn, get_slot_context_fn) {
const slot_changes = get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_fn);
if (slot_changes) {
const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
slot.p(slot_context, slot_changes);
}
}
function exclude_internal_props(props) {
const result = {};
for (const k in props)
if (k[0] !== '$')
result[k] = props[k];
return result;
}
function null_to_empty(value) {
return value == null ? '' : value;
}
const is_client = typeof window !== 'undefined';
let now = is_client
? () => window.performance.now()
: () => Date.now();
let raf = is_client ? cb => requestAnimationFrame(cb) : noop;
const tasks = new Set();
function run_tasks(now) {
tasks.forEach(task => {
if (!task.c(now)) {
tasks.delete(task);
task.f();
}
});
if (tasks.size !== 0)
raf(run_tasks);
}
/**
* Creates a new task that runs on each raf frame
* until it returns a falsy value or is aborted
*/
function loop(callback) {
let task;
if (tasks.size === 0)
raf(run_tasks);
return {
promise: new Promise(fulfill => {
tasks.add(task = { c: callback, f: fulfill });
}),
abort() {
tasks.delete(task);
}
};
}
function append(target, node) {
target.appendChild(node);
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
for (let i = 0; i < iterations.length; i += 1) {
if (iterations[i])
iterations[i].d(detaching);
}
}
function element(name) {
return document.createElement(name);
}
function svg_element(name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
}
function text(data) {
return document.createTextNode(data);
}
function space() {
return text(' ');
}
function empty() {
return text('');
}
function listen(node, event, handler, options) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
function stop_propagation(fn) {
return function (event) {
event.stopPropagation();
// @ts-ignore
return fn.call(this, event);
};
}
function attr(node, attribute, value) {
if (value == null)
node.removeAttribute(attribute);
else if (node.getAttribute(attribute) !== value)
node.setAttribute(attribute, value);
}
function to_number(value) {
return value === '' ? undefined : +value;
}
function children(element) {
return Array.from(element.childNodes);
}
function set_data(text, data) {
data = '' + data;
if (text.wholeText !== data)
text.data = data;
}
function set_input_value(input, value) {
input.value = value == null ? '' : value;
}
function select_option(select, value) {
for (let i = 0; i < select.options.length; i += 1) {
const option = select.options[i];
if (option.__value === value) {
option.selected = true;
return;
}
}
}
function select_value(select) {
const selected_option = select.querySelector(':checked') || select.options[0];
return selected_option && selected_option.__value;
}
function toggle_class(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name);
}
function custom_event(type, detail) {
const e = document.createEvent('CustomEvent');
e.initCustomEvent(type, false, false, detail);
return e;
}
const active_docs = new Set();
let active = 0;
// https://github.com/darkskyapp/string-hash/blob/master/index.js
function hash(str) {
let hash = 5381;
let i = str.length;
while (i--)
hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
return hash >>> 0;
}
function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
const step = 16.666 / duration;
let keyframes = '{\n';
for (let p = 0; p <= 1; p += step) {
const t = a + (b - a) * ease(p);
keyframes += p * 100 + `%{${fn(t, 1 - t)}}\n`;
}
const rule = keyframes + `100% {${fn(b, 1 - b)}}\n}`;
const name = `__svelte_${hash(rule)}_${uid}`;
const doc = node.ownerDocument;
active_docs.add(doc);
const stylesheet = doc.__svelte_stylesheet || (doc.__svelte_stylesheet = doc.head.appendChild(element('style')).sheet);
const current_rules = doc.__svelte_rules || (doc.__svelte_rules = {});
if (!current_rules[name]) {
current_rules[name] = true;
stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);
}
const animation = node.style.animation || '';
node.style.animation = `${animation ? `${animation}, ` : ``}${name} ${duration}ms linear ${delay}ms 1 both`;
active += 1;
return name;
}
function delete_rule(node, name) {
const previous = (node.style.animation || '').split(', ');
const next = previous.filter(name
? anim => anim.indexOf(name) < 0 // remove specific animation
: anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations
);
const deleted = previous.length - next.length;
if (deleted) {
node.style.animation = next.join(', ');
active -= deleted;
if (!active)
clear_rules();
}
}
function clear_rules() {
raf(() => {
if (active)
return;
active_docs.forEach(doc => {
const stylesheet = doc.__svelte_stylesheet;
let i = stylesheet.cssRules.length;
while (i--)
stylesheet.deleteRule(i);
doc.__svelte_rules = {};
});
active_docs.clear();
});
}
let current_component;
function set_current_component(component) {
current_component = component;
}
function get_current_component() {
if (!current_component)
throw new Error(`Function called outside component initialization`);
return current_component;
}
function afterUpdate(fn) {
get_current_component().$$.after_update.push(fn);
}
function onDestroy(fn) {
get_current_component().$$.on_destroy.push(fn);
}
function createEventDispatcher() {
const component = get_current_component();
return (type, detail) => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
// TODO are there situations where events could be dispatched
// in a server (non-DOM) environment?
const event = custom_event(type, detail);
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
}
};
}
function setContext(key, context) {
get_current_component().$$.context.set(key, context);
}
function getContext(key) {
return get_current_component().$$.context.get(key);
}
// TODO figure out if we still want to support
// shorthand events, or if we want to implement
// a real bubbling mechanism
function bubble(component, event) {
const callbacks = component.$$.callbacks[event.type];
if (callbacks) {
callbacks.slice().forEach(fn => fn(event));
}
}
const dirty_components = [];
const binding_callbacks = [];
const render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = Promise.resolve();
let update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
update_scheduled = true;
resolved_promise.then(flush);
}
}
function add_render_callback(fn) {
render_callbacks.push(fn);
}
let flushing = false;
const seen_callbacks = new Set();
function flush() {
if (flushing)
return;
flushing = true;
do {
// first, call beforeUpdate functions
// and update components
for (let i = 0; i < dirty_components.length; i += 1) {
const component = dirty_components[i];
set_current_component(component);
update(component.$$);
}
dirty_components.length = 0;
while (binding_callbacks.length)
binding_callbacks.pop()();
// then, once components are updated, call
// afterUpdate functions. This may cause
// subsequent updates...
for (let i = 0; i < render_callbacks.length; i += 1) {
const callback = render_callbacks[i];
if (!seen_callbacks.has(callback)) {
// ...so guard against infinite loops
seen_callbacks.add(callback);
callback();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
while (flush_callbacks.length) {
flush_callbacks.pop()();
}
update_scheduled = false;
flushing = false;
seen_callbacks.clear();
}
function update($$) {
if ($$.fragment !== null) {
$$.update();
run_all($$.before_update);
const dirty = $$.dirty;
$$.dirty = [-1];
$$.fragment && $$.fragment.p($$.ctx, dirty);
$$.after_update.forEach(add_render_callback);
}
}
let promise;
function wait() {
if (!promise) {
promise = Promise.resolve();
promise.then(() => {
promise = null;
});
}
return promise;
}
function dispatch(node, direction, kind) {
node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`));
}
const outroing = new Set();
let outros;
function group_outros() {
outros = {
r: 0,
c: [],
p: outros // parent group
};
}
function check_outros() {
if (!outros.r) {
run_all(outros.c);
}
outros = outros.p;
}
function transition_in(block, local) {
if (block && block.i) {
outroing.delete(block);
block.i(local);
}
}
function transition_out(block, local, detach, callback) {
if (block && block.o) {
if (outroing.has(block))
return;
outroing.add(block);
outros.c.push(() => {
outroing.delete(block);
if (callback) {
if (detach)
block.d(1);
callback();
}
});
block.o(local);
}
}
const null_transition = { duration: 0 };
function create_bidirectional_transition(node, fn, params, intro) {
let config = fn(node, params);
let t = intro ? 0 : 1;
let running_program = null;
let pending_program = null;
let animation_name = null;
function clear_animation() {
if (animation_name)
delete_rule(node, animation_name);
}
function init(program, duration) {
const d = program.b - t;
duration *= Math.abs(d);
return {
a: t,
b: program.b,
d,
duration,
start: program.start,
end: program.start + duration,
group: program.group
};
}
function go(b) {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
const program = {
start: now() + delay,
b
};
if (!b) {
// @ts-ignore todo: improve typings
program.group = outros;
outros.r += 1;
}
if (running_program) {
pending_program = program;
}
else {
// if this is an intro, and there's a delay, we need to do
// an initial tick and/or apply CSS animation immediately
if (css) {
clear_animation();
animation_name = create_rule(node, t, b, duration, delay, easing, css);
}
if (b)
tick(0, 1);
running_program = init(program, duration);
add_render_callback(() => dispatch(node, b, 'start'));
loop(now => {
if (pending_program && now > pending_program.start) {
running_program = init(pending_program, duration);
pending_program = null;
dispatch(node, running_program.b, 'start');
if (css) {
clear_animation();
animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);
}
}
if (running_program) {
if (now >= running_program.end) {
tick(t = running_program.b, 1 - t);
dispatch(node, running_program.b, 'end');
if (!pending_program) {
// we're done
if (running_program.b) {
// intro — we can tidy up immediately
clear_animation();
}
else {
// outro — needs to be coordinated
if (!--running_program.group.r)
run_all(running_program.group.c);
}
}
running_program = null;
}
else if (now >= running_program.start) {
const p = now - running_program.start;
t = running_program.a + running_program.d * easing(p / running_program.duration);
tick(t, 1 - t);
}
}
return !!(running_program || pending_program);
});
}
}
return {
run(b) {
if (is_function(config)) {
wait().then(() => {
// @ts-ignore
config = config();
go(b);
});
}
else {
go(b);
}
},
end() {
clear_animation();
running_program = pending_program = null;
}
};
}
const globals = (typeof window !== 'undefined'
? window
: typeof globalThis !== 'undefined'
? globalThis
: global);
function get_spread_update(levels, updates) {
const update = {};
const to_null_out = {};
const accounted_for = { $$scope: 1 };
let i = levels.length;
while (i--) {
const o = levels[i];
const n = updates[i];
if (n) {
for (const key in o) {
if (!(key in n))
to_null_out[key] = 1;
}
for (const key in n) {
if (!accounted_for[key]) {
update[key] = n[key];
accounted_for[key] = 1;
}
}
levels[i] = n;
}
else {
for (const key in o) {
accounted_for[key] = 1;
}
}
}
for (const key in to_null_out) {
if (!(key in update))
update[key] = undefined;
}
return update;
}
function get_spread_object(spread_props) {
return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};
}
function create_component(block) {
block && block.c();
}
function mount_component(component, target, anchor) {
const { fragment, on_mount, on_destroy, after_update } = component.$$;
fragment && fragment.m(target, anchor);
// onMount happens before the initial afterUpdate
add_render_callback(() => {
const new_on_destroy = on_mount.map(run).filter(is_function);
if (on_destroy) {
on_destroy.push(...new_on_destroy);
}
else {
// Edge case - component was destroyed immediately,
// most likely as a result of a binding initialising
run_all(new_on_destroy);
}
component.$$.on_mount = [];
});
after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
// TODO null out other refs, including component.$$ (but need to
// preserve final state?)
$$.on_destroy = $$.fragment = null;
$$.ctx = [];
}
}
function make_dirty(component, i) {
if (component.$$.dirty[0] === -1) {
dirty_components.push(component);
schedule_update();
component.$$.dirty.fill(0);
}
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function init(component, options, instance, create_fragment, not_equal, props, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const prop_values = options.props || {};
const $$ = component.$$ = {
fragment: null,
ctx: null,
// state
props,
update: noop,
not_equal,
bound: blank_object(),
// lifecycle
on_mount: [],
on_destroy: [],
before_update: [],
after_update: [],
context: new Map(parent_component ? parent_component.$$.context : []),
// everything else
callbacks: blank_object(),
dirty
};
let ready = false;
$$.ctx = instance
? instance(component, prop_values, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if ($$.bound[i])
$$.bound[i](value);
if (ready)
make_dirty(component, i);
}
return ret;
})
: [];
$$.update();
ready = true;
run_all($$.before_update);
// `false` as a special case of no DOM component
$$.fragment = create_fragment ? create_fragment($$.ctx) : false;
if (options.target) {
if (options.hydrate) {
const nodes = children(options.target);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.l(nodes);
nodes.forEach(detach);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.c();
}
if (options.intro)
transition_in(component.$$.fragment);
mount_component(component, options.target, options.anchor);
flush();
}
set_current_component(parent_component);
}
class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set() {
// overridden by instance, if it has props
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const MAKE_MOVE = 'MAKE_MOVE';
const GAME_EVENT = 'GAME_EVENT';
const REDO = 'REDO';
const RESET = 'RESET';
const SYNC = 'SYNC';
const UNDO = 'UNDO';
const UPDATE = 'UPDATE';
const PLUGIN = 'PLUGIN';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Generate a move to be dispatched to the game move reducer.
*
* @param {string} type - The move type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const makeMove = (type, args, playerID, credentials) => ({
type: MAKE_MOVE,
payload: { type, args, playerID, credentials },
});
/**
* Generate a game event to be dispatched to the flow reducer.
*
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const gameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
});
/**
* Generate an automatic game event that is a side-effect of a move.
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const automaticGameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
automatic: true,
});
const sync = (info) => ({
type: SYNC,
state: info.state,
log: info.log,
initialState: info.initialState,
clientOnly: true,
});
/**
* Used to update the Redux store's state in response to
* an action coming from another player.
* @param {object} state - The state to restore.
* @param {Array} deltalog - A log delta.
*/
const update$1 = (state, deltalog) => ({
type: UPDATE,
state,
deltalog,
clientOnly: true,
});
/**
* Used to reset the game state.
* @param {object} state - The initial state.
*/
const reset = (state) => ({
type: RESET,
state,
clientOnly: true,
});
/**
* Used to undo the last move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const undo = (playerID, credentials) => ({
type: UNDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Used to redo the last undone move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const redo = (playerID, credentials) => ({
type: REDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Allows plugins to define their own actions and intercept them.
*/
const plugin = (type, args, playerID, credentials) => ({
type: PLUGIN,
payload: { type, args, playerID, credentials },
});
var ActionCreators = /*#__PURE__*/Object.freeze({
makeMove: makeMove,
gameEvent: gameEvent,
automaticGameEvent: automaticGameEvent,
sync: sync,
update: update$1,
reset: reset,
undo: undo,
redo: redo,
plugin: plugin
});
/**
* Moves can return this when they want to indicate
* that the combination of arguments is illegal and
* the move ought to be discarded.
*/
const INVALID_MOVE = 'INVALID_MOVE';
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that allows using Immer to make immutable changes
* to G by just mutating it.
*/
const ImmerPlugin = {
name: 'plugin-immer',
fnWrap: (move) => (G, ctx, ...args) => {
let isInvalid = false;
const newG = produce(G, (G) => {
const result = move(G, ctx, ...args);
if (result === INVALID_MOVE) {
isInvalid = true;
return;
}
return result;
});
if (isInvalid)
return INVALID_MOVE;
return newG;
},
};
// Inlined version of Alea from https://github.com/davidbau/seedrandom.
// Converted to Typescript October 2020.
class Alea {
constructor(seed) {
const mash = Mash();
// Apply the seeding algorithm from Baagoe.
this.c = 1;
this.s0 = mash(' ');
this.s1 = mash(' ');
this.s2 = mash(' ');
this.s0 -= mash(seed);
if (this.s0 < 0) {
this.s0 += 1;
}
this.s1 -= mash(seed);
if (this.s1 < 0) {
this.s1 += 1;
}
this.s2 -= mash(seed);
if (this.s2 < 0) {
this.s2 += 1;
}
}
next() {
const t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
this.s0 = this.s1;
this.s1 = this.s2;
return (this.s2 = t - (this.c = Math.trunc(t)));
}
}
function Mash() {
let n = 0xefc8249d;
const mash = function (data) {
const str = data.toString();
for (let i = 0; i < str.length; i++) {
n += str.charCodeAt(i);
let h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function alea(seed, state) {
const xg = new Alea(seed);
const prng = xg.next.bind(xg);
if (state)
copy(state, xg);
prng.state = () => copy(xg, {});
return prng;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Random
*
* Calls that require a pseudorandom number generator.
* Uses a seed from ctx, and also persists the PRNG
* state in ctx so that moves can stay pure.
*/
class Random {
/**
* constructor
* @param {object} ctx - The ctx object to initialize from.
*/
constructor(state) {
// If we are on the client, the seed is not present.
// Just use a temporary seed to execute the move without
// crashing it. The move state itself is discarded,
// so the actual value doesn't matter.
this.state = state || { seed: '0' };
this.used = false;
}
/**
* Generates a new seed from the current date / time.
*/
static seed() {
return Date.now().toString(36).slice(-10);
}
isUsed() {
return this.used;
}
getState() {
return this.state;
}
/**
* Generate a random number.
*/
_random() {
this.used = true;
const R = this.state;
const seed = R.prngstate ? '' : R.seed;
const rand = alea(seed, R.prngstate);
const number = rand();
this.state = {
...R,
prngstate: rand.state(),
};
return number;
}
api() {
const random = this._random.bind(this);
const SpotValue = {
D4: 4,
D6: 6,
D8: 8,
D10: 10,
D12: 12,
D20: 20,
};
// Generate functions for predefined dice values D4 - D20.
const predefined = {};
for (const key in SpotValue) {
const spotvalue = SpotValue[key];
predefined[key] = (diceCount) => {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: [...new Array(diceCount).keys()].map(() => Math.floor(random() * spotvalue) + 1);
};
}
function Die(spotvalue = 6, diceCount) {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: [...new Array(diceCount).keys()].map(() => Math.floor(random() * spotvalue) + 1);
}
return {
/**
* Similar to Die below, but with fixed spot values.
* Supports passing a diceCount
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*
* D4: (diceCount) => value
* D6: (diceCount) => value
* D8: (diceCount) => value
* D10: (diceCount) => value
* D12: (diceCount) => value
* D20: (diceCount) => value
*/
...predefined,
/**
* Roll a die of specified spot value.
*
* @param {number} spotvalue - The die dimension (default: 6).
* @param {number} diceCount - number of dice to throw.
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*/
Die,
/**
* Generate a random number between 0 and 1.
*/
Number: () => {
return random();
},
/**
* Shuffle an array.
*
* @param {Array} deck - The array to shuffle. Does not mutate
* the input, but returns the shuffled array.
*/
Shuffle: (deck) => {
const clone = deck.slice(0);
let srcIndex = deck.length;
let dstIndex = 0;
const shuffled = new Array(srcIndex);
while (srcIndex) {
const randIndex = Math.trunc(srcIndex * random());
shuffled[dstIndex++] = clone[randIndex];
clone[randIndex] = clone[--srcIndex];
}
return shuffled;
},
_obj: this,
};
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const RandomPlugin = {
name: 'random',
noClient: ({ api }) => {
return api._obj.isUsed();
},
flush: ({ api }) => {
return api._obj.getState();
},
api: ({ data }) => {
const random = new Random(data);
return random.api();
},
setup: ({ game }) => {
let { seed } = game;
if (seed === undefined) {
seed = Random.seed();
}
return { seed };
},
playerView: () => undefined,
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Events
*/
class Events {
constructor(flow, playerID) {
this.flow = flow;
this.playerID = playerID;
this.dispatch = [];
}
/**
* Attaches the Events API to ctx.
* @param {object} ctx - The ctx object to attach to.
*/
api(ctx) {
const events = {
_obj: this,
};
const { phase, turn } = ctx;
for (const key of this.flow.eventNames) {
events[key] = (...args) => {
this.dispatch.push({ key, args, phase, turn });
};
}
return events;
}
isUsed() {
return this.dispatch.length > 0;
}
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state) {
for (let i = 0; i < this.dispatch.length; i++) {
const item = this.dispatch[i];
// If the turn already ended some other way,
// don't try to end the turn again.
if (item.key === 'endTurn' && item.turn !== state.ctx.turn) {
continue;
}
// If the phase already ended some other way,
// don't try to end the phase again.
if ((item.key === 'endPhase' || item.key === 'setPhase') &&
item.phase !== state.ctx.phase) {
continue;
}
const action = automaticGameEvent(item.key, item.args, this.playerID);
state = {
...state,
...this.flow.processEvent(state, action),
};
}
return state;
}
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const EventsPlugin = {
name: 'events',
noClient: ({ api }) => {
return api._obj.isUsed();
},
dangerouslyFlushRawState: ({ state, api }) => {
return api._obj.update(state);
},
api: ({ game, playerID, ctx }) => {
return new Events(game.flow, playerID).api(ctx);
},
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that makes it possible to add metadata to log entries.
* During a move, you can set metadata using ctx.log.setMetadata and it will be
* available on the log entry for that move.
*/
const LogPlugin = {
name: 'log',
flush: () => ({}),
api: ({ data }) => {
return {
setMetadata: (metadata) => {
data.metadata = metadata;
},
};
},
setup: () => ({}),
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* List of plugins that are always added.
*/
const DEFAULT_PLUGINS = [ImmerPlugin, RandomPlugin, EventsPlugin, LogPlugin];
/**
* Allow plugins to intercept actions and process them.
*/
const ProcessAction = (state, action, opts) => {
opts.game.plugins
.filter((plugin) => plugin.action !== undefined)
.filter((plugin) => plugin.name === action.payload.type)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const data = plugin.action(pluginState.data, action.payload);
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, data },
},
};
});
return state;
};
/**
* The API's created by various plugins are stored in the plugins
* section of the state object:
*
* {
* G: {},
* ctx: {},
* plugins: {
* plugin-a: {
* data: {}, // this is generated by the plugin at Setup / Flush.
* api: {}, // this is ephemeral and generated by Enhance.
* }
* }
* }
*
* This function takes these API's and stuffs them back into
* ctx for consumption inside a move function or hook.
*/
const EnhanceCtx = (state) => {
const ctx = { ...state.ctx };
const plugins = state.plugins || {};
Object.entries(plugins).forEach(([name, { api }]) => {
ctx[name] = api;
});
return ctx;
};
/**
* Applies the provided plugins to the given move / flow function.
*
* @param {function} fn - The move function or trigger to apply the plugins to.
* @param {object} plugins - The list of plugins.
*/
const FnWrap = (fn, plugins) => {
const reducer = (acc, { fnWrap }) => fnWrap(acc);
return [...DEFAULT_PLUGINS, ...plugins]
.filter((plugin) => plugin.fnWrap !== undefined)
.reduce(reducer, fn);
};
/**
* Allows the plugin to generate its initial state.
*/
const Setup = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.setup !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const data = plugin.setup({
G: state.G,
ctx: state.ctx,
game: opts.game,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { data },
},
};
});
return state;
};
/**
* Invokes the plugin before a move or event.
* The API that the plugin generates is stored inside
* the `plugins` section of the state (which is subsequently
* merged into ctx).
*/
const Enhance = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.api !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const api = plugin.api({
G: state.G,
ctx: state.ctx,
data: pluginState.data,
game: opts.game,
playerID: opts.playerID,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, api },
},
};
});
return state;
};
/**
* Allows plugins to update their state after a move / event.
*/
const Flush = (state, opts) => {
// Note that we flush plugins in reverse order, to make sure that plugins
// that come before in the chain are still available.
[...DEFAULT_PLUGINS, ...opts.game.plugins].reverse().forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
if (plugin.flush) {
const newData = plugin.flush({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data: newData },
},
};
}
else if (plugin.dangerouslyFlushRawState) {
state = plugin.dangerouslyFlushRawState({
state,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
// Remove everything other than data.
const data = state.plugins[name].data;
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data },
},
};
}
});
return state;
};
/**
* Allows plugins to indicate if they should not be materialized on the client.
* This will cause the client to discard the state update and wait for the
* master instead.
*/
const NoClient = (state, opts) => {
return [...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.noClient !== undefined)
.map((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name];
if (pluginState) {
return plugin.noClient({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
}
return false;
})
.some((value) => value === true);
};
/**
* Allows plugins to customize their data for specific players.
* For example, a plugin may want to share no data with the client, or
* want to keep some player data secret from opponents.
*/
const PlayerView = ({ G, ctx, plugins = {} }, { game, playerID }) => {
[...DEFAULT_PLUGINS, ...game.plugins].forEach(({ name, playerView }) => {
if (!playerView)
return;
const { data } = plugins[name] || { data: {} };
const newData = playerView({ G, ctx, game, data, playerID });
plugins = {
...plugins,
[name]: { data: newData },
};
});
return plugins;
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const production = process.env.NODE_ENV === 'production';
const logfn = production ? () => { } : console.log;
const errorfn = console.error;
function info(msg) {
logfn(`INFO: ${msg}`);
}
function error(error) {
errorfn('ERROR:', error);
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Event to change the active players (and their stages) in the current turn.
*/
function SetActivePlayersEvent(state, _playerID, arg) {
return { ...state, ctx: SetActivePlayers(state.ctx, arg) };
}
function SetActivePlayers(ctx, arg) {
let { _prevActivePlayers } = ctx;
let activePlayers = {};
let _nextActivePlayers = null;
let _activePlayersMoveLimit = {};
if (Array.isArray(arg)) {
// support a simple array of player IDs as active players
const value = {};
arg.forEach((v) => (value[v] = Stage.NULL));
activePlayers = value;
}
else {
// process active players argument object
if (arg.next) {
_nextActivePlayers = arg.next;
}
_prevActivePlayers = arg.revert
? _prevActivePlayers.concat({
activePlayers: ctx.activePlayers,
_activePlayersMoveLimit: ctx._activePlayersMoveLimit,
_activePlayersNumMoves: ctx._activePlayersNumMoves,
})
: [];
if (arg.currentPlayer !== undefined) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, ctx.currentPlayer, arg.currentPlayer);
}
if (arg.others !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
if (id !== ctx.currentPlayer) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.others);
}
}
}
if (arg.all !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.all);
}
}
if (arg.value) {
for (const id in arg.value) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.value[id]);
}
}
if (arg.moveLimit) {
for (const id in activePlayers) {
if (_activePlayersMoveLimit[id] === undefined) {
_activePlayersMoveLimit[id] = arg.moveLimit;
}
}
}
}
if (Object.keys(activePlayers).length == 0) {
activePlayers = null;
}
if (Object.keys(_activePlayersMoveLimit).length == 0) {
_activePlayersMoveLimit = null;
}
const _activePlayersNumMoves = {};
for (const id in activePlayers) {
_activePlayersNumMoves[id] = 0;
}
return {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
_nextActivePlayers,
};
}
/**
* Update activePlayers, setting it to previous, next or null values
* when it becomes empty.
* @param ctx
*/
function UpdateActivePlayersOnceEmpty(ctx) {
let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx;
if (activePlayers && Object.keys(activePlayers).length == 0) {
if (ctx._nextActivePlayers) {
ctx = SetActivePlayers(ctx, ctx._nextActivePlayers);
({
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
} = ctx);
}
else if (_prevActivePlayers.length > 0) {
const lastIndex = _prevActivePlayers.length - 1;
({
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
} = _prevActivePlayers[lastIndex]);
_prevActivePlayers = _prevActivePlayers.slice(0, lastIndex);
}
else {
activePlayers = null;
_activePlayersMoveLimit = null;
}
}
return {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
};
}
/**
* Apply an active player argument to the given player ID
* @param {Object} activePlayers
* @param {Object} _activePlayersMoveLimit
* @param {String} playerID The player to apply the parameter to
* @param {(String|Object)} arg An active player argument
*/
function ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, playerID, arg) {
if (typeof arg !== 'object' || arg === Stage.NULL) {
arg = { stage: arg };
}
if (arg.stage !== undefined) {
activePlayers[playerID] = arg.stage;
if (arg.moveLimit)
_activePlayersMoveLimit[playerID] = arg.moveLimit;
}
}
/**
* Converts a playOrderPos index into its value in playOrder.
* @param {Array} playOrder - An array of player ID's.
* @param {number} playOrderPos - An index into the above.
*/
function getCurrentPlayer(playOrder, playOrderPos) {
// convert to string in case playOrder is set to number[]
return playOrder[playOrderPos] + '';
}
/**
* Called at the start of a turn to initialize turn order state.
*
* TODO: This is called inside StartTurn, which is called from
* both UpdateTurn and StartPhase (so it's called at the beginning
* of a new phase as well as between turns). We should probably
* split it into two.
*/
function InitTurnOrderState(state, turn) {
let { G, ctx } = state;
const ctxWithAPI = EnhanceCtx(state);
const order = turn.order;
let playOrder = [...new Array(ctx.numPlayers)].map((_, i) => i + '');
if (order.playOrder !== undefined) {
playOrder = order.playOrder(G, ctxWithAPI);
}
const playOrderPos = order.first(G, ctxWithAPI);
const posType = typeof playOrderPos;
if (posType !== 'number') {
error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`);
}
const currentPlayer = getCurrentPlayer(playOrder, playOrderPos);
ctx = { ...ctx, currentPlayer, playOrderPos, playOrder };
ctx = SetActivePlayers(ctx, turn.activePlayers || {});
return ctx;
}
/**
* Called at the end of each turn to update the turn order state.
* @param {object} G - The game object G.
* @param {object} ctx - The game object ctx.
* @param {object} turn - A turn object for this phase.
* @param {string} endTurnArg - An optional argument to endTurn that
may specify the next player.
*/
function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) {
const order = turn.order;
let { G, ctx } = state;
let playOrderPos = ctx.playOrderPos;
let endPhase = false;
if (endTurnArg && endTurnArg !== true) {
if (typeof endTurnArg !== 'object') {
error(`invalid argument to endTurn: ${endTurnArg}`);
}
Object.keys(endTurnArg).forEach((arg) => {
switch (arg) {
case 'remove':
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
break;
case 'next':
playOrderPos = ctx.playOrder.indexOf(endTurnArg.next);
currentPlayer = endTurnArg.next;
break;
default:
error(`invalid argument to endTurn: ${arg}`);
}
});
}
else {
const ctxWithAPI = EnhanceCtx(state);
const t = order.next(G, ctxWithAPI);
const type = typeof t;
if (t !== undefined && type !== 'number') {
error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`);
}
if (t === undefined) {
endPhase = true;
}
else {
playOrderPos = t;
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
}
}
ctx = {
...ctx,
playOrderPos,
currentPlayer,
};
return { endPhase, ctx };
}
/**
* Set of different turn orders possible in a phase.
* These are meant to be passed to the `turn` setting
* in the flow objects.
*
* Each object defines the first player when the phase / game
* begins, and also a function `next` to determine who the
* next player is when the turn ends.
*
* The phase ends if next() returns undefined.
*/
const TurnOrder = {
/**
* DEFAULT
*
* The default round-robin turn order.
*/
DEFAULT: {
first: (G, ctx) => ctx.turn === 0
? ctx.playOrderPos
: (ctx.playOrderPos + 1) % ctx.playOrder.length,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* RESET
*
* Similar to DEFAULT, but starts from 0 each time.
*/
RESET: {
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* CONTINUE
*
* Similar to DEFAULT, but starts with the player who ended the last phase.
*/
CONTINUE: {
first: (G, ctx) => ctx.playOrderPos,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* ONCE
*
* Another round-robin turn order, but goes around just once.
* The phase ends after all players have played.
*/
ONCE: {
first: () => 0,
next: (G, ctx) => {
if (ctx.playOrderPos < ctx.playOrder.length - 1) {
return ctx.playOrderPos + 1;
}
},
},
/**
* CUSTOM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase.
*
* @param {Array} playOrder - The play order.
*/
CUSTOM: (playOrder) => ({
playOrder: () => playOrder,
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
/**
* CUSTOM_FROM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase to a value specified by a field
* in G.
*
* @param {string} playOrderField - Field in G.
*/
CUSTOM_FROM: (playOrderField) => ({
playOrder: (G) => G[playOrderField],
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
};
const Stage = {
NULL: null,
};
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Flow
*
* Creates a reducer that updates ctx (analogous to how moves update G).
*/
function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) {
// Attach defaults.
if (moves === undefined) {
moves = {};
}
if (events === undefined) {
events = {};
}
if (plugins === undefined) {
plugins = [];
}
if (phases === undefined) {
phases = {};
}
if (!endIf)
endIf = () => undefined;
if (!onEnd)
onEnd = (G) => G;
if (!turn)
turn = {};
const phaseMap = { ...phases };
if ('' in phaseMap) {
error('cannot specify phase with empty name');
}
phaseMap[''] = {};
const moveMap = {};
const moveNames = new Set();
let startingPhase = null;
Object.keys(moves).forEach((name) => moveNames.add(name));
const HookWrapper = (fn) => {
const withPlugins = FnWrap(fn, plugins);
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return withPlugins(state.G, ctxWithAPI);
};
};
const TriggerWrapper = (endIf) => {
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return endIf(state.G, ctxWithAPI);
};
};
const wrapped = {
onEnd: HookWrapper(onEnd),
endIf: TriggerWrapper(endIf),
};
for (const phase in phaseMap) {
const conf = phaseMap[phase];
if (conf.start === true) {
startingPhase = phase;
}
if (conf.moves !== undefined) {
for (const move of Object.keys(conf.moves)) {
moveMap[phase + '.' + move] = conf.moves[move];
moveNames.add(move);
}
}
if (conf.endIf === undefined) {
conf.endIf = () => undefined;
}
if (conf.onBegin === undefined) {
conf.onBegin = (G) => G;
}
if (conf.onEnd === undefined) {
conf.onEnd = (G) => G;
}
if (conf.turn === undefined) {
conf.turn = turn;
}
if (conf.turn.order === undefined) {
conf.turn.order = TurnOrder.DEFAULT;
}
if (conf.turn.onBegin === undefined) {
conf.turn.onBegin = (G) => G;
}
if (conf.turn.onEnd === undefined) {
conf.turn.onEnd = (G) => G;
}
if (conf.turn.endIf === undefined) {
conf.turn.endIf = () => false;
}
if (conf.turn.onMove === undefined) {
conf.turn.onMove = (G) => G;
}
if (conf.turn.stages === undefined) {
conf.turn.stages = {};
}
for (const stage in conf.turn.stages) {
const stageConfig = conf.turn.stages[stage];
const moves = stageConfig.moves || {};
for (const move of Object.keys(moves)) {
const key = phase + '.' + stage + '.' + move;
moveMap[key] = moves[move];
moveNames.add(move);
}
}
conf.wrapped = {
onBegin: HookWrapper(conf.onBegin),
onEnd: HookWrapper(conf.onEnd),
endIf: TriggerWrapper(conf.endIf),
};
conf.turn.wrapped = {
onMove: HookWrapper(conf.turn.onMove),
onBegin: HookWrapper(conf.turn.onBegin),
onEnd: HookWrapper(conf.turn.onEnd),
endIf: TriggerWrapper(conf.turn.endIf),
};
}
function GetPhase(ctx) {
return ctx.phase ? phaseMap[ctx.phase] : phaseMap[''];
}
function OnMove(s) {
return s;
}
function Process(state, events) {
const phasesEnded = new Set();
const turnsEnded = new Set();
for (let i = 0; i < events.length; i++) {
const { fn, arg, ...rest } = events[i];
// Detect a loop of EndPhase calls.
// This could potentially even be an infinite loop
// if the endIf condition of each phase blindly
// returns true. The moment we detect a single
// loop, we just bail out of all phases.
if (fn === EndPhase) {
turnsEnded.clear();
const phase = state.ctx.phase;
if (phasesEnded.has(phase)) {
const ctx = { ...state.ctx, phase: null };
return { ...state, ctx };
}
phasesEnded.add(phase);
}
// Process event.
const next = [];
state = fn(state, {
...rest,
arg,
next,
});
if (fn === EndGame) {
break;
}
// Check if we should end the game.
const shouldEndGame = ShouldEndGame(state);
if (shouldEndGame) {
events.push({
fn: EndGame,
arg: shouldEndGame,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the phase.
const shouldEndPhase = ShouldEndPhase(state);
if (shouldEndPhase) {
events.push({
fn: EndPhase,
arg: shouldEndPhase,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the turn.
if (fn === OnMove) {
const shouldEndTurn = ShouldEndTurn(state);
if (shouldEndTurn) {
events.push({
fn: EndTurn,
arg: shouldEndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
}
events.push(...next);
}
return state;
}
///////////
// Start //
///////////
function StartGame(state, { next }) {
next.push({ fn: StartPhase });
return state;
}
function StartPhase(state, { next }) {
let { G, ctx } = state;
const conf = GetPhase(ctx);
// Run any phase setup code provided by the user.
G = conf.wrapped.onBegin(state);
next.push({ fn: StartTurn });
return { ...state, G, ctx };
}
function StartTurn(state, { currentPlayer }) {
let { G, ctx } = state;
const conf = GetPhase(ctx);
// Initialize the turn order state.
if (currentPlayer) {
ctx = { ...ctx, currentPlayer };
if (conf.turn.activePlayers) {
ctx = SetActivePlayers(ctx, conf.turn.activePlayers);
}
}
else {
// This is only called at the beginning of the phase
// when there is no currentPlayer yet.
ctx = InitTurnOrderState(state, conf.turn);
}
const turn = ctx.turn + 1;
ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] };
G = conf.turn.wrapped.onBegin({ ...state, G, ctx });
return { ...state, G, ctx, _undo: [], _redo: [] };
}
////////////
// Update //
////////////
function UpdatePhase(state, { arg, next, phase }) {
const conf = GetPhase({ phase });
let { ctx } = state;
if (arg && arg.next) {
if (arg.next in phaseMap) {
ctx = { ...ctx, phase: arg.next };
}
else {
error('invalid phase: ' + arg.next);
return state;
}
}
else if (conf.next !== undefined) {
ctx = { ...ctx, phase: conf.next };
}
else {
ctx = { ...ctx, phase: null };
}
state = { ...state, ctx };
// Start the new phase.
next.push({ fn: StartPhase });
return state;
}
function UpdateTurn(state, { arg, currentPlayer, next }) {
let { G, ctx } = state;
const conf = GetPhase(ctx);
// Update turn order state.
const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, conf.turn, arg);
ctx = newCtx;
state = { ...state, G, ctx };
if (endPhase) {
next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase });
}
else {
next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer });
}
return state;
}
function UpdateStage(state, { arg, playerID }) {
if (typeof arg === 'string' || arg === Stage.NULL) {
arg = { stage: arg };
}
let { ctx } = state;
let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = ctx;
// Checking if stage is valid, even Stage.NULL
if (arg.stage !== undefined) {
if (activePlayers === null) {
activePlayers = {};
}
activePlayers[playerID] = arg.stage;
_activePlayersNumMoves[playerID] = 0;
if (arg.moveLimit) {
if (_activePlayersMoveLimit === null) {
_activePlayersMoveLimit = {};
}
_activePlayersMoveLimit[playerID] = arg.moveLimit;
}
}
ctx = {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
};
return { ...state, ctx };
}
///////////////
// ShouldEnd //
///////////////
function ShouldEndGame(state) {
return wrapped.endIf(state);
}
function ShouldEndPhase(state) {
const conf = GetPhase(state.ctx);
return conf.wrapped.endIf(state);
}
function ShouldEndTurn(state) {
const conf = GetPhase(state.ctx);
// End the turn if the required number of moves has been made.
const currentPlayerMoves = state.ctx.numMoves || 0;
if (conf.turn.moveLimit && currentPlayerMoves >= conf.turn.moveLimit) {
return true;
}
return conf.turn.wrapped.endIf(state);
}
/////////
// End //
/////////
function EndGame(state, { arg, phase }) {
state = EndPhase(state, { phase });
if (arg === undefined) {
arg = true;
}
state = { ...state, ctx: { ...state.ctx, gameover: arg } };
// Run game end hook.
const G = wrapped.onEnd(state);
return { ...state, G };
}
function EndPhase(state, { arg, next, turn, automatic }) {
// End the turn first.
state = EndTurn(state, { turn, force: true, automatic: true });
let G = state.G;
let ctx = state.ctx;
if (next) {
next.push({ fn: UpdatePhase, arg, phase: ctx.phase });
}
// If we aren't in a phase, there is nothing else to do.
if (ctx.phase === null) {
return state;
}
// Run any cleanup code for the phase that is about to end.
const conf = GetPhase(ctx);
G = conf.wrapped.onEnd(state);
// Reset the phase.
ctx = { ...ctx, phase: null };
// Add log entry.
const action = gameEvent('endPhase', arg);
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
if (automatic) {
logEntry.automatic = true;
}
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog };
}
function EndTurn(state, { arg, next, turn, force, automatic, playerID }) {
// This is not the turn that EndTurn was originally
// called for. The turn was probably ended some other way.
if (turn !== state.ctx.turn) {
return state;
}
let { G, ctx } = state;
const conf = GetPhase(ctx);
// Prevent ending the turn if moveLimit hasn't been reached.
const currentPlayerMoves = ctx.numMoves || 0;
if (!force &&
conf.turn.moveLimit &&
currentPlayerMoves < conf.turn.moveLimit) {
info(`cannot end turn before making ${conf.turn.moveLimit} moves`);
return state;
}
// Run turn-end triggers.
G = conf.turn.wrapped.onEnd(state);
if (next) {
next.push({ fn: UpdateTurn, arg, currentPlayer: ctx.currentPlayer });
}
// Reset activePlayers.
ctx = { ...ctx, activePlayers: null };
// Remove player from playerOrder
if (arg && arg.remove) {
playerID = playerID || ctx.currentPlayer;
const playOrder = ctx.playOrder.filter((i) => i != playerID);
const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos;
ctx = { ...ctx, playOrder, playOrderPos };
if (playOrder.length === 0) {
next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase });
return state;
}
}
// Add log entry.
const action = gameEvent('endTurn', arg);
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
if (automatic) {
logEntry.automatic = true;
}
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog, _undo: [], _redo: [] };
}
function EndStage(state, { arg, next, automatic, playerID }) {
playerID = playerID || state.ctx.currentPlayer;
let { ctx } = state;
let { activePlayers, _activePlayersMoveLimit } = ctx;
const playerInStage = activePlayers !== null && playerID in activePlayers;
if (!arg && playerInStage) {
const conf = GetPhase(ctx);
const stage = conf.turn.stages[activePlayers[playerID]];
if (stage && stage.next)
arg = stage.next;
}
// Checking if arg is a valid stage, even Stage.NULL
if (next && arg !== undefined) {
next.push({ fn: UpdateStage, arg, playerID });
}
// If player isn’t in a stage, there is nothing else to do.
if (!playerInStage)
return state;
// Remove player from activePlayers.
activePlayers = Object.keys(activePlayers)
.filter((id) => id !== playerID)
.reduce((obj, key) => {
obj[key] = activePlayers[key];
return obj;
}, {});
if (_activePlayersMoveLimit) {
// Remove player from _activePlayersMoveLimit.
_activePlayersMoveLimit = Object.keys(_activePlayersMoveLimit)
.filter((id) => id !== playerID)
.reduce((obj, key) => {
obj[key] = _activePlayersMoveLimit[key];
return obj;
}, {});
}
ctx = UpdateActivePlayersOnceEmpty({
...ctx,
activePlayers,
_activePlayersMoveLimit,
});
// Add log entry.
const action = gameEvent('endStage', arg);
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
if (automatic) {
logEntry.automatic = true;
}
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, ctx, deltalog };
}
/**
* Retrieves the relevant move that can be played by playerID.
*
* If ctx.activePlayers is set (i.e. one or more players are in some stage),
* then it attempts to find the move inside the stages config for
* that turn. If the stage for a player is '', then the player is
* allowed to make a move (as determined by the phase config), but
* isn't restricted to a particular set as defined in the stage config.
*
* If not, it then looks for the move inside the phase.
*
* If it doesn't find the move there, it looks at the global move definition.
*
* @param {object} ctx
* @param {string} name
* @param {string} playerID
*/
function GetMove(ctx, name, playerID) {
const conf = GetPhase(ctx);
const stages = conf.turn.stages;
const { activePlayers } = ctx;
if (activePlayers &&
activePlayers[playerID] !== undefined &&
activePlayers[playerID] !== Stage.NULL &&
stages[activePlayers[playerID]] !== undefined &&
stages[activePlayers[playerID]].moves !== undefined) {
// Check if moves are defined for the player's stage.
const stage = stages[activePlayers[playerID]];
const moves = stage.moves;
if (name in moves) {
return moves[name];
}
}
else if (conf.moves) {
// Check if moves are defined for the current phase.
if (name in conf.moves) {
return conf.moves[name];
}
}
else if (name in moves) {
// Check for the move globally.
return moves[name];
}
return null;
}
function ProcessMove(state, action) {
const conf = GetPhase(state.ctx);
const move = GetMove(state.ctx, action.type, action.playerID);
const shouldCount = !move || typeof move === 'function' || move.noLimit !== true;
const { ctx } = state;
const { _activePlayersNumMoves } = ctx;
const { playerID } = action;
let numMoves = state.ctx.numMoves;
if (shouldCount) {
if (playerID == state.ctx.currentPlayer) {
numMoves++;
}
if (ctx.activePlayers)
_activePlayersNumMoves[playerID]++;
}
state = {
...state,
ctx: {
...ctx,
numMoves,
_activePlayersNumMoves,
},
};
if (ctx._activePlayersMoveLimit &&
_activePlayersNumMoves[playerID] >= ctx._activePlayersMoveLimit[playerID]) {
state = EndStage(state, { playerID, automatic: true });
}
const G = conf.turn.wrapped.onMove(state);
state = { ...state, G };
const events = [{ fn: OnMove }];
return Process(state, events);
}
function SetStageEvent(state, playerID, arg) {
return Process(state, [{ fn: EndStage, arg, playerID }]);
}
function EndStageEvent(state, playerID) {
return Process(state, [{ fn: EndStage, playerID }]);
}
function SetPhaseEvent(state, _playerID, newPhase) {
return Process(state, [
{
fn: EndPhase,
phase: state.ctx.phase,
turn: state.ctx.turn,
arg: { next: newPhase },
},
]);
}
function EndPhaseEvent(state) {
return Process(state, [
{ fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn },
]);
}
function EndTurnEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
function PassEvent(state, _playerID, arg) {
return Process(state, [
{
fn: EndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
force: true,
arg,
},
]);
}
function EndGameEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
const eventHandlers = {
endStage: EndStageEvent,
setStage: SetStageEvent,
endTurn: EndTurnEvent,
pass: PassEvent,
endPhase: EndPhaseEvent,
setPhase: SetPhaseEvent,
endGame: EndGameEvent,
setActivePlayers: SetActivePlayersEvent,
};
const enabledEventNames = [];
if (events.endTurn !== false) {
enabledEventNames.push('endTurn');
}
if (events.pass !== false) {
enabledEventNames.push('pass');
}
if (events.endPhase !== false) {
enabledEventNames.push('endPhase');
}
if (events.setPhase !== false) {
enabledEventNames.push('setPhase');
}
if (events.endGame !== false) {
enabledEventNames.push('endGame');
}
if (events.setActivePlayers !== false) {
enabledEventNames.push('setActivePlayers');
}
if (events.endStage !== false) {
enabledEventNames.push('endStage');
}
if (events.setStage !== false) {
enabledEventNames.push('setStage');
}
function ProcessEvent(state, action) {
const { type, playerID, args } = action.payload;
if (Object.prototype.hasOwnProperty.call(eventHandlers, type)) {
const eventArgs = [state, playerID].concat(args);
return eventHandlers[type].apply({}, eventArgs);
}
return state;
}
function IsPlayerActive(_G, ctx, playerID) {
if (ctx.activePlayers) {
return playerID in ctx.activePlayers;
}
return ctx.currentPlayer === playerID;
}
return {
ctx: (numPlayers) => ({
numPlayers,
turn: 0,
currentPlayer: '0',
playOrder: [...new Array(numPlayers)].map((_d, i) => i + ''),
playOrderPos: 0,
phase: startingPhase,
activePlayers: null,
}),
init: (state) => {
return Process(state, [{ fn: StartGame }]);
},
isPlayerActive: IsPlayerActive,
eventHandlers,
eventNames: Object.keys(eventHandlers),
enabledEventNames,
moveMap,
moveNames: [...moveNames.values()],
processMove: ProcessMove,
processEvent: ProcessEvent,
getMove: GetMove,
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function IsProcessed(game) {
return game.processMove !== undefined;
}
/**
* Helper to generate the game move reducer. The returned
* reducer has the following signature:
*
* (G, action, ctx) => {}
*
* You can roll your own if you like, or use any Redux
* addon to generate such a reducer.
*
* The convention used in this framework is to
* have action.type contain the name of the move, and
* action.args contain any additional arguments as an
* Array.
*/
function ProcessGameConfig(game) {
// The Game() function has already been called on this
// config object, so just pass it through.
if (IsProcessed(game)) {
return game;
}
if (game.name === undefined)
game.name = 'default';
if (game.disableUndo === undefined)
game.disableUndo = false;
if (game.setup === undefined)
game.setup = () => ({});
if (game.moves === undefined)
game.moves = {};
if (game.playerView === undefined)
game.playerView = (G) => G;
if (game.plugins === undefined)
game.plugins = [];
game.plugins.forEach((plugin) => {
if (plugin.name === undefined) {
throw new Error('Plugin missing name attribute');
}
if (plugin.name.includes(' ')) {
throw new Error(plugin.name + ': Plugin name must not include spaces');
}
});
if (game.name.includes(' ')) {
throw new Error(game.name + ': Game name must not include spaces');
}
const flow = Flow(game);
return {
...game,
flow,
moveNames: flow.moveNames,
pluginNames: game.plugins.map((p) => p.name),
processMove: (state, action) => {
let moveFn = flow.getMove(state.ctx, action.type, action.playerID);
if (IsLongFormMove(moveFn)) {
moveFn = moveFn.move;
}
if (moveFn instanceof Function) {
const fn = FnWrap(moveFn, game.plugins);
const ctxWithAPI = {
...EnhanceCtx(state),
playerID: action.playerID,
};
let args = [];
if (action.args !== undefined) {
args = args.concat(action.args);
}
return fn(state.G, ctxWithAPI, ...args);
}
error(`invalid move object: ${action.type}`);
return state.G;
},
};
}
function IsLongFormMove(move) {
return move instanceof Object && move.move !== undefined;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Check if the payload for the passed action contains a playerID.
*/
const actionHasPlayerID = (action) => action.payload.playerID !== null && action.payload.playerID !== undefined;
/**
* Returns true if a move can be undone.
*/
const CanUndoMove = (G, ctx, move) => {
function HasUndoable(move) {
return move.undoable !== undefined;
}
function IsFunction(undoable) {
return undoable instanceof Function;
}
if (!HasUndoable(move)) {
return true;
}
if (IsFunction(move.undoable)) {
return move.undoable(G, ctx);
}
return move.undoable;
};
/**
* Update the undo and redo stacks for a move or event.
*/
function updateUndoRedoState(state, opts) {
if (opts.game.disableUndo)
return state;
const undoEntry = {
G: state.G,
ctx: state.ctx,
plugins: state.plugins,
playerID: opts.action.payload.playerID || state.ctx.currentPlayer,
};
if (opts.action.type === 'MAKE_MOVE') {
undoEntry.moveType = opts.action.payload.type;
}
return {
...state,
_undo: [...state._undo, undoEntry],
// Always reset redo stack when making a move or event
_redo: [],
};
}
/**
* Process state, adding the initial deltalog for this action.
*/
function initializeDeltalog(state, action, move) {
// Create a log entry for this action.
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
const pluginLogMetadata = state.plugins.log.data.metadata;
if (pluginLogMetadata !== undefined) {
logEntry.metadata = pluginLogMetadata;
}
if (typeof move === 'object' && move.redact === true) {
logEntry.redact = true;
}
return {
...state,
deltalog: [logEntry],
};
}
/**
* CreateGameReducer
*
* Creates the main game state reducer.
*/
function CreateGameReducer({ game, isClient, }) {
game = ProcessGameConfig(game);
/**
* GameReducer
*
* Redux reducer that maintains the overall game state.
* @param {object} state - The state before the action.
* @param {object} action - A Redux action.
*/
return (state = null, action) => {
switch (action.type) {
case GAME_EVENT: {
state = { ...state, deltalog: [] };
// Process game events only on the server.
// These events like `endTurn` typically
// contain code that may rely on secret state
// and cannot be computed on the client.
if (isClient) {
return state;
}
// Disallow events once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot call event after game end`);
return state;
}
// Ignore the event if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed event: ${action.payload.type}`);
return state;
}
// Execute plugins.
state = Enhance(state, {
game,
isClient: false,
playerID: action.payload.playerID,
});
// Process event.
let newState = game.flow.processEvent(state, action);
// Execute plugins.
newState = Flush(newState, { game, isClient: false });
// Update undo / redo state.
newState = updateUndoRedoState(newState, { game, action });
return { ...newState, _stateID: state._stateID + 1 };
}
case MAKE_MOVE: {
state = { ...state, deltalog: [] };
// Check whether the move is allowed at this time.
const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer);
if (move === null) {
error(`disallowed move: ${action.payload.type}`);
return state;
}
// Don't run move on client if move says so.
if (isClient && move.client === false) {
return state;
}
// Disallow moves once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot make move after game end`);
return state;
}
// Ignore the move if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed move: ${action.payload.type}`);
return state;
}
// Execute plugins.
state = Enhance(state, {
game,
isClient,
playerID: action.payload.playerID,
});
// Process the move.
const G = game.processMove(state, action.payload);
// The game declared the move as invalid.
if (G === INVALID_MOVE) {
error(`invalid move: ${action.payload.type} args: ${action.payload.args}`);
return state;
}
const newState = { ...state, G };
// Some plugin indicated that it is not suitable to be
// materialized on the client (and must wait for the server
// response instead).
if (isClient && NoClient(newState, { game })) {
return state;
}
state = newState;
// If we're on the client, just process the move
// and no triggers in multiplayer mode.
// These will be processed on the server, which
// will send back a state update.
if (isClient) {
state = Flush(state, {
game,
isClient: true,
});
return {
...state,
_stateID: state._stateID + 1,
};
}
// On the server, construct the deltalog.
state = initializeDeltalog(state, action, move);
// Allow the flow reducer to process any triggers that happen after moves.
state = game.flow.processMove(state, action.payload);
state = Flush(state, { game });
// Update undo / redo state.
state = updateUndoRedoState(state, { game, action });
return {
...state,
_stateID: state._stateID + 1,
};
}
case RESET:
case UPDATE:
case SYNC: {
return action.state;
}
case UNDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Undo is not enabled');
return state;
}
const { _undo, _redo } = state;
if (_undo.length < 2) {
return state;
}
const last = _undo[_undo.length - 1];
const restore = _undo[_undo.length - 2];
// Only allow players to undo their own moves.
if (actionHasPlayerID(action) &&
action.payload.playerID !== last.playerID) {
return state;
}
// Only allow undoable moves to be undone.
const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID);
if (!CanUndoMove(state.G, state.ctx, lastMove)) {
return state;
}
state = initializeDeltalog(state, action);
return {
...state,
G: restore.G,
ctx: restore.ctx,
plugins: restore.plugins,
_stateID: state._stateID + 1,
_undo: _undo.slice(0, -1),
_redo: [last, ..._redo],
};
}
case REDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Redo is not enabled');
return state;
}
const { _undo, _redo } = state;
if (_redo.length == 0) {
return state;
}
const first = _redo[0];
// Only allow players to redo their own undos.
if (actionHasPlayerID(action) &&
action.payload.playerID !== first.playerID) {
return state;
}
state = initializeDeltalog(state, action);
return {
...state,
G: first.G,
ctx: first.ctx,
plugins: first.plugins,
_stateID: state._stateID + 1,
_undo: [..._undo, first],
_redo: _redo.slice(1),
};
}
case PLUGIN: {
return ProcessAction(state, action, { game });
}
default: {
return state;
}
}
};
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Creates the initial game state.
*/
function InitializeGame({ game, numPlayers, setupData, }) {
game = ProcessGameConfig(game);
if (!numPlayers) {
numPlayers = 2;
}
const ctx = game.flow.ctx(numPlayers);
let state = {
// User managed state.
G: {},
// Framework managed state.
ctx,
// Plugin related state.
plugins: {},
};
// Run plugins over initial state.
state = Setup(state, { game });
state = Enhance(state, { game, playerID: undefined });
const enhancedCtx = EnhanceCtx(state);
state.G = game.setup(enhancedCtx, setupData);
let initial = {
...state,
// List of {G, ctx} pairs that can be undone.
_undo: [],
// List of {G, ctx} pairs that can be redone.
_redo: [],
// A monotonically non-decreasing ID to ensure that
// state updates are only allowed from clients that
// are at the same version that the server.
_stateID: 0,
};
initial = game.flow.init(initial);
initial = Flush(initial, { game });
// Initialize undo stack.
if (!game.disableUndo) {
initial._undo = [
{
G: initial.G,
ctx: initial.ctx,
plugins: initial.plugins,
},
];
}
return initial;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class Transport {
constructor({ store, gameName, playerID, matchID, credentials, numPlayers, }) {
this.store = store;
this.gameName = gameName || 'default';
this.playerID = playerID || null;
this.matchID = matchID || 'default';
this.credentials = credentials;
this.numPlayers = numPlayers || 2;
}
}
/**
* This class doesn’t do anything, but simplifies the client class by providing
* dummy functions to call, so we don’t need to mock them in the client.
*/
class DummyImpl extends Transport {
connect() { }
disconnect() { }
onAction() { }
onChatMessage() { }
subscribe() { }
subscribeChatMessage() { }
subscribeMatchData() { }
updateCredentials() { }
updateMatchID() { }
updatePlayerID() { }
}
const DummyTransport = (opts) => new DummyImpl(opts);
const subscriber_queue = [];
/**
* Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions
*/
function writable(value, start = noop) {
let stop;
const subscribers = [];
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) { // store is ready
const run_queue = !subscriber_queue.length;
for (let i = 0; i < subscribers.length; i += 1) {
const s = subscribers[i];
s[1]();
subscriber_queue.push(s, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.push(subscriber);
if (subscribers.length === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
const index = subscribers.indexOf(subscriber);
if (index !== -1) {
subscribers.splice(index, 1);
}
if (subscribers.length === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
function cubicOut(t) {
const f = t - 1.0;
return f * f * f + 1.0;
}
function fly(node, { delay = 0, duration = 400, easing = cubicOut, x = 0, y = 0, opacity = 0 }) {
const style = getComputedStyle(node);
const target_opacity = +style.opacity;
const transform = style.transform === 'none' ? '' : style.transform;
const od = target_opacity * (1 - opacity);
return {
delay,
duration,
easing,
css: (t, u) => `
transform: ${transform} translate(${(1 - t) * x}px, ${(1 - t) * y}px);
opacity: ${target_opacity - (od * u)}`
};
}
/* src/client/debug/Menu.svelte generated by Svelte v3.24.0 */
function add_css() {
var style = element("style");
style.id = "svelte-14p9tpy-style";
style.textContent = ".menu.svelte-14p9tpy{display:flex;margin-top:-10px;flex-direction:row-reverse;border:1px solid #ccc;border-radius:5px 5px 0 0;height:25px;line-height:25px;margin-right:-500px;transform-origin:bottom right;transform:rotate(-90deg) translate(0, -500px)}.menu-item.svelte-14p9tpy{line-height:25px;cursor:pointer;border:0;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-14p9tpy:first-child{border-radius:0 5px 0 0}.menu-item.svelte-14p9tpy:last-child{border-radius:5px 0 0 0}.menu-item.active.svelte-14p9tpy{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-14p9tpy:hover,.menu-item.svelte-14p9tpy:focus{background:#eee;color:#555}";
append(document.head, style);
}
function get_each_context(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[4] = list[i][0];
child_ctx[5] = list[i][1].label;
return child_ctx;
}
// (57:2) {#each Object.entries(panes) as [key, {label}
function create_each_block(ctx) {
let button;
let t0_value = /*label*/ ctx[5] + "";
let t0;
let t1;
let mounted;
let dispose;
function click_handler(...args) {
return /*click_handler*/ ctx[3](/*key*/ ctx[4], ...args);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "menu-item svelte-14p9tpy");
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*panes*/ 2 && t0_value !== (t0_value = /*label*/ ctx[5] + "")) set_data(t0, t0_value);
if (dirty & /*pane, Object, panes*/ 3) {
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment(ctx) {
let nav;
let each_value = Object.entries(/*panes*/ ctx[1]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
}
return {
c() {
nav = element("nav");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(nav, "class", "menu svelte-14p9tpy");
},
m(target, anchor) {
insert(target, nav, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(nav, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*pane, Object, panes, dispatch*/ 7) {
each_value = Object.entries(/*panes*/ ctx[1]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block(child_ctx);
each_blocks[i].c();
each_blocks[i].m(nav, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(nav);
destroy_each(each_blocks, detaching);
}
};
}
function instance($$self, $$props, $$invalidate) {
let { pane } = $$props;
let { panes } = $$props;
const dispatch = createEventDispatcher();
const click_handler = key => dispatch("change", key);
$$self.$set = $$props => {
if ("pane" in $$props) $$invalidate(0, pane = $$props.pane);
if ("panes" in $$props) $$invalidate(1, panes = $$props.panes);
};
return [pane, panes, dispatch, click_handler];
}
class Menu extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-14p9tpy-style")) add_css();
init(this, options, instance, create_fragment, safe_not_equal, { pane: 0, panes: 1 });
}
}
var contextKey = {};
/* node_modules/svelte-json-tree-auto/src/JSONArrow.svelte generated by Svelte v3.24.0 */
function add_css$1() {
var style = element("style");
style.id = "svelte-1vyml86-style";
style.textContent = ".container.svelte-1vyml86{display:inline-block;cursor:pointer;transform:translate(calc(0px - var(--li-identation)), -50%);position:absolute;top:50%;padding-right:100%}.arrow.svelte-1vyml86{transform-origin:25% 50%;position:relative;line-height:1.1em;font-size:0.75em;margin-left:0;transition:150ms;color:var(--arrow-sign);user-select:none;font-family:'Courier New', Courier, monospace}.expanded.svelte-1vyml86{transform:rotateZ(90deg) translateX(-3px)}";
append(document.head, style);
}
function create_fragment$1(ctx) {
let div1;
let div0;
let mounted;
let dispose;
return {
c() {
div1 = element("div");
div0 = element("div");
div0.textContent = `${"▶"}`;
attr(div0, "class", "arrow svelte-1vyml86");
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
attr(div1, "class", "container svelte-1vyml86");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
if (!mounted) {
dispose = listen(div1, "click", /*click_handler*/ ctx[1]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*expanded*/ 1) {
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
mounted = false;
dispose();
}
};
}
function instance$1($$self, $$props, $$invalidate) {
let { expanded } = $$props;
function click_handler(event) {
bubble($$self, event);
}
$$self.$set = $$props => {
if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded);
};
return [expanded, click_handler];
}
class JSONArrow extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1vyml86-style")) add_css$1();
init(this, options, instance$1, create_fragment$1, safe_not_equal, { expanded: 0 });
}
}
/* node_modules/svelte-json-tree-auto/src/JSONKey.svelte generated by Svelte v3.24.0 */
function add_css$2() {
var style = element("style");
style.id = "svelte-1vlbacg-style";
style.textContent = "label.svelte-1vlbacg{display:inline-block;color:var(--label-color);padding:0}.spaced.svelte-1vlbacg{padding-right:var(--li-colon-space)}";
append(document.head, style);
}
// (16:0) {#if showKey && key}
function create_if_block(ctx) {
let label;
let span;
let t0;
let t1;
let mounted;
let dispose;
return {
c() {
label = element("label");
span = element("span");
t0 = text(/*key*/ ctx[0]);
t1 = text(/*colon*/ ctx[2]);
attr(label, "class", "svelte-1vlbacg");
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
},
m(target, anchor) {
insert(target, label, anchor);
append(label, span);
append(span, t0);
append(span, t1);
if (!mounted) {
dispose = listen(label, "click", /*click_handler*/ ctx[5]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*key*/ 1) set_data(t0, /*key*/ ctx[0]);
if (dirty & /*colon*/ 4) set_data(t1, /*colon*/ ctx[2]);
if (dirty & /*isParentExpanded*/ 2) {
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(label);
mounted = false;
dispose();
}
};
}
function create_fragment$2(ctx) {
let if_block_anchor;
let if_block = /*showKey*/ ctx[3] && /*key*/ ctx[0] && create_if_block(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*showKey*/ ctx[3] && /*key*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function instance$2($$self, $$props, $$invalidate) {
let { key } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray = false } = $$props,
{ colon = ":" } = $$props;
function click_handler(event) {
bubble($$self, event);
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ("colon" in $$props) $$invalidate(2, colon = $$props.colon);
};
let showKey;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded, isParentArray, key*/ 19) {
$: $$invalidate(3, showKey = isParentExpanded || !isParentArray || key != +key);
}
};
return [key, isParentExpanded, colon, showKey, isParentArray, click_handler];
}
class JSONKey extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1vlbacg-style")) add_css$2();
init(this, options, instance$2, create_fragment$2, safe_not_equal, {
key: 0,
isParentExpanded: 1,
isParentArray: 4,
colon: 2
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONNested.svelte generated by Svelte v3.24.0 */
function add_css$3() {
var style = element("style");
style.id = "svelte-rwxv37-style";
style.textContent = "label.svelte-rwxv37{display:inline-block}.indent.svelte-rwxv37{padding-left:var(--li-identation)}.collapse.svelte-rwxv37{--li-display:inline;display:inline;font-style:italic}.comma.svelte-rwxv37{margin-left:-0.5em;margin-right:0.5em}label.svelte-rwxv37{position:relative}";
append(document.head, style);
}
function get_each_context$1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[12] = list[i];
child_ctx[20] = i;
return child_ctx;
}
// (57:4) {#if expandable && isParentExpanded}
function create_if_block_3(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[15]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (75:4) {:else}
function create_else_block(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(span);
}
};
}
// (63:4) {#if isParentExpanded}
function create_if_block$1(ctx) {
let ul;
let t;
let current;
let mounted;
let dispose;
let each_value = /*slicedKeys*/ ctx[13];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length && create_if_block_1();
return {
c() {
ul = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(ul, "class", "svelte-rwxv37");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul, null);
}
append(ul, t);
if (if_block) if_block.m(ul, null);
current = true;
if (!mounted) {
dispose = listen(ul, "click", /*expand*/ ctx[16]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*expanded, previewKeys, getKey, slicedKeys, isArray, getValue, getPreviewValue*/ 10129) {
each_value = /*slicedKeys*/ ctx[13];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$1(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$1(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length) {
if (if_block) ; else {
if_block = create_if_block_1();
if_block.c();
if_block.m(ul, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
mounted = false;
dispose();
}
};
}
// (67:10) {#if !expanded && index < previewKeys.length - 1}
function create_if_block_2(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = ",";
attr(span, "class", "comma svelte-rwxv37");
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
// (65:8) {#each slicedKeys as key, index}
function create_each_block$1(ctx) {
let jsonnode;
let t;
let if_block_anchor;
let current;
jsonnode = new JSONNode({
props: {
key: /*getKey*/ ctx[8](/*key*/ ctx[12]),
isParentExpanded: /*expanded*/ ctx[0],
isParentArray: /*isArray*/ ctx[4],
value: /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12])
}
});
let if_block = !/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1 && create_if_block_2();
return {
c() {
create_component(jsonnode.$$.fragment);
t = space();
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*getKey, slicedKeys*/ 8448) jsonnode_changes.key = /*getKey*/ ctx[8](/*key*/ ctx[12]);
if (dirty & /*expanded*/ 1) jsonnode_changes.isParentExpanded = /*expanded*/ ctx[0];
if (dirty & /*isArray*/ 16) jsonnode_changes.isParentArray = /*isArray*/ ctx[4];
if (dirty & /*expanded, getValue, slicedKeys, getPreviewValue*/ 9729) jsonnode_changes.value = /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12]);
jsonnode.$set(jsonnode_changes);
if (!/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1) {
if (if_block) ; else {
if_block = create_if_block_2();
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t);
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (71:8) {#if slicedKeys.length < previewKeys.length }
function create_if_block_1(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$3(ctx) {
let li;
let label_1;
let t0;
let jsonkey;
let t1;
let span1;
let span0;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block1;
let t5;
let span2;
let t6;
let current;
let mounted;
let dispose;
let if_block0 = /*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2] && create_if_block_3(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[12],
colon: /*context*/ ctx[14].colon,
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3]
}
});
jsonkey.$on("click", /*toggleExpand*/ ctx[15]);
const if_block_creators = [create_if_block$1, create_else_block];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*isParentExpanded*/ ctx[2]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
li = element("li");
label_1 = element("label");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span1 = element("span");
span0 = element("span");
t2 = text(/*label*/ ctx[1]);
t3 = text(/*bracketOpen*/ ctx[5]);
t4 = space();
if_block1.c();
t5 = space();
span2 = element("span");
t6 = text(/*bracketClose*/ ctx[6]);
attr(label_1, "class", "svelte-rwxv37");
attr(li, "class", "svelte-rwxv37");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
},
m(target, anchor) {
insert(target, li, anchor);
append(li, label_1);
if (if_block0) if_block0.m(label_1, null);
append(label_1, t0);
mount_component(jsonkey, label_1, null);
append(label_1, t1);
append(label_1, span1);
append(span1, span0);
append(span0, t2);
append(span1, t3);
append(li, t4);
if_blocks[current_block_type_index].m(li, null);
append(li, t5);
append(li, span2);
append(span2, t6);
current = true;
if (!mounted) {
dispose = listen(span1, "click", /*toggleExpand*/ ctx[15]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*expandable, isParentExpanded*/ 2052) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_3(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(label_1, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 4096) jsonkey_changes.key = /*key*/ ctx[12];
if (dirty & /*isParentExpanded*/ 4) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (!current || dirty & /*label*/ 2) set_data(t2, /*label*/ ctx[1]);
if (!current || dirty & /*bracketOpen*/ 32) set_data(t3, /*bracketOpen*/ ctx[5]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
}
transition_in(if_block1, 1);
if_block1.m(li, t5);
}
if (!current || dirty & /*bracketClose*/ 64) set_data(t6, /*bracketClose*/ ctx[6]);
if (dirty & /*isParentExpanded*/ 4) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$3($$self, $$props, $$invalidate) {
let { key } = $$props,
{ keys } = $$props,
{ colon = ":" } = $$props,
{ label = "" } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ isArray = false } = $$props,
{ bracketOpen } = $$props,
{ bracketClose } = $$props;
let { previewKeys = keys } = $$props;
let { getKey = key => key } = $$props;
let { getValue = key => key } = $$props;
let { getPreviewValue = getValue } = $$props;
let { expanded = false } = $$props, { expandable = true } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
function expand() {
$$invalidate(0, expanded = true);
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(12, key = $$props.key);
if ("keys" in $$props) $$invalidate(17, keys = $$props.keys);
if ("colon" in $$props) $$invalidate(18, colon = $$props.colon);
if ("label" in $$props) $$invalidate(1, label = $$props.label);
if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ("isArray" in $$props) $$invalidate(4, isArray = $$props.isArray);
if ("bracketOpen" in $$props) $$invalidate(5, bracketOpen = $$props.bracketOpen);
if ("bracketClose" in $$props) $$invalidate(6, bracketClose = $$props.bracketClose);
if ("previewKeys" in $$props) $$invalidate(7, previewKeys = $$props.previewKeys);
if ("getKey" in $$props) $$invalidate(8, getKey = $$props.getKey);
if ("getValue" in $$props) $$invalidate(9, getValue = $$props.getValue);
if ("getPreviewValue" in $$props) $$invalidate(10, getPreviewValue = $$props.getPreviewValue);
if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded);
if ("expandable" in $$props) $$invalidate(11, expandable = $$props.expandable);
};
let slicedKeys;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded*/ 4) {
$: if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
if ($$self.$$.dirty & /*expanded, keys, previewKeys*/ 131201) {
$: $$invalidate(13, slicedKeys = expanded ? keys : previewKeys.slice(0, 5));
}
};
return [
expanded,
label,
isParentExpanded,
isParentArray,
isArray,
bracketOpen,
bracketClose,
previewKeys,
getKey,
getValue,
getPreviewValue,
expandable,
key,
slicedKeys,
context,
toggleExpand,
expand,
keys,
colon
];
}
class JSONNested extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-rwxv37-style")) add_css$3();
init(this, options, instance$3, create_fragment$3, safe_not_equal, {
key: 12,
keys: 17,
colon: 18,
label: 1,
isParentExpanded: 2,
isParentArray: 3,
isArray: 4,
bracketOpen: 5,
bracketClose: 6,
previewKeys: 7,
getKey: 8,
getValue: 9,
getPreviewValue: 10,
expanded: 0,
expandable: 11
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONObjectNode.svelte generated by Svelte v3.24.0 */
function create_fragment$4(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[5],
previewKeys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: "" + (/*nodeType*/ ctx[3] + " "),
bracketOpen: "{",
bracketClose: "}"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*keys*/ 32) jsonnested_changes.previewKeys = /*keys*/ ctx[5];
if (dirty & /*nodeType*/ 8) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + " ");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$4($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ nodeType } = $$props;
let { expanded = true } = $$props;
function getValue(key) {
return value[key];
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(7, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType);
if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded);
};
let keys;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 128) {
$: $$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
};
return [
key,
isParentExpanded,
isParentArray,
nodeType,
expanded,
keys,
getValue,
value
];
}
class JSONObjectNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$4, create_fragment$4, safe_not_equal, {
key: 0,
value: 7,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONArrayNode.svelte generated by Svelte v3.24.0 */
function create_fragment$5(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
isArray: true,
keys: /*keys*/ ctx[5],
previewKeys: /*previewKeys*/ ctx[6],
getValue: /*getValue*/ ctx[7],
label: "Array(" + /*value*/ ctx[1].length + ")",
bracketOpen: "[",
bracketClose: "]"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*previewKeys*/ 64) jsonnested_changes.previewKeys = /*previewKeys*/ ctx[6];
if (dirty & /*value*/ 2) jsonnested_changes.label = "Array(" + /*value*/ ctx[1].length + ")";
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$5($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props;
let { expanded = JSON.stringify(value).length < 1024 } = $$props;
const filteredKey = new Set(["length"]);
function getValue(key) {
return value[key];
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded);
};
let keys;
let previewKeys;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$: $$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
if ($$self.$$.dirty & /*keys*/ 32) {
$: $$invalidate(6, previewKeys = keys.filter(key => !filteredKey.has(key)));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
expanded,
keys,
previewKeys,
getValue
];
}
class JSONArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$5, create_fragment$5, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableArrayNode.svelte generated by Svelte v3.24.0 */
function create_fragment$6(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey,
getValue,
isArray: true,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
bracketOpen: "{",
bracketClose: "}"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey(key) {
return String(key[0]);
}
function getValue(key) {
return key[1];
}
function instance$6($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ nodeType } = $$props;
let keys = [];
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(5, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
$: {
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, entry]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$6, create_fragment$6, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
class MapEntry {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableMapNode.svelte generated by Svelte v3.24.0 */
function create_fragment$7(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey: getKey$1,
getValue: getValue$1,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
colon: "",
bracketOpen: "{",
bracketClose: "}"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey$1(entry) {
return entry[0];
}
function getValue$1(entry) {
return entry[1];
}
function instance$7($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ nodeType } = $$props;
let keys = [];
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(5, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
$: {
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, new MapEntry(entry[0], entry[1])]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableMapNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$7, create_fragment$7, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONMapEntryNode.svelte generated by Svelte v3.24.0 */
function create_fragment$8(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
key: /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key,
keys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: /*isParentExpanded*/ ctx[2] ? "Entry " : "=> ",
bracketOpen: "{",
bracketClose: "}"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*isParentExpanded, key, value*/ 7) jsonnested_changes.key = /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key;
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.label = /*isParentExpanded*/ ctx[2] ? "Entry " : "=> ";
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$8($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props;
let { expanded = false } = $$props;
const keys = ["key", "value"];
function getValue(key) {
return value[key];
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded);
};
return [key, value, isParentExpanded, isParentArray, expanded, keys, getValue];
}
class JSONMapEntryNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$8, create_fragment$8, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONValueNode.svelte generated by Svelte v3.24.0 */
function add_css$4() {
var style = element("style");
style.id = "svelte-3bjyvl-style";
style.textContent = "li.svelte-3bjyvl{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-3bjyvl{padding-left:var(--li-identation)}.String.svelte-3bjyvl{color:var(--string-color)}.Date.svelte-3bjyvl{color:var(--date-color)}.Number.svelte-3bjyvl{color:var(--number-color)}.Boolean.svelte-3bjyvl{color:var(--boolean-color)}.Null.svelte-3bjyvl{color:var(--null-color)}.Undefined.svelte-3bjyvl{color:var(--undefined-color)}.Function.svelte-3bjyvl{color:var(--function-color);font-style:italic}.Symbol.svelte-3bjyvl{color:var(--symbol-color)}";
append(document.head, style);
}
function create_fragment$9(ctx) {
let li;
let jsonkey;
let t0;
let span;
let t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "";
let t1;
let span_class_value;
let current;
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[0],
colon: /*colon*/ ctx[6],
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
return {
c() {
li = element("li");
create_component(jsonkey.$$.fragment);
t0 = space();
span = element("span");
t1 = text(t1_value);
attr(span, "class", span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"));
attr(li, "class", "svelte-3bjyvl");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t0);
append(li, span);
append(span, t1);
current = true;
},
p(ctx, [dirty]) {
const jsonkey_changes = {};
if (dirty & /*key*/ 1) jsonkey_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*valueGetter, value*/ 6) && t1_value !== (t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "")) set_data(t1, t1_value);
if (!current || dirty & /*nodeType*/ 32 && span_class_value !== (span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"))) {
attr(span, "class", span_class_value);
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(jsonkey);
}
};
}
function instance$9($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ valueGetter = null } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ nodeType } = $$props;
const { colon } = getContext(contextKey);
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
if ("valueGetter" in $$props) $$invalidate(2, valueGetter = $$props.valueGetter);
if ("isParentExpanded" in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ("nodeType" in $$props) $$invalidate(5, nodeType = $$props.nodeType);
};
return [key, value, valueGetter, isParentExpanded, isParentArray, nodeType, colon];
}
class JSONValueNode extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-3bjyvl-style")) add_css$4();
init(this, options, instance$9, create_fragment$9, safe_not_equal, {
key: 0,
value: 1,
valueGetter: 2,
isParentExpanded: 3,
isParentArray: 4,
nodeType: 5
});
}
}
/* node_modules/svelte-json-tree-auto/src/ErrorNode.svelte generated by Svelte v3.24.0 */
function add_css$5() {
var style = element("style");
style.id = "svelte-1ca3gb2-style";
style.textContent = "li.svelte-1ca3gb2{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-1ca3gb2{padding-left:var(--li-identation)}.collapse.svelte-1ca3gb2{--li-display:inline;display:inline;font-style:italic}";
append(document.head, style);
}
function get_each_context$2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[8] = list[i];
child_ctx[10] = i;
return child_ctx;
}
// (40:2) {#if isParentExpanded}
function create_if_block_2$1(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[7]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (45:2) {#if isParentExpanded}
function create_if_block$2(ctx) {
let ul;
let current;
let if_block = /*expanded*/ ctx[0] && create_if_block_1$1(ctx);
return {
c() {
ul = element("ul");
if (if_block) if_block.c();
attr(ul, "class", "svelte-1ca3gb2");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
if (if_block) if_block.m(ul, null);
current = true;
},
p(ctx, dirty) {
if (/*expanded*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*expanded*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$1(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(ul, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
if (if_block) if_block.d();
}
};
}
// (47:6) {#if expanded}
function create_if_block_1$1(ctx) {
let jsonnode;
let t0;
let li;
let jsonkey;
let t1;
let span;
let current;
jsonnode = new JSONNode({
props: {
key: "message",
value: /*value*/ ctx[2].message
}
});
jsonkey = new JSONKey({
props: {
key: "stack",
colon: ":",
isParentExpanded: /*isParentExpanded*/ ctx[3]
}
});
let each_value = /*stack*/ ctx[5];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i));
}
return {
c() {
create_component(jsonnode.$$.fragment);
t0 = space();
li = element("li");
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(li, "class", "svelte-1ca3gb2");
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t0, anchor);
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(span, null);
}
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*value*/ 4) jsonnode_changes.value = /*value*/ ctx[2].message;
jsonnode.$set(jsonnode_changes);
const jsonkey_changes = {};
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (dirty & /*stack*/ 32) {
each_value = /*stack*/ ctx[5];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$2(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$2(child_ctx);
each_blocks[i].c();
each_blocks[i].m(span, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t0);
if (detaching) detach(li);
destroy_component(jsonkey);
destroy_each(each_blocks, detaching);
}
};
}
// (52:12) {#each stack as line, index}
function create_each_block$2(ctx) {
let span;
let t_value = /*line*/ ctx[8] + "";
let t;
let br;
return {
c() {
span = element("span");
t = text(t_value);
br = element("br");
attr(span, "class", "svelte-1ca3gb2");
toggle_class(span, "indent", /*index*/ ctx[10] > 0);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
insert(target, br, anchor);
},
p(ctx, dirty) {
if (dirty & /*stack*/ 32 && t_value !== (t_value = /*line*/ ctx[8] + "")) set_data(t, t_value);
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(br);
}
};
}
function create_fragment$a(ctx) {
let li;
let t0;
let jsonkey;
let t1;
let span;
let t2;
let t3_value = (/*expanded*/ ctx[0] ? "" : /*value*/ ctx[2].message) + "";
let t3;
let t4;
let current;
let mounted;
let dispose;
let if_block0 = /*isParentExpanded*/ ctx[3] && create_if_block_2$1(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[1],
colon: /*context*/ ctx[6].colon,
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
let if_block1 = /*isParentExpanded*/ ctx[3] && create_if_block$2(ctx);
return {
c() {
li = element("li");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
t2 = text("Error: ");
t3 = text(t3_value);
t4 = space();
if (if_block1) if_block1.c();
attr(li, "class", "svelte-1ca3gb2");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
if (if_block0) if_block0.m(li, null);
append(li, t0);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
append(span, t2);
append(span, t3);
append(li, t4);
if (if_block1) if_block1.m(li, null);
current = true;
if (!mounted) {
dispose = listen(span, "click", /*toggleExpand*/ ctx[7]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*isParentExpanded*/ ctx[3]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$1(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(li, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 2) jsonkey_changes.key = /*key*/ ctx[1];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*expanded, value*/ 5) && t3_value !== (t3_value = (/*expanded*/ ctx[0] ? "" : /*value*/ ctx[2].message) + "")) set_data(t3, t3_value);
if (/*isParentExpanded*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block$2(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(li, null);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if (if_block1) if_block1.d();
mounted = false;
dispose();
}
};
}
function instance$a($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props;
let { expanded = false } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon: ":" });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(1, key = $$props.key);
if ("value" in $$props) $$invalidate(2, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded);
};
let stack;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 4) {
$: $$invalidate(5, stack = value.stack.split("\n"));
}
if ($$self.$$.dirty & /*isParentExpanded*/ 8) {
$: if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
};
return [
expanded,
key,
value,
isParentExpanded,
isParentArray,
stack,
context,
toggleExpand
];
}
class ErrorNode extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1ca3gb2-style")) add_css$5();
init(this, options, instance$a, create_fragment$a, safe_not_equal, {
key: 1,
value: 2,
isParentExpanded: 3,
isParentArray: 4,
expanded: 0
});
}
}
function objType(obj) {
const type = Object.prototype.toString.call(obj).slice(8, -1);
if (type === 'Object') {
if (typeof obj[Symbol.iterator] === 'function') {
return 'Iterable';
}
return obj.constructor.name;
}
return type;
}
/* node_modules/svelte-json-tree-auto/src/JSONNode.svelte generated by Svelte v3.24.0 */
function create_fragment$b(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*componentType*/ ctx[5];
function switch_props(ctx) {
return {
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
nodeType: /*nodeType*/ ctx[4],
valueGetter: /*valueGetter*/ ctx[6]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, [dirty]) {
const switch_instance_changes = {};
if (dirty & /*key*/ 1) switch_instance_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) switch_instance_changes.value = /*value*/ ctx[1];
if (dirty & /*isParentExpanded*/ 4) switch_instance_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) switch_instance_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*nodeType*/ 16) switch_instance_changes.nodeType = /*nodeType*/ ctx[4];
if (dirty & /*valueGetter*/ 64) switch_instance_changes.valueGetter = /*valueGetter*/ ctx[6];
if (switch_value !== (switch_value = /*componentType*/ ctx[5])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function instance$b($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props;
function getComponent(nodeType) {
switch (nodeType) {
case "Object":
return JSONObjectNode;
case "Error":
return ErrorNode;
case "Array":
return JSONArrayNode;
case "Iterable":
case "Map":
case "Set":
return typeof value.set === "function"
? JSONIterableMapNode
: JSONIterableArrayNode;
case "MapEntry":
return JSONMapEntryNode;
default:
return JSONValueNode;
}
}
function getValueGetter(nodeType) {
switch (nodeType) {
case "Object":
case "Error":
case "Array":
case "Iterable":
case "Map":
case "Set":
case "MapEntry":
case "Number":
return undefined;
case "String":
return raw => `"${raw}"`;
case "Boolean":
return raw => raw ? "true" : "false";
case "Date":
return raw => raw.toISOString();
case "Null":
return () => "null";
case "Undefined":
return () => "undefined";
case "Function":
case "Symbol":
return raw => raw.toString();
default:
return () => `<${nodeType}>`;
}
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
};
let nodeType;
let componentType;
let valueGetter;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$: $$invalidate(4, nodeType = objType(value));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$: $$invalidate(5, componentType = getComponent(nodeType));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$: $$invalidate(6, valueGetter = getValueGetter(nodeType));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
nodeType,
componentType,
valueGetter
];
}
class JSONNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$b, create_fragment$b, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/Root.svelte generated by Svelte v3.24.0 */
function add_css$6() {
var style = element("style");
style.id = "svelte-773n60-style";
style.textContent = "ul.svelte-773n60{--string-color:var(--json-tree-string-color, #cb3f41);--symbol-color:var(--json-tree-symbol-color, #cb3f41);--boolean-color:var(--json-tree-boolean-color, #112aa7);--function-color:var(--json-tree-function-color, #112aa7);--number-color:var(--json-tree-number-color, #3029cf);--label-color:var(--json-tree-label-color, #871d8f);--arrow-color:var(--json-tree-arrow-color, #727272);--null-color:var(--json-tree-null-color, #8d8d8d);--undefined-color:var(--json-tree-undefined-color, #8d8d8d);--date-color:var(--json-tree-date-color, #8d8d8d);--li-identation:var(--json-tree-li-indentation, 1em);--li-line-height:var(--json-tree-li-line-height, 1.3);--li-colon-space:0.3em;font-size:var(--json-tree-font-size, 12px);font-family:var(--json-tree-font-family, 'Courier New', Courier, monospace)}ul.svelte-773n60 li{line-height:var(--li-line-height);display:var(--li-display, list-item);list-style:none}ul.svelte-773n60,ul.svelte-773n60 ul{padding:0;margin:0}";
append(document.head, style);
}
function create_fragment$c(ctx) {
let ul;
let jsonnode;
let current;
jsonnode = new JSONNode({
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: true,
isParentArray: false
}
});
return {
c() {
ul = element("ul");
create_component(jsonnode.$$.fragment);
attr(ul, "class", "svelte-773n60");
},
m(target, anchor) {
insert(target, ul, anchor);
mount_component(jsonnode, ul, null);
current = true;
},
p(ctx, [dirty]) {
const jsonnode_changes = {};
if (dirty & /*key*/ 1) jsonnode_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) jsonnode_changes.value = /*value*/ ctx[1];
jsonnode.$set(jsonnode_changes);
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(jsonnode);
}
};
}
function instance$c($$self, $$props, $$invalidate) {
setContext(contextKey, {});
let { key = "" } = $$props, { value } = $$props;
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
};
return [key, value];
}
class Root extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-773n60-style")) add_css$6();
init(this, options, instance$c, create_fragment$c, safe_not_equal, { key: 0, value: 1 });
}
}
/* src/client/debug/main/ClientSwitcher.svelte generated by Svelte v3.24.0 */
const { document: document_1 } = globals;
function add_css$7() {
var style = element("style");
style.id = "svelte-jvfq3i-style";
style.textContent = ".svelte-jvfq3i{box-sizing:border-box}section.switcher.svelte-jvfq3i{position:sticky;bottom:0;transform:translateY(20px);margin:40px -20px 0;border-top:1px solid #999;padding:20px;background:#fff}label.svelte-jvfq3i{display:flex;align-items:baseline;gap:5px;font-weight:bold}select.svelte-jvfq3i{min-width:140px}";
append(document_1.head, style);
}
function get_each_context$3(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
child_ctx[9] = i;
return child_ctx;
}
// (42:0) {#if debuggableClients.length > 1}
function create_if_block$3(ctx) {
let section;
let label;
let t;
let select;
let mounted;
let dispose;
let each_value = /*debuggableClients*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i));
}
return {
c() {
section = element("section");
label = element("label");
t = text("Client\n \n ");
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(select, "id", selectId);
attr(select, "class", "svelte-jvfq3i");
if (/*selected*/ ctx[2] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[4].call(select));
attr(label, "class", "svelte-jvfq3i");
attr(section, "class", "switcher svelte-jvfq3i");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, label);
append(label, t);
append(label, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selected*/ ctx[2]);
if (!mounted) {
dispose = [
listen(select, "change", /*handleSelection*/ ctx[3]),
listen(select, "change", /*select_change_handler*/ ctx[4])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debuggableClients, JSON*/ 2) {
each_value = /*debuggableClients*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$3(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$3(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selected*/ 4) {
select_option(select, /*selected*/ ctx[2]);
}
},
d(detaching) {
if (detaching) detach(section);
destroy_each(each_blocks, detaching);
mounted = false;
run_all(dispose);
}
};
}
// (48:8) {#each debuggableClients as clientOption, index}
function create_each_block$3(ctx) {
let option;
let t0;
let t1;
let t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "";
let t2;
let t3;
let t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "";
let t4;
let t5;
let t6_value = /*clientOption*/ ctx[7].game.name + "";
let t6;
let t7;
let option_value_value;
return {
c() {
option = element("option");
t0 = text(/*index*/ ctx[9]);
t1 = text(" —\n playerID: ");
t2 = text(t2_value);
t3 = text(",\n matchID: ");
t4 = text(t4_value);
t5 = text("\n (");
t6 = text(t6_value);
t7 = text(")\n ");
option.__value = option_value_value = /*index*/ ctx[9];
option.value = option.__value;
attr(option, "class", "svelte-jvfq3i");
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t0);
append(option, t1);
append(option, t2);
append(option, t3);
append(option, t4);
append(option, t5);
append(option, t6);
append(option, t7);
},
p(ctx, dirty) {
if (dirty & /*debuggableClients*/ 2 && t2_value !== (t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "")) set_data(t2, t2_value);
if (dirty & /*debuggableClients*/ 2 && t4_value !== (t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "")) set_data(t4, t4_value);
if (dirty & /*debuggableClients*/ 2 && t6_value !== (t6_value = /*clientOption*/ ctx[7].game.name + "")) set_data(t6, t6_value);
},
d(detaching) {
if (detaching) detach(option);
}
};
}
function create_fragment$d(ctx) {
let if_block_anchor;
let if_block = /*debuggableClients*/ ctx[1].length > 1 && create_if_block$3(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*debuggableClients*/ ctx[1].length > 1) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$3(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
const selectId = "bgio-debug-select-client";
function instance$d($$self, $$props, $$invalidate) {
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(6, $clientManager = $$value)), clientManager);
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const handleSelection = e => {
// Request to switch to the selected client.
const selectedClient = debuggableClients[e.target.value];
clientManager.switchToClient(selectedClient);
// Maintain focus on the client select menu after switching clients.
// Necessary because switching clients will usually trigger a mount/unmount.
const select = document.getElementById(selectId);
if (select) select.focus();
};
function select_change_handler() {
selected = select_value(this);
((($$invalidate(2, selected), $$invalidate(1, debuggableClients)), $$invalidate(5, client)), $$invalidate(6, $clientManager));
}
$$self.$set = $$props => {
if ("clientManager" in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
let client;
let debuggableClients;
let selected;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 64) {
$: $$invalidate(5, { client, debuggableClients } = $clientManager, client, ($$invalidate(1, debuggableClients), $$invalidate(6, $clientManager)));
}
if ($$self.$$.dirty & /*debuggableClients, client*/ 34) {
$: $$invalidate(2, selected = debuggableClients.indexOf(client));
}
};
return [
clientManager,
debuggableClients,
selected,
handleSelection,
select_change_handler
];
}
class ClientSwitcher extends SvelteComponent {
constructor(options) {
super();
if (!document_1.getElementById("svelte-jvfq3i-style")) add_css$7();
init(this, options, instance$d, create_fragment$d, safe_not_equal, { clientManager: 0 });
}
}
/* src/client/debug/main/Hotkey.svelte generated by Svelte v3.24.0 */
function add_css$8() {
var style = element("style");
style.id = "svelte-1vfj1mn-style";
style.textContent = ".key.svelte-1vfj1mn.svelte-1vfj1mn{display:flex;flex-direction:row;align-items:center}button.svelte-1vfj1mn.svelte-1vfj1mn{cursor:pointer;min-width:10px;padding-left:5px;padding-right:5px;height:20px;line-height:20px;text-align:center;border:1px solid #ccc;box-shadow:1px 1px 1px #888;background:#eee;color:#444}button.svelte-1vfj1mn.svelte-1vfj1mn:hover{background:#ddd}.key.active.svelte-1vfj1mn button.svelte-1vfj1mn{background:#ddd;border:1px solid #999;box-shadow:none}label.svelte-1vfj1mn.svelte-1vfj1mn{margin-left:10px}";
append(document.head, style);
}
// (78:2) {#if label}
function create_if_block$4(ctx) {
let label_1;
let t0;
let t1;
let span;
let t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "";
let t2;
return {
c() {
label_1 = element("label");
t0 = text(/*label*/ ctx[1]);
t1 = space();
span = element("span");
t2 = text(t2_value);
attr(span, "class", "screen-reader-only");
attr(label_1, "for", /*id*/ ctx[5]);
attr(label_1, "class", "svelte-1vfj1mn");
},
m(target, anchor) {
insert(target, label_1, anchor);
append(label_1, t0);
append(label_1, t1);
append(label_1, span);
append(span, t2);
},
p(ctx, dirty) {
if (dirty & /*label*/ 2) set_data(t0, /*label*/ ctx[1]);
if (dirty & /*value*/ 1 && t2_value !== (t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "")) set_data(t2, t2_value);
},
d(detaching) {
if (detaching) detach(label_1);
}
};
}
function create_fragment$e(ctx) {
let div;
let button;
let t0;
let t1;
let mounted;
let dispose;
let if_block = /*label*/ ctx[1] && create_if_block$4(ctx);
return {
c() {
div = element("div");
button = element("button");
t0 = text(/*value*/ ctx[0]);
t1 = space();
if (if_block) if_block.c();
attr(button, "id", /*id*/ ctx[5]);
button.disabled = /*disable*/ ctx[2];
attr(button, "class", "svelte-1vfj1mn");
attr(div, "class", "key svelte-1vfj1mn");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, button);
append(button, t0);
append(div, t1);
if (if_block) if_block.m(div, null);
if (!mounted) {
dispose = [
listen(window, "keydown", /*Keypress*/ ctx[7]),
listen(button, "click", /*Activate*/ ctx[6])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*value*/ 1) set_data(t0, /*value*/ ctx[0]);
if (dirty & /*disable*/ 4) {
button.disabled = /*disable*/ ctx[2];
}
if (/*label*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$4(ctx);
if_block.c();
if_block.m(div, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
if (if_block) if_block.d();
mounted = false;
run_all(dispose);
}
};
}
function instance$e($$self, $$props, $$invalidate) {
let $disableHotkeys;
let { value } = $$props;
let { onPress = null } = $$props;
let { label = null } = $$props;
let { disable = false } = $$props;
const { disableHotkeys } = getContext("hotkeys");
component_subscribe($$self, disableHotkeys, value => $$invalidate(9, $disableHotkeys = value));
let active = false;
let id = `key-${value}`;
function Deactivate() {
$$invalidate(3, active = false);
}
function Activate() {
$$invalidate(3, active = true);
setTimeout(Deactivate, 200);
if (onPress) {
setTimeout(onPress, 1);
}
}
function Keypress(e) {
if (!$disableHotkeys && !disable && !e.ctrlKey && !e.metaKey && e.key == value) {
e.preventDefault();
Activate();
}
}
$$self.$set = $$props => {
if ("value" in $$props) $$invalidate(0, value = $$props.value);
if ("onPress" in $$props) $$invalidate(8, onPress = $$props.onPress);
if ("label" in $$props) $$invalidate(1, label = $$props.label);
if ("disable" in $$props) $$invalidate(2, disable = $$props.disable);
};
return [value, label, disable, active, disableHotkeys, id, Activate, Keypress, onPress];
}
class Hotkey extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1vfj1mn-style")) add_css$8();
init(this, options, instance$e, create_fragment$e, safe_not_equal, {
value: 0,
onPress: 8,
label: 1,
disable: 2
});
}
}
/* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.24.0 */
function add_css$9() {
var style = element("style");
style.id = "svelte-1mppqmp-style";
style.textContent = ".move.svelte-1mppqmp{display:flex;flex-direction:row;cursor:pointer;margin-left:10px;color:#666}.move.svelte-1mppqmp:hover{color:#333}.move.active.svelte-1mppqmp{color:#111;font-weight:bold}.arg-field.svelte-1mppqmp{outline:none;font-family:monospace}";
append(document.head, style);
}
function create_fragment$f(ctx) {
let div;
let span0;
let t0;
let t1;
let span1;
let t3;
let span2;
let t4;
let span3;
let mounted;
let dispose;
return {
c() {
div = element("div");
span0 = element("span");
t0 = text(/*name*/ ctx[2]);
t1 = space();
span1 = element("span");
span1.textContent = "(";
t3 = space();
span2 = element("span");
t4 = space();
span3 = element("span");
span3.textContent = ")";
attr(span2, "class", "arg-field svelte-1mppqmp");
attr(span2, "contenteditable", "");
attr(div, "class", "move svelte-1mppqmp");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, span0);
append(span0, t0);
append(div, t1);
append(div, span1);
append(div, t3);
append(div, span2);
/*span2_binding*/ ctx[6](span2);
append(div, t4);
append(div, span3);
if (!mounted) {
dispose = [
listen(span2, "focus", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
}),
listen(span2, "blur", function () {
if (is_function(/*Deactivate*/ ctx[1])) /*Deactivate*/ ctx[1].apply(this, arguments);
}),
listen(span2, "keypress", stop_propagation(keypress_handler)),
listen(span2, "keydown", /*OnKeyDown*/ ctx[5]),
listen(div, "click", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
})
];
mounted = true;
}
},
p(new_ctx, [dirty]) {
ctx = new_ctx;
if (dirty & /*name*/ 4) set_data(t0, /*name*/ ctx[2]);
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
/*span2_binding*/ ctx[6](null);
mounted = false;
run_all(dispose);
}
};
}
const keypress_handler = () => {
};
function instance$f($$self, $$props, $$invalidate) {
let { Activate } = $$props;
let { Deactivate } = $$props;
let { name } = $$props;
let { active } = $$props;
let span;
const dispatch = createEventDispatcher();
function Submit() {
try {
const value = span.innerText;
let argArray = new Function(`return [${value}]`)();
dispatch("submit", argArray);
} catch(error) {
dispatch("error", error);
}
$$invalidate(4, span.innerText = "", span);
}
function OnKeyDown(e) {
if (e.key == "Enter") {
e.preventDefault();
Submit();
}
if (e.key == "Escape") {
e.preventDefault();
Deactivate();
}
}
afterUpdate(() => {
if (active) {
span.focus();
} else {
span.blur();
}
});
function span2_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
span = $$value;
$$invalidate(4, span);
});
}
$$self.$set = $$props => {
if ("Activate" in $$props) $$invalidate(0, Activate = $$props.Activate);
if ("Deactivate" in $$props) $$invalidate(1, Deactivate = $$props.Deactivate);
if ("name" in $$props) $$invalidate(2, name = $$props.name);
if ("active" in $$props) $$invalidate(3, active = $$props.active);
};
return [Activate, Deactivate, name, active, span, OnKeyDown, span2_binding];
}
class InteractiveFunction extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1mppqmp-style")) add_css$9();
init(this, options, instance$f, create_fragment$f, safe_not_equal, {
Activate: 0,
Deactivate: 1,
name: 2,
active: 3
});
}
}
/* src/client/debug/main/Move.svelte generated by Svelte v3.24.0 */
function add_css$a() {
var style = element("style");
style.id = "svelte-smqssc-style";
style.textContent = ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}";
append(document.head, style);
}
// (65:2) {#if error}
function create_if_block$5(ctx) {
let span;
let t;
return {
c() {
span = element("span");
t = text(/*error*/ ctx[2]);
attr(span, "class", "move-error svelte-smqssc");
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
},
p(ctx, dirty) {
if (dirty & /*error*/ 4) set_data(t, /*error*/ ctx[2]);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$g(ctx) {
let div1;
let div0;
let hotkey;
let t0;
let interactivefunction;
let t1;
let current;
hotkey = new Hotkey({
props: {
value: /*shortcut*/ ctx[0],
onPress: /*Activate*/ ctx[4]
}
});
interactivefunction = new InteractiveFunction({
props: {
Activate: /*Activate*/ ctx[4],
Deactivate: /*Deactivate*/ ctx[5],
name: /*name*/ ctx[1],
active: /*active*/ ctx[3]
}
});
interactivefunction.$on("submit", /*Submit*/ ctx[6]);
interactivefunction.$on("error", /*Error*/ ctx[7]);
let if_block = /*error*/ ctx[2] && create_if_block$5(ctx);
return {
c() {
div1 = element("div");
div0 = element("div");
create_component(hotkey.$$.fragment);
t0 = space();
create_component(interactivefunction.$$.fragment);
t1 = space();
if (if_block) if_block.c();
attr(div0, "class", "wrapper svelte-smqssc");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
mount_component(hotkey, div0, null);
append(div0, t0);
mount_component(interactivefunction, div0, null);
append(div1, t1);
if (if_block) if_block.m(div1, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey_changes = {};
if (dirty & /*shortcut*/ 1) hotkey_changes.value = /*shortcut*/ ctx[0];
hotkey.$set(hotkey_changes);
const interactivefunction_changes = {};
if (dirty & /*name*/ 2) interactivefunction_changes.name = /*name*/ ctx[1];
if (dirty & /*active*/ 8) interactivefunction_changes.active = /*active*/ ctx[3];
interactivefunction.$set(interactivefunction_changes);
if (/*error*/ ctx[2]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$5(ctx);
if_block.c();
if_block.m(div1, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey.$$.fragment, local);
transition_in(interactivefunction.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey.$$.fragment, local);
transition_out(interactivefunction.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_component(hotkey);
destroy_component(interactivefunction);
if (if_block) if_block.d();
}
};
}
function instance$g($$self, $$props, $$invalidate) {
let { shortcut } = $$props;
let { name } = $$props;
let { fn } = $$props;
const { disableHotkeys } = getContext("hotkeys");
let error$1 = "";
let active = false;
function Activate() {
disableHotkeys.set(true);
$$invalidate(3, active = true);
}
function Deactivate() {
disableHotkeys.set(false);
$$invalidate(2, error$1 = "");
$$invalidate(3, active = false);
}
function Submit(e) {
$$invalidate(2, error$1 = "");
Deactivate();
fn.apply(this, e.detail);
}
function Error(e) {
$$invalidate(2, error$1 = e.detail);
error(e.detail);
}
$$self.$set = $$props => {
if ("shortcut" in $$props) $$invalidate(0, shortcut = $$props.shortcut);
if ("name" in $$props) $$invalidate(1, name = $$props.name);
if ("fn" in $$props) $$invalidate(8, fn = $$props.fn);
};
return [shortcut, name, error$1, active, Activate, Deactivate, Submit, Error, fn];
}
class Move extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-smqssc-style")) add_css$a();
init(this, options, instance$g, create_fragment$g, safe_not_equal, { shortcut: 0, name: 1, fn: 8 });
}
}
/* src/client/debug/main/Controls.svelte generated by Svelte v3.24.0 */
function add_css$b() {
var style = element("style");
style.id = "svelte-c3lavh-style";
style.textContent = "ul.svelte-c3lavh{padding-left:0}li.svelte-c3lavh{list-style:none;margin:none;margin-bottom:5px}";
append(document.head, style);
}
function create_fragment$h(ctx) {
let ul;
let li0;
let hotkey0;
let t0;
let li1;
let hotkey1;
let t1;
let li2;
let hotkey2;
let t2;
let li3;
let hotkey3;
let current;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*client*/ ctx[0].reset,
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Save*/ ctx[1],
label: "save"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Restore*/ ctx[2],
label: "restore"
}
});
hotkey3 = new Hotkey({
props: { value: ".", disable: true, label: "hide" }
});
return {
c() {
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t0 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t1 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t2 = space();
li3 = element("li");
create_component(hotkey3.$$.fragment);
attr(li0, "class", "svelte-c3lavh");
attr(li1, "class", "svelte-c3lavh");
attr(li2, "class", "svelte-c3lavh");
attr(li3, "class", "svelte-c3lavh");
attr(ul, "id", "debug-controls");
attr(ul, "class", "controls svelte-c3lavh");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t0);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t1);
append(ul, li2);
mount_component(hotkey2, li2, null);
append(ul, t2);
append(ul, li3);
mount_component(hotkey3, li3, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey0_changes = {};
if (dirty & /*client*/ 1) hotkey0_changes.onPress = /*client*/ ctx[0].reset;
hotkey0.$set(hotkey0_changes);
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(hotkey3.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(hotkey3.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
destroy_component(hotkey3);
}
};
}
function instance$h($$self, $$props, $$invalidate) {
let { client } = $$props;
function Save() {
// get state to persist and overwrite deltalog, _undo, and _redo
const state = client.getState();
const json = stringify({
...state,
_undo: [],
_redo: [],
deltalog: []
});
window.localStorage.setItem("gamestate", json);
window.localStorage.setItem("initialState", stringify(client.initialState));
}
function Restore() {
const gamestateJSON = window.localStorage.getItem("gamestate");
const initialStateJSON = window.localStorage.getItem("initialState");
if (gamestateJSON !== null && initialStateJSON !== null) {
const gamestate = parse(gamestateJSON);
const initialState = parse(initialStateJSON);
client.store.dispatch(sync({ state: gamestate, initialState }));
}
}
$$self.$set = $$props => {
if ("client" in $$props) $$invalidate(0, client = $$props.client);
};
return [client, Save, Restore];
}
class Controls extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-c3lavh-style")) add_css$b();
init(this, options, instance$h, create_fragment$h, safe_not_equal, { client: 0 });
}
}
/* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.24.0 */
function add_css$c() {
var style = element("style");
style.id = "svelte-19aan9p-style";
style.textContent = ".player-box.svelte-19aan9p{display:flex;flex-direction:row}.player.svelte-19aan9p{cursor:pointer;text-align:center;width:30px;height:30px;line-height:30px;background:#eee;border:3px solid #fefefe;box-sizing:content-box;padding:0}.player.current.svelte-19aan9p{background:#555;color:#eee;font-weight:bold}.player.active.svelte-19aan9p{border:3px solid #ff7f50}";
append(document.head, style);
}
function get_each_context$4(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (59:2) {#each players as player}
function create_each_block$4(ctx) {
let button;
let t0_value = /*player*/ ctx[7] + "";
let t0;
let t1;
let button_aria_label_value;
let mounted;
let dispose;
function click_handler(...args) {
return /*click_handler*/ ctx[5](/*player*/ ctx[7], ...args);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "player svelte-19aan9p");
attr(button, "aria-label", button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]));
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*players*/ 4 && t0_value !== (t0_value = /*player*/ ctx[7] + "")) set_data(t0, t0_value);
if (dirty & /*players*/ 4 && button_aria_label_value !== (button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]))) {
attr(button, "aria-label", button_aria_label_value);
}
if (dirty & /*players, ctx*/ 5) {
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
}
if (dirty & /*players, playerID*/ 6) {
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment$i(ctx) {
let div;
let each_value = /*players*/ ctx[2];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$4(get_each_context$4(ctx, each_value, i));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "player-box svelte-19aan9p");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*playerLabel, players, ctx, playerID, OnClick*/ 31) {
each_value = /*players*/ ctx[2];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$4(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$4(child_ctx);
each_blocks[i].c();
each_blocks[i].m(div, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
}
};
}
function instance$i($$self, $$props, $$invalidate) {
let { ctx } = $$props;
let { playerID } = $$props;
const dispatch = createEventDispatcher();
function OnClick(player) {
if (player == playerID) {
dispatch("change", { playerID: null });
} else {
dispatch("change", { playerID: player });
}
}
function playerLabel(player) {
const properties = [];
if (player == ctx.currentPlayer) properties.push("current");
if (player == playerID) properties.push("active");
let label = `Player ${player}`;
if (properties.length) label += ` (${properties.join(", ")})`;
return label;
}
let players;
const click_handler = player => OnClick(player);
$$self.$set = $$props => {
if ("ctx" in $$props) $$invalidate(0, ctx = $$props.ctx);
if ("playerID" in $$props) $$invalidate(1, playerID = $$props.playerID);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*ctx*/ 1) {
$: $$invalidate(2, players = ctx
? [...Array(ctx.numPlayers).keys()].map(i => i.toString())
: []);
}
};
return [ctx, playerID, players, OnClick, playerLabel, click_handler];
}
class PlayerInfo extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-19aan9p-style")) add_css$c();
init(this, options, instance$i, create_fragment$i, safe_not_equal, { ctx: 0, playerID: 1 });
}
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
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 ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function AssignShortcuts(moveNames, blacklist) {
var shortcuts = {};
var taken = {};
var _iterator = _createForOfIteratorHelper(blacklist),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var c = _step.value;
taken[c] = true;
} // Try assigning the first char of each move as the shortcut.
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var t = taken;
var canUseFirstChar = true;
for (var name in moveNames) {
var shortcut = name[0];
if (t[shortcut]) {
canUseFirstChar = false;
break;
}
t[shortcut] = true;
shortcuts[name] = shortcut;
}
if (canUseFirstChar) {
return shortcuts;
} // If those aren't unique, use a-z.
t = taken;
var next = 97;
shortcuts = {};
for (var _name in moveNames) {
var _shortcut = String.fromCharCode(next);
while (t[_shortcut]) {
next++;
_shortcut = String.fromCharCode(next);
}
t[_shortcut] = true;
shortcuts[_name] = _shortcut;
}
return shortcuts;
}
/* src/client/debug/main/Main.svelte generated by Svelte v3.24.0 */
function add_css$d() {
var style = element("style");
style.id = "svelte-146sq5f-style";
style.textContent = ".tree.svelte-146sq5f{--json-tree-font-family:monospace;--json-tree-font-size:14px;--json-tree-null-color:#757575}.label.svelte-146sq5f{margin-bottom:0;text-transform:none}h3.svelte-146sq5f{text-transform:uppercase}ul.svelte-146sq5f{padding-left:0}li.svelte-146sq5f{list-style:none;margin:0;margin-bottom:5px}";
append(document.head, style);
}
function get_each_context$5(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i][0];
child_ctx[10] = list[i][1];
return child_ctx;
}
// (77:4) {#each Object.entries(moves) as [name, fn]}
function create_each_block$5(ctx) {
let li;
let move;
let t;
let current;
move = new Move({
props: {
shortcut: /*shortcuts*/ ctx[7][/*name*/ ctx[9]],
fn: /*fn*/ ctx[10],
name: /*name*/ ctx[9]
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
t = space();
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
append(li, t);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*moves*/ 8) move_changes.shortcut = /*shortcuts*/ ctx[7][/*name*/ ctx[9]];
if (dirty & /*moves*/ 8) move_changes.fn = /*fn*/ ctx[10];
if (dirty & /*moves*/ 8) move_changes.name = /*name*/ ctx[9];
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (89:2) {#if ctx.activePlayers && events.endStage}
function create_if_block_2$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endStage",
shortcut: 7,
fn: /*events*/ ctx[4].endStage
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endStage;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (94:2) {#if events.endTurn}
function create_if_block_1$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endTurn",
shortcut: 8,
fn: /*events*/ ctx[4].endTurn
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endTurn;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (99:2) {#if ctx.phase && events.endPhase}
function create_if_block$6(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endPhase",
shortcut: 9,
fn: /*events*/ ctx[4].endPhase
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endPhase;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
function create_fragment$j(ctx) {
let section0;
let h30;
let t1;
let controls;
let t2;
let section1;
let h31;
let t4;
let playerinfo;
let t5;
let section2;
let h32;
let t7;
let ul0;
let t8;
let section3;
let h33;
let t10;
let ul1;
let t11;
let t12;
let t13;
let section4;
let h34;
let t15;
let jsontree0;
let t16;
let section5;
let h35;
let t18;
let jsontree1;
let t19;
let clientswitcher;
let current;
controls = new Controls({ props: { client: /*client*/ ctx[0] } });
playerinfo = new PlayerInfo({
props: {
ctx: /*ctx*/ ctx[5],
playerID: /*playerID*/ ctx[2]
}
});
playerinfo.$on("change", /*change_handler*/ ctx[8]);
let each_value = Object.entries(/*moves*/ ctx[3]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$5(get_each_context$5(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block0 = /*ctx*/ ctx[5].activePlayers && /*events*/ ctx[4].endStage && create_if_block_2$2(ctx);
let if_block1 = /*events*/ ctx[4].endTurn && create_if_block_1$2(ctx);
let if_block2 = /*ctx*/ ctx[5].phase && /*events*/ ctx[4].endPhase && create_if_block$6(ctx);
jsontree0 = new Root({ props: { value: /*G*/ ctx[6] } });
jsontree1 = new Root({
props: { value: SanitizeCtx(/*ctx*/ ctx[5]) }
});
clientswitcher = new ClientSwitcher({
props: { clientManager: /*clientManager*/ ctx[1] }
});
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
create_component(controls.$$.fragment);
t2 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Players";
t4 = space();
create_component(playerinfo.$$.fragment);
t5 = space();
section2 = element("section");
h32 = element("h3");
h32.textContent = "Moves";
t7 = space();
ul0 = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t8 = space();
section3 = element("section");
h33 = element("h3");
h33.textContent = "Events";
t10 = space();
ul1 = element("ul");
if (if_block0) if_block0.c();
t11 = space();
if (if_block1) if_block1.c();
t12 = space();
if (if_block2) if_block2.c();
t13 = space();
section4 = element("section");
h34 = element("h3");
h34.textContent = "G";
t15 = space();
create_component(jsontree0.$$.fragment);
t16 = space();
section5 = element("section");
h35 = element("h3");
h35.textContent = "ctx";
t18 = space();
create_component(jsontree1.$$.fragment);
t19 = space();
create_component(clientswitcher.$$.fragment);
attr(h30, "class", "svelte-146sq5f");
attr(h31, "class", "svelte-146sq5f");
attr(h32, "class", "svelte-146sq5f");
attr(ul0, "class", "svelte-146sq5f");
attr(h33, "class", "svelte-146sq5f");
attr(ul1, "class", "svelte-146sq5f");
attr(h34, "class", "label svelte-146sq5f");
attr(section4, "class", "tree svelte-146sq5f");
attr(h35, "class", "label svelte-146sq5f");
attr(section5, "class", "tree svelte-146sq5f");
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
mount_component(controls, section0, null);
insert(target, t2, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t4);
mount_component(playerinfo, section1, null);
insert(target, t5, anchor);
insert(target, section2, anchor);
append(section2, h32);
append(section2, t7);
append(section2, ul0);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul0, null);
}
insert(target, t8, anchor);
insert(target, section3, anchor);
append(section3, h33);
append(section3, t10);
append(section3, ul1);
if (if_block0) if_block0.m(ul1, null);
append(ul1, t11);
if (if_block1) if_block1.m(ul1, null);
append(ul1, t12);
if (if_block2) if_block2.m(ul1, null);
insert(target, t13, anchor);
insert(target, section4, anchor);
append(section4, h34);
append(section4, t15);
mount_component(jsontree0, section4, null);
insert(target, t16, anchor);
insert(target, section5, anchor);
append(section5, h35);
append(section5, t18);
mount_component(jsontree1, section5, null);
insert(target, t19, anchor);
mount_component(clientswitcher, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const controls_changes = {};
if (dirty & /*client*/ 1) controls_changes.client = /*client*/ ctx[0];
controls.$set(controls_changes);
const playerinfo_changes = {};
if (dirty & /*ctx*/ 32) playerinfo_changes.ctx = /*ctx*/ ctx[5];
if (dirty & /*playerID*/ 4) playerinfo_changes.playerID = /*playerID*/ ctx[2];
playerinfo.$set(playerinfo_changes);
if (dirty & /*shortcuts, Object, moves*/ 136) {
each_value = Object.entries(/*moves*/ ctx[3]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$5(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$5(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul0, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*ctx*/ ctx[5].activePlayers && /*events*/ ctx[4].endStage) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*ctx, events*/ 48) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$2(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(ul1, t11);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*events*/ ctx[4].endTurn) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*events*/ 16) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block_1$2(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(ul1, t12);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (/*ctx*/ ctx[5].phase && /*events*/ ctx[4].endPhase) {
if (if_block2) {
if_block2.p(ctx, dirty);
if (dirty & /*ctx, events*/ 48) {
transition_in(if_block2, 1);
}
} else {
if_block2 = create_if_block$6(ctx);
if_block2.c();
transition_in(if_block2, 1);
if_block2.m(ul1, null);
}
} else if (if_block2) {
group_outros();
transition_out(if_block2, 1, 1, () => {
if_block2 = null;
});
check_outros();
}
const jsontree0_changes = {};
if (dirty & /*G*/ 64) jsontree0_changes.value = /*G*/ ctx[6];
jsontree0.$set(jsontree0_changes);
const jsontree1_changes = {};
if (dirty & /*ctx*/ 32) jsontree1_changes.value = SanitizeCtx(/*ctx*/ ctx[5]);
jsontree1.$set(jsontree1_changes);
const clientswitcher_changes = {};
if (dirty & /*clientManager*/ 2) clientswitcher_changes.clientManager = /*clientManager*/ ctx[1];
clientswitcher.$set(clientswitcher_changes);
},
i(local) {
if (current) return;
transition_in(controls.$$.fragment, local);
transition_in(playerinfo.$$.fragment, local);
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block0);
transition_in(if_block1);
transition_in(if_block2);
transition_in(jsontree0.$$.fragment, local);
transition_in(jsontree1.$$.fragment, local);
transition_in(clientswitcher.$$.fragment, local);
current = true;
},
o(local) {
transition_out(controls.$$.fragment, local);
transition_out(playerinfo.$$.fragment, local);
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block0);
transition_out(if_block1);
transition_out(if_block2);
transition_out(jsontree0.$$.fragment, local);
transition_out(jsontree1.$$.fragment, local);
transition_out(clientswitcher.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(controls);
if (detaching) detach(t2);
if (detaching) detach(section1);
destroy_component(playerinfo);
if (detaching) detach(t5);
if (detaching) detach(section2);
destroy_each(each_blocks, detaching);
if (detaching) detach(t8);
if (detaching) detach(section3);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
if (if_block2) if_block2.d();
if (detaching) detach(t13);
if (detaching) detach(section4);
destroy_component(jsontree0);
if (detaching) detach(t16);
if (detaching) detach(section5);
destroy_component(jsontree1);
if (detaching) detach(t19);
destroy_component(clientswitcher, detaching);
}
};
}
function SanitizeCtx(ctx) {
let r = {};
for (const key in ctx) {
if (!key.startsWith("_")) {
r[key] = ctx[key];
}
}
return r;
}
function instance$j($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
const shortcuts = AssignShortcuts(client.moves, "mlia");
let { playerID, moves, events } = client;
let ctx = {};
let G = {};
client.subscribe(state => {
if (state) $$invalidate(6, { G, ctx } = state, G, $$invalidate(5, ctx));
$$invalidate(2, { playerID, moves, events } = client, playerID, $$invalidate(3, moves), $$invalidate(4, events));
});
const change_handler = e => clientManager.switchPlayerID(e.detail.playerID);
$$self.$set = $$props => {
if ("client" in $$props) $$invalidate(0, client = $$props.client);
if ("clientManager" in $$props) $$invalidate(1, clientManager = $$props.clientManager);
};
return [
client,
clientManager,
playerID,
moves,
events,
ctx,
G,
shortcuts,
change_handler
];
}
class Main extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-146sq5f-style")) add_css$d();
init(this, options, instance$j, create_fragment$j, safe_not_equal, { client: 0, clientManager: 1 });
}
}
/* src/client/debug/info/Item.svelte generated by Svelte v3.24.0 */
function add_css$e() {
var style = element("style");
style.id = "svelte-13qih23-style";
style.textContent = ".item.svelte-13qih23.svelte-13qih23{padding:10px}.item.svelte-13qih23.svelte-13qih23:not(:first-child){border-top:1px dashed #aaa}.item.svelte-13qih23 div.svelte-13qih23{float:right;text-align:right}";
append(document.head, style);
}
function create_fragment$k(ctx) {
let div1;
let strong;
let t0;
let t1;
let div0;
let t2_value = JSON.stringify(/*value*/ ctx[1]) + "";
let t2;
return {
c() {
div1 = element("div");
strong = element("strong");
t0 = text(/*name*/ ctx[0]);
t1 = space();
div0 = element("div");
t2 = text(t2_value);
attr(div0, "class", "svelte-13qih23");
attr(div1, "class", "item svelte-13qih23");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, strong);
append(strong, t0);
append(div1, t1);
append(div1, div0);
append(div0, t2);
},
p(ctx, [dirty]) {
if (dirty & /*name*/ 1) set_data(t0, /*name*/ ctx[0]);
if (dirty & /*value*/ 2 && t2_value !== (t2_value = JSON.stringify(/*value*/ ctx[1]) + "")) set_data(t2, t2_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
}
};
}
function instance$k($$self, $$props, $$invalidate) {
let { name } = $$props;
let { value } = $$props;
$$self.$set = $$props => {
if ("name" in $$props) $$invalidate(0, name = $$props.name);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
};
return [name, value];
}
class Item extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-13qih23-style")) add_css$e();
init(this, options, instance$k, create_fragment$k, safe_not_equal, { name: 0, value: 1 });
}
}
/* src/client/debug/info/Info.svelte generated by Svelte v3.24.0 */
function add_css$f() {
var style = element("style");
style.id = "svelte-1yzq5o8-style";
style.textContent = ".gameinfo.svelte-1yzq5o8{padding:10px}";
append(document.head, style);
}
// (18:2) {#if client.multiplayer}
function create_if_block$7(ctx) {
let item;
let current;
item = new Item({
props: {
name: "isConnected",
value: /*$client*/ ctx[1].isConnected
}
});
return {
c() {
create_component(item.$$.fragment);
},
m(target, anchor) {
mount_component(item, target, anchor);
current = true;
},
p(ctx, dirty) {
const item_changes = {};
if (dirty & /*$client*/ 2) item_changes.value = /*$client*/ ctx[1].isConnected;
item.$set(item_changes);
},
i(local) {
if (current) return;
transition_in(item.$$.fragment, local);
current = true;
},
o(local) {
transition_out(item.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(item, detaching);
}
};
}
function create_fragment$l(ctx) {
let section;
let item0;
let t0;
let item1;
let t1;
let item2;
let t2;
let current;
item0 = new Item({
props: {
name: "matchID",
value: /*client*/ ctx[0].matchID
}
});
item1 = new Item({
props: {
name: "playerID",
value: /*client*/ ctx[0].playerID
}
});
item2 = new Item({
props: {
name: "isActive",
value: /*$client*/ ctx[1].isActive
}
});
let if_block = /*client*/ ctx[0].multiplayer && create_if_block$7(ctx);
return {
c() {
section = element("section");
create_component(item0.$$.fragment);
t0 = space();
create_component(item1.$$.fragment);
t1 = space();
create_component(item2.$$.fragment);
t2 = space();
if (if_block) if_block.c();
attr(section, "class", "gameinfo svelte-1yzq5o8");
},
m(target, anchor) {
insert(target, section, anchor);
mount_component(item0, section, null);
append(section, t0);
mount_component(item1, section, null);
append(section, t1);
mount_component(item2, section, null);
append(section, t2);
if (if_block) if_block.m(section, null);
current = true;
},
p(ctx, [dirty]) {
const item0_changes = {};
if (dirty & /*client*/ 1) item0_changes.value = /*client*/ ctx[0].matchID;
item0.$set(item0_changes);
const item1_changes = {};
if (dirty & /*client*/ 1) item1_changes.value = /*client*/ ctx[0].playerID;
item1.$set(item1_changes);
const item2_changes = {};
if (dirty & /*$client*/ 2) item2_changes.value = /*$client*/ ctx[1].isActive;
item2.$set(item2_changes);
if (/*client*/ ctx[0].multiplayer) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*client*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$7(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(section, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(item0.$$.fragment, local);
transition_in(item1.$$.fragment, local);
transition_in(item2.$$.fragment, local);
transition_in(if_block);
current = true;
},
o(local) {
transition_out(item0.$$.fragment, local);
transition_out(item1.$$.fragment, local);
transition_out(item2.$$.fragment, local);
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(item0);
destroy_component(item1);
destroy_component(item2);
if (if_block) if_block.d();
}
};
}
function instance$l($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(1, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
let { clientManager } = $$props;
$$self.$set = $$props => {
if ("client" in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
if ("clientManager" in $$props) $$invalidate(2, clientManager = $$props.clientManager);
};
return [client, $client, clientManager];
}
class Info extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1yzq5o8-style")) add_css$f();
init(this, options, instance$l, create_fragment$l, safe_not_equal, { client: 0, clientManager: 2 });
}
}
/* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.24.0 */
function add_css$g() {
var style = element("style");
style.id = "svelte-6eza86-style";
style.textContent = ".turn-marker.svelte-6eza86{display:flex;justify-content:center;align-items:center;grid-column:1;background:#555;color:#eee;text-align:center;font-weight:bold;border:1px solid #888}";
append(document.head, style);
}
function create_fragment$m(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*turn*/ ctx[0]);
attr(div, "class", "turn-marker svelte-6eza86");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*turn*/ 1) set_data(t, /*turn*/ ctx[0]);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$m($$self, $$props, $$invalidate) {
let { turn } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$set = $$props => {
if ("turn" in $$props) $$invalidate(0, turn = $$props.turn);
if ("numEvents" in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [turn, style, numEvents];
}
class TurnMarker extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-6eza86-style")) add_css$g();
init(this, options, instance$m, create_fragment$m, safe_not_equal, { turn: 0, numEvents: 2 });
}
}
/* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.24.0 */
function add_css$h() {
var style = element("style");
style.id = "svelte-1t4xap-style";
style.textContent = ".phase-marker.svelte-1t4xap{grid-column:3;background:#555;border:1px solid #888;color:#eee;text-align:center;font-weight:bold;padding-top:10px;padding-bottom:10px;text-orientation:sideways;writing-mode:vertical-rl;line-height:30px;width:100%}";
append(document.head, style);
}
function create_fragment$n(ctx) {
let div;
let t_value = (/*phase*/ ctx[0] || "") + "";
let t;
return {
c() {
div = element("div");
t = text(t_value);
attr(div, "class", "phase-marker svelte-1t4xap");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*phase*/ 1 && t_value !== (t_value = (/*phase*/ ctx[0] || "") + "")) set_data(t, t_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$n($$self, $$props, $$invalidate) {
let { phase } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$set = $$props => {
if ("phase" in $$props) $$invalidate(0, phase = $$props.phase);
if ("numEvents" in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [phase, style, numEvents];
}
class PhaseMarker extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1t4xap-style")) add_css$h();
init(this, options, instance$n, create_fragment$n, safe_not_equal, { phase: 0, numEvents: 2 });
}
}
/* src/client/debug/log/LogMetadata.svelte generated by Svelte v3.24.0 */
function create_fragment$o(ctx) {
let div;
return {
c() {
div = element("div");
div.textContent = `${/*renderedMetadata*/ ctx[0]}`;
},
m(target, anchor) {
insert(target, div, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$o($$self, $$props, $$invalidate) {
let { metadata } = $$props;
const renderedMetadata = metadata !== undefined
? JSON.stringify(metadata, null, 4)
: "";
$$self.$set = $$props => {
if ("metadata" in $$props) $$invalidate(1, metadata = $$props.metadata);
};
return [renderedMetadata, metadata];
}
class LogMetadata extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$o, create_fragment$o, safe_not_equal, { metadata: 1 });
}
}
/* src/client/debug/log/LogEvent.svelte generated by Svelte v3.24.0 */
function add_css$i() {
var style = element("style");
style.id = "svelte-11hs70q-style";
style.textContent = ".log-event.svelte-11hs70q{grid-column:2;cursor:pointer;overflow:hidden;display:flex;flex-direction:column;justify-content:center;background:#fff;border:1px dotted #ccc;border-left:5px solid #ccc;padding:5px;text-align:center;color:#666;font-size:14px;min-height:25px;line-height:25px}.log-event.svelte-11hs70q:hover,.log-event.svelte-11hs70q:focus{border-style:solid;background:#eee}.log-event.pinned.svelte-11hs70q{border-style:solid;background:#eee;opacity:1}.player0.svelte-11hs70q{border-left-color:#ff851b}.player1.svelte-11hs70q{border-left-color:#7fdbff}.player2.svelte-11hs70q{border-left-color:#0074d9}.player3.svelte-11hs70q{border-left-color:#39cccc}.player4.svelte-11hs70q{border-left-color:#3d9970}.player5.svelte-11hs70q{border-left-color:#2ecc40}.player6.svelte-11hs70q{border-left-color:#01ff70}.player7.svelte-11hs70q{border-left-color:#ffdc00}.player8.svelte-11hs70q{border-left-color:#001f3f}.player9.svelte-11hs70q{border-left-color:#ff4136}.player10.svelte-11hs70q{border-left-color:#85144b}.player11.svelte-11hs70q{border-left-color:#f012be}.player12.svelte-11hs70q{border-left-color:#b10dc9}.player13.svelte-11hs70q{border-left-color:#111111}.player14.svelte-11hs70q{border-left-color:#aaaaaa}.player15.svelte-11hs70q{border-left-color:#dddddd}";
append(document.head, style);
}
// (139:2) {:else}
function create_else_block$1(ctx) {
let logmetadata;
let current;
logmetadata = new LogMetadata({ props: { metadata: /*metadata*/ ctx[2] } });
return {
c() {
create_component(logmetadata.$$.fragment);
},
m(target, anchor) {
mount_component(logmetadata, target, anchor);
current = true;
},
p(ctx, dirty) {
const logmetadata_changes = {};
if (dirty & /*metadata*/ 4) logmetadata_changes.metadata = /*metadata*/ ctx[2];
logmetadata.$set(logmetadata_changes);
},
i(local) {
if (current) return;
transition_in(logmetadata.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logmetadata.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logmetadata, detaching);
}
};
}
// (137:2) {#if metadataComponent}
function create_if_block$8(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*metadataComponent*/ ctx[3];
function switch_props(ctx) {
return { props: { metadata: /*metadata*/ ctx[2] } };
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*metadata*/ 4) switch_instance_changes.metadata = /*metadata*/ ctx[2];
if (switch_value !== (switch_value = /*metadataComponent*/ ctx[3])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function create_fragment$p(ctx) {
let button;
let div;
let t0;
let t1;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block;
let button_class_value;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$8, create_else_block$1];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*metadataComponent*/ ctx[3]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
button = element("button");
div = element("div");
t0 = text(/*actionType*/ ctx[4]);
t1 = text("(");
t2 = text(/*renderedArgs*/ ctx[6]);
t3 = text(")");
t4 = space();
if_block.c();
attr(button, "class", button_class_value = "log-event player" + /*playerID*/ ctx[7] + " svelte-11hs70q");
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, div);
append(div, t0);
append(div, t1);
append(div, t2);
append(div, t3);
append(button, t4);
if_blocks[current_block_type_index].m(button, null);
current = true;
if (!mounted) {
dispose = [
listen(button, "click", /*click_handler*/ ctx[9]),
listen(button, "mouseenter", /*mouseenter_handler*/ ctx[10]),
listen(button, "focus", /*focus_handler*/ ctx[11]),
listen(button, "mouseleave", /*mouseleave_handler*/ ctx[12]),
listen(button, "blur", /*blur_handler*/ ctx[13])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (!current || dirty & /*actionType*/ 16) set_data(t0, /*actionType*/ ctx[4]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
}
transition_in(if_block, 1);
if_block.m(button, null);
}
if (dirty & /*pinned*/ 2) {
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(button);
if_blocks[current_block_type_index].d();
mounted = false;
run_all(dispose);
}
};
}
function instance$p($$self, $$props, $$invalidate) {
let { logIndex } = $$props;
let { action } = $$props;
let { pinned } = $$props;
let { metadata } = $$props;
let { metadataComponent } = $$props;
const dispatch = createEventDispatcher();
const args = action.payload.args;
const renderedArgs = typeof args === "string" ? args : (args || []).join(",");
const playerID = action.payload.playerID;
let actionType;
switch (action.type) {
case "UNDO":
actionType = "undo";
break;
case "REDO":
actionType = "redo";
case "GAME_EVENT":
case "MAKE_MOVE":
default:
actionType = action.payload.type;
break;
}
const click_handler = () => dispatch("click", { logIndex });
const mouseenter_handler = () => dispatch("mouseenter", { logIndex });
const focus_handler = () => dispatch("mouseenter", { logIndex });
const mouseleave_handler = () => dispatch("mouseleave");
const blur_handler = () => dispatch("mouseleave");
$$self.$set = $$props => {
if ("logIndex" in $$props) $$invalidate(0, logIndex = $$props.logIndex);
if ("action" in $$props) $$invalidate(8, action = $$props.action);
if ("pinned" in $$props) $$invalidate(1, pinned = $$props.pinned);
if ("metadata" in $$props) $$invalidate(2, metadata = $$props.metadata);
if ("metadataComponent" in $$props) $$invalidate(3, metadataComponent = $$props.metadataComponent);
};
return [
logIndex,
pinned,
metadata,
metadataComponent,
actionType,
dispatch,
renderedArgs,
playerID,
action,
click_handler,
mouseenter_handler,
focus_handler,
mouseleave_handler,
blur_handler
];
}
class LogEvent extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-11hs70q-style")) add_css$i();
init(this, options, instance$p, create_fragment$p, safe_not_equal, {
logIndex: 0,
action: 8,
pinned: 1,
metadata: 2,
metadataComponent: 3
});
}
}
/* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.24.0 */
function add_css$j() {
var style = element("style");
style.id = "svelte-c8tyih-style";
style.textContent = "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}";
append(document.head, style);
}
// (18:2) {#if title}
function create_if_block$9(ctx) {
let title_1;
let t;
return {
c() {
title_1 = svg_element("title");
t = text(/*title*/ ctx[0]);
},
m(target, anchor) {
insert(target, title_1, anchor);
append(title_1, t);
},
p(ctx, dirty) {
if (dirty & /*title*/ 1) set_data(t, /*title*/ ctx[0]);
},
d(detaching) {
if (detaching) detach(title_1);
}
};
}
function create_fragment$q(ctx) {
let svg;
let if_block_anchor;
let current;
let if_block = /*title*/ ctx[0] && create_if_block$9(ctx);
const default_slot_template = /*$$slots*/ ctx[3].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[2], null);
return {
c() {
svg = svg_element("svg");
if (if_block) if_block.c();
if_block_anchor = empty();
if (default_slot) default_slot.c();
attr(svg, "xmlns", "http://www.w3.org/2000/svg");
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
attr(svg, "class", "svelte-c8tyih");
},
m(target, anchor) {
insert(target, svg, anchor);
if (if_block) if_block.m(svg, null);
append(svg, if_block_anchor);
if (default_slot) {
default_slot.m(svg, null);
}
current = true;
},
p(ctx, [dirty]) {
if (/*title*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$9(ctx);
if_block.c();
if_block.m(svg, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (default_slot) {
if (default_slot.p && dirty & /*$$scope*/ 4) {
update_slot(default_slot, default_slot_template, ctx, /*$$scope*/ ctx[2], dirty, null, null);
}
}
if (!current || dirty & /*viewBox*/ 2) {
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(svg);
if (if_block) if_block.d();
if (default_slot) default_slot.d(detaching);
}
};
}
function instance$q($$self, $$props, $$invalidate) {
let { title = null } = $$props;
let { viewBox } = $$props;
let { $$slots = {}, $$scope } = $$props;
$$self.$set = $$props => {
if ("title" in $$props) $$invalidate(0, title = $$props.title);
if ("viewBox" in $$props) $$invalidate(1, viewBox = $$props.viewBox);
if ("$$scope" in $$props) $$invalidate(2, $$scope = $$props.$$scope);
};
return [title, viewBox, $$scope, $$slots];
}
class IconBase extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-c8tyih-style")) add_css$j();
init(this, options, instance$q, create_fragment$q, safe_not_equal, { title: 0, viewBox: 1 });
}
}
/* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.24.0 */
function create_default_slot(ctx) {
let path;
return {
c() {
path = svg_element("path");
attr(path, "d", "M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM212 140v116h-70.9c-10.7 0-16.1 13-8.5 20.5l114.9 114.3c4.7 4.7 12.2 4.7 16.9 0l114.9-114.3c7.6-7.6 2.2-20.5-8.5-20.5H300V140c0-6.6-5.4-12-12-12h-64c-6.6 0-12 5.4-12 12z");
},
m(target, anchor) {
insert(target, path, anchor);
},
d(detaching) {
if (detaching) detach(path);
}
};
}
function create_fragment$r(ctx) {
let iconbase;
let current;
const iconbase_spread_levels = [{ viewBox: "0 0 512 512" }, /*$$props*/ ctx[0]];
let iconbase_props = {
$$slots: { default: [create_default_slot] },
$$scope: { ctx }
};
for (let i = 0; i < iconbase_spread_levels.length; i += 1) {
iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]);
}
iconbase = new IconBase({ props: iconbase_props });
return {
c() {
create_component(iconbase.$$.fragment);
},
m(target, anchor) {
mount_component(iconbase, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const iconbase_changes = (dirty & /*$$props*/ 1)
? get_spread_update(iconbase_spread_levels, [iconbase_spread_levels[0], get_spread_object(/*$$props*/ ctx[0])])
: {};
if (dirty & /*$$scope*/ 2) {
iconbase_changes.$$scope = { dirty, ctx };
}
iconbase.$set(iconbase_changes);
},
i(local) {
if (current) return;
transition_in(iconbase.$$.fragment, local);
current = true;
},
o(local) {
transition_out(iconbase.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(iconbase, detaching);
}
};
}
function instance$r($$self, $$props, $$invalidate) {
$$self.$set = $$new_props => {
$$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
};
$$props = exclude_internal_props($$props);
return [$$props];
}
class FaArrowAltCircleDown extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$r, create_fragment$r, safe_not_equal, {});
}
}
/* src/client/debug/mcts/Action.svelte generated by Svelte v3.24.0 */
function add_css$k() {
var style = element("style");
style.id = "svelte-1a7time-style";
style.textContent = "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}";
append(document.head, style);
}
function create_fragment$s(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*text*/ ctx[0]);
attr(div, "alt", /*text*/ ctx[0]);
attr(div, "class", "svelte-1a7time");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*text*/ 1) set_data(t, /*text*/ ctx[0]);
if (dirty & /*text*/ 1) {
attr(div, "alt", /*text*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$s($$self, $$props, $$invalidate) {
let { action } = $$props;
let text;
$$self.$set = $$props => {
if ("action" in $$props) $$invalidate(1, action = $$props.action);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*action*/ 2) {
$: {
const { type, args } = action.payload;
const argsFormatted = (args || []).join(",");
$$invalidate(0, text = `${type}(${argsFormatted})`);
}
}
};
return [text, action];
}
class Action extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1a7time-style")) add_css$k();
init(this, options, instance$s, create_fragment$s, safe_not_equal, { action: 1 });
}
}
/* src/client/debug/mcts/Table.svelte generated by Svelte v3.24.0 */
function add_css$l() {
var style = element("style");
style.id = "svelte-ztcwsu-style";
style.textContent = "table.svelte-ztcwsu.svelte-ztcwsu{font-size:12px;border-collapse:collapse;border:1px solid #ddd;padding:0}tr.svelte-ztcwsu.svelte-ztcwsu{cursor:pointer}tr.svelte-ztcwsu:hover td.svelte-ztcwsu{background:#eee}tr.selected.svelte-ztcwsu td.svelte-ztcwsu{background:#eee}td.svelte-ztcwsu.svelte-ztcwsu{padding:10px;height:10px;line-height:10px;font-size:12px;border:none}th.svelte-ztcwsu.svelte-ztcwsu{background:#888;color:#fff;padding:10px;text-align:center}";
append(document.head, style);
}
function get_each_context$6(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[10] = list[i];
child_ctx[12] = i;
return child_ctx;
}
// (86:2) {#each children as child, i}
function create_each_block$6(ctx) {
let tr;
let td0;
let t0_value = /*child*/ ctx[10].value + "";
let t0;
let t1;
let td1;
let t2_value = /*child*/ ctx[10].visits + "";
let t2;
let t3;
let td2;
let action;
let t4;
let current;
let mounted;
let dispose;
action = new Action({
props: { action: /*child*/ ctx[10].parentAction }
});
function click_handler(...args) {
return /*click_handler*/ ctx[5](/*child*/ ctx[10], /*i*/ ctx[12], ...args);
}
function mouseout_handler(...args) {
return /*mouseout_handler*/ ctx[6](/*i*/ ctx[12], ...args);
}
function mouseover_handler(...args) {
return /*mouseover_handler*/ ctx[7](/*child*/ ctx[10], /*i*/ ctx[12], ...args);
}
return {
c() {
tr = element("tr");
td0 = element("td");
t0 = text(t0_value);
t1 = space();
td1 = element("td");
t2 = text(t2_value);
t3 = space();
td2 = element("td");
create_component(action.$$.fragment);
t4 = space();
attr(td0, "class", "svelte-ztcwsu");
attr(td1, "class", "svelte-ztcwsu");
attr(td2, "class", "svelte-ztcwsu");
attr(tr, "class", "svelte-ztcwsu");
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
},
m(target, anchor) {
insert(target, tr, anchor);
append(tr, td0);
append(td0, t0);
append(tr, t1);
append(tr, td1);
append(td1, t2);
append(tr, t3);
append(tr, td2);
mount_component(action, td2, null);
append(tr, t4);
current = true;
if (!mounted) {
dispose = [
listen(tr, "click", click_handler),
listen(tr, "mouseout", mouseout_handler),
listen(tr, "mouseover", mouseover_handler)
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if ((!current || dirty & /*children*/ 2) && t0_value !== (t0_value = /*child*/ ctx[10].value + "")) set_data(t0, t0_value);
if ((!current || dirty & /*children*/ 2) && t2_value !== (t2_value = /*child*/ ctx[10].visits + "")) set_data(t2, t2_value);
const action_changes = {};
if (dirty & /*children*/ 2) action_changes.action = /*child*/ ctx[10].parentAction;
action.$set(action_changes);
if (dirty & /*children*/ 2) {
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
}
if (dirty & /*selectedIndex*/ 1) {
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(action.$$.fragment, local);
current = true;
},
o(local) {
transition_out(action.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(tr);
destroy_component(action);
mounted = false;
run_all(dispose);
}
};
}
function create_fragment$t(ctx) {
let table;
let thead;
let t5;
let tbody;
let current;
let each_value = /*children*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$6(get_each_context$6(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
table = element("table");
thead = element("thead");
thead.innerHTML = `<th class="svelte-ztcwsu">Value</th>
<th class="svelte-ztcwsu">Visits</th>
<th class="svelte-ztcwsu">Action</th>`;
t5 = space();
tbody = element("tbody");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(table, "class", "svelte-ztcwsu");
},
m(target, anchor) {
insert(target, table, anchor);
append(table, thead);
append(table, t5);
append(table, tbody);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(tbody, null);
}
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*children, selectedIndex, Select, Preview*/ 15) {
each_value = /*children*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$6(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$6(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(tbody, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(table);
destroy_each(each_blocks, detaching);
}
};
}
function instance$t($$self, $$props, $$invalidate) {
let { root } = $$props;
let { selectedIndex = null } = $$props;
const dispatch = createEventDispatcher();
let parents = [];
let children = [];
function Select(node, i) {
dispatch("select", { node, selectedIndex: i });
}
function Preview(node, i) {
if (selectedIndex === null) {
dispatch("preview", { node });
}
}
const click_handler = (child, i) => Select(child, i);
const mouseout_handler = i => Preview(null);
const mouseover_handler = (child, i) => Preview(child);
$$self.$set = $$props => {
if ("root" in $$props) $$invalidate(4, root = $$props.root);
if ("selectedIndex" in $$props) $$invalidate(0, selectedIndex = $$props.selectedIndex);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*root, parents*/ 272) {
$: {
let t = root;
$$invalidate(8, parents = []);
while (t.parent) {
const parent = t.parent;
const { type, args } = t.parentAction.payload;
const argsFormatted = (args || []).join(",");
const arrowText = `${type}(${argsFormatted})`;
parents.push({ parent, arrowText });
t = parent;
}
parents.reverse();
$$invalidate(1, children = [...root.children].sort((a, b) => a.visits < b.visits ? 1 : -1).slice(0, 50));
}
}
};
return [
selectedIndex,
children,
Select,
Preview,
root,
click_handler,
mouseout_handler,
mouseover_handler
];
}
class Table extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-ztcwsu-style")) add_css$l();
init(this, options, instance$t, create_fragment$t, safe_not_equal, { root: 4, selectedIndex: 0 });
}
}
/* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.24.0 */
function add_css$m() {
var style = element("style");
style.id = "svelte-1f0amz4-style";
style.textContent = ".visualizer.svelte-1f0amz4{display:flex;flex-direction:column;align-items:center;padding:50px}.preview.svelte-1f0amz4{opacity:0.5}.icon.svelte-1f0amz4{color:#777;width:32px;height:32px;margin-bottom:20px}";
append(document.head, style);
}
function get_each_context$7(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i].node;
child_ctx[10] = list[i].selectedIndex;
child_ctx[12] = i;
return child_ctx;
}
// (50:4) {#if i !== 0}
function create_if_block_2$3(ctx) {
let div;
let arrow;
let current;
arrow = new FaArrowAltCircleDown({});
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
current = true;
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
}
};
}
// (61:6) {:else}
function create_else_block$2(ctx) {
let table;
let current;
function select_handler_1(...args) {
return /*select_handler_1*/ ctx[7](/*i*/ ctx[12], ...args);
}
table = new Table({
props: {
root: /*node*/ ctx[9],
selectedIndex: /*selectedIndex*/ ctx[10]
}
});
table.$on("select", select_handler_1);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
if (dirty & /*nodes*/ 1) table_changes.selectedIndex = /*selectedIndex*/ ctx[10];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (57:6) {#if i === nodes.length - 1}
function create_if_block_1$3(ctx) {
let table;
let current;
function select_handler(...args) {
return /*select_handler*/ ctx[5](/*i*/ ctx[12], ...args);
}
function preview_handler(...args) {
return /*preview_handler*/ ctx[6](/*i*/ ctx[12], ...args);
}
table = new Table({ props: { root: /*node*/ ctx[9] } });
table.$on("select", select_handler);
table.$on("preview", preview_handler);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (49:2) {#each nodes as { node, selectedIndex }
function create_each_block$7(ctx) {
let t;
let section;
let current_block_type_index;
let if_block1;
let current;
let if_block0 = /*i*/ ctx[12] !== 0 && create_if_block_2$3();
const if_block_creators = [create_if_block_1$3, create_else_block$2];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*i*/ ctx[12] === /*nodes*/ ctx[0].length - 1) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
if (if_block0) if_block0.c();
t = space();
section = element("section");
if_block1.c();
},
m(target, anchor) {
if (if_block0) if_block0.m(target, anchor);
insert(target, t, anchor);
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
},
p(ctx, dirty) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
}
transition_in(if_block1, 1);
if_block1.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t);
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
}
};
}
// (69:2) {#if preview}
function create_if_block$a(ctx) {
let div;
let arrow;
let t;
let section;
let table;
let current;
arrow = new FaArrowAltCircleDown({});
table = new Table({ props: { root: /*preview*/ ctx[1] } });
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
t = space();
section = element("section");
create_component(table.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
attr(section, "class", "preview svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
insert(target, t, anchor);
insert(target, section, anchor);
mount_component(table, section, null);
current = true;
},
p(ctx, dirty) {
const table_changes = {};
if (dirty & /*preview*/ 2) table_changes.root = /*preview*/ ctx[1];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
if (detaching) detach(t);
if (detaching) detach(section);
destroy_component(table);
}
};
}
function create_fragment$u(ctx) {
let div;
let t;
let current;
let each_value = /*nodes*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$7(get_each_context$7(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*preview*/ ctx[1] && create_if_block$a(ctx);
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(div, "class", "visualizer svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
append(div, t);
if (if_block) if_block.m(div, null);
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*nodes, SelectNode, PreviewNode*/ 13) {
each_value = /*nodes*/ ctx[0];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$7(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$7(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*preview*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*preview*/ 2) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$a(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(div, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block);
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
}
};
}
function instance$u($$self, $$props, $$invalidate) {
let { metadata } = $$props;
let nodes = [];
let preview = null;
function SelectNode({ node, selectedIndex }, i) {
$$invalidate(1, preview = null);
$$invalidate(0, nodes[i].selectedIndex = selectedIndex, nodes);
$$invalidate(0, nodes = [...nodes.slice(0, i + 1), { node }]);
}
function PreviewNode({ node }, i) {
$$invalidate(1, preview = node);
}
const select_handler = (i, e) => SelectNode(e.detail, i);
const preview_handler = (i, e) => PreviewNode(e.detail);
const select_handler_1 = (i, e) => SelectNode(e.detail, i);
$$self.$set = $$props => {
if ("metadata" in $$props) $$invalidate(4, metadata = $$props.metadata);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*metadata*/ 16) {
$: {
$$invalidate(0, nodes = [{ node: metadata }]);
}
}
};
return [
nodes,
preview,
SelectNode,
PreviewNode,
metadata,
select_handler,
preview_handler,
select_handler_1
];
}
class MCTS extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1f0amz4-style")) add_css$m();
init(this, options, instance$u, create_fragment$u, safe_not_equal, { metadata: 4 });
}
}
/* src/client/debug/log/Log.svelte generated by Svelte v3.24.0 */
function add_css$n() {
var style = element("style");
style.id = "svelte-1pq5e4b-style";
style.textContent = ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}";
append(document.head, style);
}
function get_each_context$8(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[16] = list[i].phase;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[19] = list[i].action;
child_ctx[20] = list[i].metadata;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[22] = list[i].turn;
child_ctx[18] = i;
return child_ctx;
}
// (136:4) {#if i in turnBoundaries}
function create_if_block_1$4(ctx) {
let turnmarker;
let current;
turnmarker = new TurnMarker({
props: {
turn: /*turn*/ ctx[22],
numEvents: /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(turnmarker.$$.fragment);
},
m(target, anchor) {
mount_component(turnmarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const turnmarker_changes = {};
if (dirty & /*renderedLogEntries*/ 4) turnmarker_changes.turn = /*turn*/ ctx[22];
if (dirty & /*turnBoundaries*/ 8) turnmarker_changes.numEvents = /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]];
turnmarker.$set(turnmarker_changes);
},
i(local) {
if (current) return;
transition_in(turnmarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(turnmarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(turnmarker, detaching);
}
};
}
// (135:2) {#each renderedLogEntries as { turn }
function create_each_block_2(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*turnBoundaries*/ ctx[3] && create_if_block_1$4(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*turnBoundaries*/ ctx[3]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*turnBoundaries*/ 8) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$4(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (141:2) {#each renderedLogEntries as { action, metadata }
function create_each_block_1(ctx) {
let logevent;
let current;
logevent = new LogEvent({
props: {
pinned: /*i*/ ctx[18] === /*pinned*/ ctx[1],
logIndex: /*i*/ ctx[18],
action: /*action*/ ctx[19],
metadata: /*metadata*/ ctx[20]
}
});
logevent.$on("click", /*OnLogClick*/ ctx[5]);
logevent.$on("mouseenter", /*OnMouseEnter*/ ctx[6]);
logevent.$on("mouseleave", /*OnMouseLeave*/ ctx[7]);
return {
c() {
create_component(logevent.$$.fragment);
},
m(target, anchor) {
mount_component(logevent, target, anchor);
current = true;
},
p(ctx, dirty) {
const logevent_changes = {};
if (dirty & /*pinned*/ 2) logevent_changes.pinned = /*i*/ ctx[18] === /*pinned*/ ctx[1];
if (dirty & /*renderedLogEntries*/ 4) logevent_changes.action = /*action*/ ctx[19];
if (dirty & /*renderedLogEntries*/ 4) logevent_changes.metadata = /*metadata*/ ctx[20];
logevent.$set(logevent_changes);
},
i(local) {
if (current) return;
transition_in(logevent.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logevent.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logevent, detaching);
}
};
}
// (153:4) {#if i in phaseBoundaries}
function create_if_block$b(ctx) {
let phasemarker;
let current;
phasemarker = new PhaseMarker({
props: {
phase: /*phase*/ ctx[16],
numEvents: /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(phasemarker.$$.fragment);
},
m(target, anchor) {
mount_component(phasemarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const phasemarker_changes = {};
if (dirty & /*renderedLogEntries*/ 4) phasemarker_changes.phase = /*phase*/ ctx[16];
if (dirty & /*phaseBoundaries*/ 16) phasemarker_changes.numEvents = /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]];
phasemarker.$set(phasemarker_changes);
},
i(local) {
if (current) return;
transition_in(phasemarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(phasemarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(phasemarker, detaching);
}
};
}
// (152:2) {#each renderedLogEntries as { phase }
function create_each_block$8(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4] && create_if_block$b(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*phaseBoundaries*/ 16) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$b(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function create_fragment$v(ctx) {
let div;
let t0;
let t1;
let current;
let mounted;
let dispose;
let each_value_2 = /*renderedLogEntries*/ ctx[2];
let each_blocks_2 = [];
for (let i = 0; i < each_value_2.length; i += 1) {
each_blocks_2[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
}
const out = i => transition_out(each_blocks_2[i], 1, 1, () => {
each_blocks_2[i] = null;
});
let each_value_1 = /*renderedLogEntries*/ ctx[2];
let each_blocks_1 = [];
for (let i = 0; i < each_value_1.length; i += 1) {
each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
}
const out_1 = i => transition_out(each_blocks_1[i], 1, 1, () => {
each_blocks_1[i] = null;
});
let each_value = /*renderedLogEntries*/ ctx[2];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$8(get_each_context$8(ctx, each_value, i));
}
const out_2 = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].c();
}
t0 = space();
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].c();
}
t1 = space();
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "gamelog svelte-1pq5e4b");
toggle_class(div, "pinned", /*pinned*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].m(div, null);
}
append(div, t0);
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].m(div, null);
}
append(div, t1);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[8]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*renderedLogEntries, turnBoundaries*/ 12) {
each_value_2 = /*renderedLogEntries*/ ctx[2];
let i;
for (i = 0; i < each_value_2.length; i += 1) {
const child_ctx = get_each_context_2(ctx, each_value_2, i);
if (each_blocks_2[i]) {
each_blocks_2[i].p(child_ctx, dirty);
transition_in(each_blocks_2[i], 1);
} else {
each_blocks_2[i] = create_each_block_2(child_ctx);
each_blocks_2[i].c();
transition_in(each_blocks_2[i], 1);
each_blocks_2[i].m(div, t0);
}
}
group_outros();
for (i = each_value_2.length; i < each_blocks_2.length; i += 1) {
out(i);
}
check_outros();
}
if (dirty & /*pinned, renderedLogEntries, OnLogClick, OnMouseEnter, OnMouseLeave*/ 230) {
each_value_1 = /*renderedLogEntries*/ ctx[2];
let i;
for (i = 0; i < each_value_1.length; i += 1) {
const child_ctx = get_each_context_1(ctx, each_value_1, i);
if (each_blocks_1[i]) {
each_blocks_1[i].p(child_ctx, dirty);
transition_in(each_blocks_1[i], 1);
} else {
each_blocks_1[i] = create_each_block_1(child_ctx);
each_blocks_1[i].c();
transition_in(each_blocks_1[i], 1);
each_blocks_1[i].m(div, t1);
}
}
group_outros();
for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
out_1(i);
}
check_outros();
}
if (dirty & /*renderedLogEntries, phaseBoundaries*/ 20) {
each_value = /*renderedLogEntries*/ ctx[2];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$8(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$8(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out_2(i);
}
check_outros();
}
if (dirty & /*pinned*/ 2) {
toggle_class(div, "pinned", /*pinned*/ ctx[1]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value_2.length; i += 1) {
transition_in(each_blocks_2[i]);
}
for (let i = 0; i < each_value_1.length; i += 1) {
transition_in(each_blocks_1[i]);
}
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks_2 = each_blocks_2.filter(Boolean);
for (let i = 0; i < each_blocks_2.length; i += 1) {
transition_out(each_blocks_2[i]);
}
each_blocks_1 = each_blocks_1.filter(Boolean);
for (let i = 0; i < each_blocks_1.length; i += 1) {
transition_out(each_blocks_1[i]);
}
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks_2, detaching);
destroy_each(each_blocks_1, detaching);
destroy_each(each_blocks, detaching);
mounted = false;
dispose();
}
};
}
function instance$v($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(10, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
const { secondaryPane } = getContext("secondaryPane");
const reducer = CreateGameReducer({ game: client.game });
const initialState = client.getInitialState();
let { log } = $client;
let pinned = null;
function rewind(logIndex) {
let state = initialState;
for (let i = 0; i < log.length; i++) {
const { action, automatic } = log[i];
if (!automatic) {
state = reducer(state, action);
if (logIndex == 0) {
break;
}
logIndex--;
}
}
return {
G: state.G,
ctx: state.ctx,
plugins: state.plugins
};
}
function OnLogClick(e) {
const { logIndex } = e.detail;
const state = rewind(logIndex);
const renderedLogEntries = log.filter(e => !e.automatic);
client.overrideGameState(state);
if (pinned == logIndex) {
$$invalidate(1, pinned = null);
secondaryPane.set(null);
} else {
$$invalidate(1, pinned = logIndex);
const { metadata } = renderedLogEntries[logIndex].action.payload;
if (metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
}
}
function OnMouseEnter(e) {
const { logIndex } = e.detail;
if (pinned === null) {
const state = rewind(logIndex);
client.overrideGameState(state);
}
}
function OnMouseLeave() {
if (pinned === null) {
client.overrideGameState(null);
}
}
function Reset() {
$$invalidate(1, pinned = null);
client.overrideGameState(null);
secondaryPane.set(null);
}
onDestroy(Reset);
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Reset();
}
}
let renderedLogEntries;
let turnBoundaries = {};
let phaseBoundaries = {};
$$self.$set = $$props => {
if ("client" in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$client, log, renderedLogEntries*/ 1540) {
$: {
$$invalidate(9, log = $client.log);
$$invalidate(2, renderedLogEntries = log.filter(e => !e.automatic));
let eventsInCurrentPhase = 0;
let eventsInCurrentTurn = 0;
$$invalidate(3, turnBoundaries = {});
$$invalidate(4, phaseBoundaries = {});
for (let i = 0; i < renderedLogEntries.length; i++) {
const { action, payload, turn, phase } = renderedLogEntries[i];
eventsInCurrentTurn++;
eventsInCurrentPhase++;
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].turn != turn) {
$$invalidate(3, turnBoundaries[i] = eventsInCurrentTurn, turnBoundaries);
eventsInCurrentTurn = 0;
}
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].phase != phase) {
$$invalidate(4, phaseBoundaries[i] = eventsInCurrentPhase, phaseBoundaries);
eventsInCurrentPhase = 0;
}
}
}
}
};
return [
client,
pinned,
renderedLogEntries,
turnBoundaries,
phaseBoundaries,
OnLogClick,
OnMouseEnter,
OnMouseLeave,
OnKeyDown
];
}
class Log extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1pq5e4b-style")) add_css$n();
init(this, options, instance$v, create_fragment$v, safe_not_equal, { client: 0 });
}
}
/* src/client/debug/ai/Options.svelte generated by Svelte v3.24.0 */
function add_css$o() {
var style = element("style");
style.id = "svelte-1fu900w-style";
style.textContent = "label.svelte-1fu900w{color:#666}.option.svelte-1fu900w{margin-bottom:20px}.value.svelte-1fu900w{font-weight:bold;color:#000}input[type='checkbox'].svelte-1fu900w{vertical-align:middle}";
append(document.head, style);
}
function get_each_context$9(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[5] = list[i][0];
child_ctx[6] = list[i][1];
return child_ctx;
}
// (39:4) {#if value.range}
function create_if_block_1$5(ctx) {
let span;
let t0_value = /*values*/ ctx[1][/*key*/ ctx[5]] + "";
let t0;
let t1;
let input;
let input_min_value;
let input_max_value;
let mounted;
let dispose;
function input_change_input_handler() {
/*input_change_input_handler*/ ctx[3].call(input, /*key*/ ctx[5]);
}
return {
c() {
span = element("span");
t0 = text(t0_value);
t1 = space();
input = element("input");
attr(span, "class", "value svelte-1fu900w");
attr(input, "type", "range");
attr(input, "min", input_min_value = /*value*/ ctx[6].range.min);
attr(input, "max", input_max_value = /*value*/ ctx[6].range.max);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t0);
insert(target, t1, anchor);
insert(target, input, anchor);
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[5]]);
if (!mounted) {
dispose = [
listen(input, "change", input_change_input_handler),
listen(input, "input", input_change_input_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*values, bot*/ 3 && t0_value !== (t0_value = /*values*/ ctx[1][/*key*/ ctx[5]] + "")) set_data(t0, t0_value);
if (dirty & /*bot*/ 1 && input_min_value !== (input_min_value = /*value*/ ctx[6].range.min)) {
attr(input, "min", input_min_value);
}
if (dirty & /*bot*/ 1 && input_max_value !== (input_max_value = /*value*/ ctx[6].range.max)) {
attr(input, "max", input_max_value);
}
if (dirty & /*values, Object, bot*/ 3) {
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[5]]);
}
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(t1);
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (44:4) {#if typeof value.value === 'boolean'}
function create_if_block$c(ctx) {
let input;
let mounted;
let dispose;
function input_change_handler() {
/*input_change_handler*/ ctx[4].call(input, /*key*/ ctx[5]);
}
return {
c() {
input = element("input");
attr(input, "type", "checkbox");
attr(input, "class", "svelte-1fu900w");
},
m(target, anchor) {
insert(target, input, anchor);
input.checked = /*values*/ ctx[1][/*key*/ ctx[5]];
if (!mounted) {
dispose = [
listen(input, "change", input_change_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*values, Object, bot*/ 3) {
input.checked = /*values*/ ctx[1][/*key*/ ctx[5]];
}
},
d(detaching) {
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (35:0) {#each Object.entries(bot.opts()) as [key, value]}
function create_each_block$9(ctx) {
let div;
let label;
let t0_value = /*key*/ ctx[5] + "";
let t0;
let t1;
let t2;
let t3;
let if_block0 = /*value*/ ctx[6].range && create_if_block_1$5(ctx);
let if_block1 = typeof /*value*/ ctx[6].value === "boolean" && create_if_block$c(ctx);
return {
c() {
div = element("div");
label = element("label");
t0 = text(t0_value);
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
t3 = space();
attr(label, "class", "svelte-1fu900w");
attr(div, "class", "option svelte-1fu900w");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, label);
append(label, t0);
append(div, t1);
if (if_block0) if_block0.m(div, null);
append(div, t2);
if (if_block1) if_block1.m(div, null);
append(div, t3);
},
p(ctx, dirty) {
if (dirty & /*bot*/ 1 && t0_value !== (t0_value = /*key*/ ctx[5] + "")) set_data(t0, t0_value);
if (/*value*/ ctx[6].range) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_1$5(ctx);
if_block0.c();
if_block0.m(div, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (typeof /*value*/ ctx[6].value === "boolean") {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block$c(ctx);
if_block1.c();
if_block1.m(div, t3);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(div);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
}
};
}
function create_fragment$w(ctx) {
let each_1_anchor;
let each_value = Object.entries(/*bot*/ ctx[0].opts());
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$9(get_each_context$9(ctx, each_value, i));
}
return {
c() {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(target, anchor);
}
insert(target, each_1_anchor, anchor);
},
p(ctx, [dirty]) {
if (dirty & /*values, Object, bot, OnChange*/ 7) {
each_value = Object.entries(/*bot*/ ctx[0].opts());
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$9(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$9(child_ctx);
each_blocks[i].c();
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
destroy_each(each_blocks, detaching);
if (detaching) detach(each_1_anchor);
}
};
}
function instance$w($$self, $$props, $$invalidate) {
let { bot } = $$props;
let values = {};
for (let [key, value] of Object.entries(bot.opts())) {
values[key] = value.value;
}
function OnChange() {
for (let [key, value] of Object.entries(values)) {
bot.setOpt(key, value);
}
}
function input_change_input_handler(key) {
values[key] = to_number(this.value);
$$invalidate(1, values);
$$invalidate(0, bot);
}
function input_change_handler(key) {
values[key] = this.checked;
$$invalidate(1, values);
$$invalidate(0, bot);
}
$$self.$set = $$props => {
if ("bot" in $$props) $$invalidate(0, bot = $$props.bot);
};
return [bot, values, OnChange, input_change_input_handler, input_change_handler];
}
class Options extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1fu900w-style")) add_css$o();
init(this, options, instance$w, create_fragment$w, safe_not_equal, { bot: 0 });
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Base class that bots can extend.
*/
class Bot {
constructor({ enumerate, seed, }) {
this.enumerateFn = enumerate;
this.seed = seed;
this.iterationCounter = 0;
this._opts = {};
}
addOpt({ key, range, initial, }) {
this._opts[key] = {
range,
value: initial,
};
}
getOpt(key) {
return this._opts[key].value;
}
setOpt(key, value) {
if (key in this._opts) {
this._opts[key].value = value;
}
}
opts() {
return this._opts;
}
enumerate(G, ctx, playerID) {
const actions = this.enumerateFn(G, ctx, playerID);
return actions.map((a) => {
if ('payload' in a) {
return a;
}
if ('move' in a) {
return makeMove(a.move, a.args, playerID);
}
if ('event' in a) {
return gameEvent(a.event, a.args, playerID);
}
});
}
random(arg) {
let number;
if (this.seed !== undefined) {
const seed = this.prngstate ? '' : this.seed;
const rand = alea(seed, this.prngstate);
number = rand();
this.prngstate = rand.state();
}
else {
number = Math.random();
}
if (arg) {
if (Array.isArray(arg)) {
const id = Math.floor(number * arg.length);
return arg[id];
}
else {
return Math.floor(number * arg);
}
}
return number;
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* The number of iterations to run before yielding to
* the JS event loop (in async mode).
*/
const CHUNK_SIZE = 25;
/**
* Bot that uses Monte-Carlo Tree Search to find promising moves.
*/
class MCTSBot extends Bot {
constructor({ enumerate, seed, objectives, game, iterations, playoutDepth, iterationCallback, }) {
super({ enumerate, seed });
if (objectives === undefined) {
objectives = () => ({});
}
this.objectives = objectives;
this.iterationCallback = iterationCallback || (() => { });
this.reducer = CreateGameReducer({ game });
this.iterations = iterations;
this.playoutDepth = playoutDepth;
this.addOpt({
key: 'async',
initial: false,
});
this.addOpt({
key: 'iterations',
initial: typeof iterations === 'number' ? iterations : 1000,
range: { min: 1, max: 2000 },
});
this.addOpt({
key: 'playoutDepth',
initial: typeof playoutDepth === 'number' ? playoutDepth : 50,
range: { min: 1, max: 100 },
});
}
createNode({ state, parentAction, parent, playerID, }) {
const { G, ctx } = state;
let actions = [];
let objectives = [];
if (playerID !== undefined) {
actions = this.enumerate(G, ctx, playerID);
objectives = this.objectives(G, ctx, playerID);
}
else if (ctx.activePlayers) {
for (const playerID in ctx.activePlayers) {
actions = actions.concat(this.enumerate(G, ctx, playerID));
objectives = objectives.concat(this.objectives(G, ctx, playerID));
}
}
else {
actions = actions.concat(this.enumerate(G, ctx, ctx.currentPlayer));
objectives = objectives.concat(this.objectives(G, ctx, ctx.currentPlayer));
}
return {
state,
parent,
parentAction,
actions,
objectives,
children: [],
visits: 0,
value: 0,
};
}
select(node) {
// This node has unvisited children.
if (node.actions.length > 0) {
return node;
}
// This is a terminal node.
if (node.children.length == 0) {
return node;
}
let selectedChild = null;
let best = 0;
for (const child of node.children) {
const childVisits = child.visits + Number.EPSILON;
const uct = child.value / childVisits +
Math.sqrt((2 * Math.log(node.visits)) / childVisits);
if (selectedChild == null || uct > best) {
best = uct;
selectedChild = child;
}
}
return this.select(selectedChild);
}
expand(node) {
const actions = node.actions;
if (actions.length == 0 || node.state.ctx.gameover !== undefined) {
return node;
}
const id = this.random(actions.length);
const action = actions[id];
node.actions.splice(id, 1);
const childState = this.reducer(node.state, action);
const childNode = this.createNode({
state: childState,
parentAction: action,
parent: node,
});
node.children.push(childNode);
return childNode;
}
playout({ state }) {
let playoutDepth = this.getOpt('playoutDepth');
if (typeof this.playoutDepth === 'function') {
playoutDepth = this.playoutDepth(state.G, state.ctx);
}
for (let i = 0; i < playoutDepth && state.ctx.gameover === undefined; i++) {
const { G, ctx } = state;
let playerID = ctx.currentPlayer;
if (ctx.activePlayers) {
playerID = Object.keys(ctx.activePlayers)[0];
}
const moves = this.enumerate(G, ctx, playerID);
// Check if any objectives are met.
const objectives = this.objectives(G, ctx, playerID);
const score = Object.keys(objectives).reduce((score, key) => {
const objective = objectives[key];
if (objective.checker(G, ctx)) {
return score + objective.weight;
}
return score;
}, 0);
// If so, stop and return the score.
if (score > 0) {
return { score };
}
if (!moves || moves.length == 0) {
return undefined;
}
const id = this.random(moves.length);
const childState = this.reducer(state, moves[id]);
state = childState;
}
return state.ctx.gameover;
}
backpropagate(node, result = {}) {
node.visits++;
if (result.score !== undefined) {
node.value += result.score;
}
if (result.draw === true) {
node.value += 0.5;
}
if (node.parentAction &&
result.winner === node.parentAction.payload.playerID) {
node.value++;
}
if (node.parent) {
this.backpropagate(node.parent, result);
}
}
play(state, playerID) {
const root = this.createNode({ state, playerID });
let numIterations = this.getOpt('iterations');
if (typeof this.iterations === 'function') {
numIterations = this.iterations(state.G, state.ctx);
}
const getResult = () => {
let selectedChild = null;
for (const child of root.children) {
if (selectedChild == null || child.visits > selectedChild.visits) {
selectedChild = child;
}
}
const action = selectedChild && selectedChild.parentAction;
const metadata = root;
return { action, metadata };
};
return new Promise((resolve) => {
const iteration = () => {
for (let i = 0; i < CHUNK_SIZE && this.iterationCounter < numIterations; i++) {
const leaf = this.select(root);
const child = this.expand(leaf);
const result = this.playout(child);
this.backpropagate(child, result);
this.iterationCounter++;
}
this.iterationCallback({
iterationCounter: this.iterationCounter,
numIterations,
metadata: root,
});
};
this.iterationCounter = 0;
if (this.getOpt('async')) {
const asyncIteration = () => {
if (this.iterationCounter < numIterations) {
iteration();
setTimeout(asyncIteration, 0);
}
else {
resolve(getResult());
}
};
asyncIteration();
}
else {
while (this.iterationCounter < numIterations) {
iteration();
}
resolve(getResult());
}
});
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Bot that picks a move at random.
*/
class RandomBot extends Bot {
play({ G, ctx }, playerID) {
const moves = this.enumerate(G, ctx, playerID);
return Promise.resolve({ action: this.random(moves) });
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Make a single move on the client with a bot.
*
* @param {...object} client - The game client.
* @param {...object} bot - The bot.
*/
async function Step(client, bot) {
const state = client.store.getState();
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const { action, metadata } = await bot.play(state, playerID);
if (action) {
const a = {
...action,
payload: {
...action.payload,
metadata,
},
};
client.store.dispatch(a);
return a;
}
}
/**
* Simulates the game till the end or a max depth.
*
* @param {...object} game - The game object.
* @param {...object} bots - An array of bots.
* @param {...object} state - The game state to start from.
*/
async function Simulate({ game, bots, state, depth, }) {
if (depth === undefined)
depth = 10000;
const reducer = CreateGameReducer({ game });
let metadata = null;
let iter = 0;
while (state.ctx.gameover === undefined && iter < depth) {
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const bot = bots instanceof Bot ? bots : bots[playerID];
const t = await bot.play(state, playerID);
if (!t.action) {
break;
}
metadata = t.metadata;
state = reducer(state, t.action);
iter++;
}
return { state, metadata };
}
/* src/client/debug/ai/AI.svelte generated by Svelte v3.24.0 */
function add_css$p() {
var style = element("style");
style.id = "svelte-lifdi8-style";
style.textContent = "ul.svelte-lifdi8{padding-left:0}li.svelte-lifdi8{list-style:none;margin:none;margin-bottom:5px}h3.svelte-lifdi8{text-transform:uppercase}label.svelte-lifdi8{color:#666}input[type='checkbox'].svelte-lifdi8{vertical-align:middle}";
append(document.head, style);
}
function get_each_context$a(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (201:4) {:else}
function create_else_block$3(ctx) {
let p0;
let t1;
let p1;
return {
c() {
p0 = element("p");
p0.textContent = "No bots available.";
t1 = space();
p1 = element("p");
p1.innerHTML = `Follow the instructions
<a href="https://boardgame.io/documentation/#/tutorial?id=bots" target="_blank">here</a>
to set up bots.`;
},
m(target, anchor) {
insert(target, p0, anchor);
insert(target, t1, anchor);
insert(target, p1, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p0);
if (detaching) detach(t1);
if (detaching) detach(p1);
}
};
}
// (199:4) {#if client.multiplayer}
function create_if_block_5(ctx) {
let p;
return {
c() {
p = element("p");
p.textContent = "The bot debugger is only available in singleplayer mode.";
},
m(target, anchor) {
insert(target, p, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p);
}
};
}
// (149:2) {#if client.game.ai && !client.multiplayer}
function create_if_block$d(ctx) {
let section0;
let h30;
let t1;
let ul;
let li0;
let hotkey0;
let t2;
let li1;
let hotkey1;
let t3;
let li2;
let hotkey2;
let t4;
let section1;
let h31;
let t6;
let select;
let t7;
let show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
let t8;
let if_block1_anchor;
let current;
let mounted;
let dispose;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*Reset*/ ctx[13],
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Step*/ ctx[11],
label: "play"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Simulate*/ ctx[12],
label: "simulate"
}
});
let each_value = Object.keys(/*bots*/ ctx[8]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$a(get_each_context$a(ctx, each_value, i));
}
let if_block0 = show_if && create_if_block_4(ctx);
let if_block1 = (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) && create_if_block_1$6(ctx);
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t2 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t3 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t4 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Bot";
t6 = space();
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t7 = space();
if (if_block0) if_block0.c();
t8 = space();
if (if_block1) if_block1.c();
if_block1_anchor = empty();
attr(h30, "class", "svelte-lifdi8");
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(li2, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
attr(h31, "class", "svelte-lifdi8");
if (/*selectedBot*/ ctx[4] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[16].call(select));
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
append(section0, ul);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t2);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t3);
append(ul, li2);
mount_component(hotkey2, li2, null);
insert(target, t4, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t6);
append(section1, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selectedBot*/ ctx[4]);
insert(target, t7, anchor);
if (if_block0) if_block0.m(target, anchor);
insert(target, t8, anchor);
if (if_block1) if_block1.m(target, anchor);
insert(target, if_block1_anchor, anchor);
current = true;
if (!mounted) {
dispose = [
listen(select, "change", /*select_change_handler*/ ctx[16]),
listen(select, "change", /*ChangeBot*/ ctx[10])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*Object, bots*/ 256) {
each_value = Object.keys(/*bots*/ ctx[8]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$a(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$a(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selectedBot, Object, bots*/ 272) {
select_option(select, /*selectedBot*/ ctx[4]);
}
if (dirty & /*bot*/ 128) show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
if (show_if) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*bot*/ 128) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_4(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(t8.parentNode, t8);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_1$6(ctx);
if_block1.c();
if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(if_block0);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(if_block0);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
if (detaching) detach(t4);
if (detaching) detach(section1);
destroy_each(each_blocks, detaching);
if (detaching) detach(t7);
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t8);
if (if_block1) if_block1.d(detaching);
if (detaching) detach(if_block1_anchor);
mounted = false;
run_all(dispose);
}
};
}
// (168:8) {#each Object.keys(bots) as bot}
function create_each_block$a(ctx) {
let option;
let t_value = /*bot*/ ctx[7] + "";
let t;
let option_value_value;
return {
c() {
option = element("option");
t = text(t_value);
option.__value = option_value_value = /*bot*/ ctx[7];
option.value = option.__value;
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t);
},
p: noop,
d(detaching) {
if (detaching) detach(option);
}
};
}
// (174:4) {#if Object.keys(bot.opts()).length}
function create_if_block_4(ctx) {
let section;
let h3;
let t1;
let label;
let t3;
let input;
let t4;
let options;
let current;
let mounted;
let dispose;
options = new Options({ props: { bot: /*bot*/ ctx[7] } });
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Options";
t1 = space();
label = element("label");
label.textContent = "debug";
t3 = space();
input = element("input");
t4 = space();
create_component(options.$$.fragment);
attr(h3, "class", "svelte-lifdi8");
attr(label, "class", "svelte-lifdi8");
attr(input, "type", "checkbox");
attr(input, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
append(section, label);
append(section, t3);
append(section, input);
input.checked = /*debug*/ ctx[1];
append(section, t4);
mount_component(options, section, null);
current = true;
if (!mounted) {
dispose = [
listen(input, "change", /*input_change_handler*/ ctx[17]),
listen(input, "change", /*OnDebug*/ ctx[9])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debug*/ 2) {
input.checked = /*debug*/ ctx[1];
}
const options_changes = {};
if (dirty & /*bot*/ 128) options_changes.bot = /*bot*/ ctx[7];
options.$set(options_changes);
},
i(local) {
if (current) return;
transition_in(options.$$.fragment, local);
current = true;
},
o(local) {
transition_out(options.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(options);
mounted = false;
run_all(dispose);
}
};
}
// (183:4) {#if botAction || iterationCounter}
function create_if_block_1$6(ctx) {
let section;
let h3;
let t1;
let t2;
let if_block0 = /*progress*/ ctx[2] && /*progress*/ ctx[2] < 1 && create_if_block_3$1(ctx);
let if_block1 = /*botAction*/ ctx[5] && create_if_block_2$4(ctx);
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Result";
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
attr(h3, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
if (if_block0) if_block0.m(section, null);
append(section, t2);
if (if_block1) if_block1.m(section, null);
},
p(ctx, dirty) {
if (/*progress*/ ctx[2] && /*progress*/ ctx[2] < 1) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_3$1(ctx);
if_block0.c();
if_block0.m(section, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (/*botAction*/ ctx[5]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_2$4(ctx);
if_block1.c();
if_block1.m(section, null);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(section);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
}
};
}
// (186:6) {#if progress && progress < 1.0}
function create_if_block_3$1(ctx) {
let progress_1;
return {
c() {
progress_1 = element("progress");
progress_1.value = /*progress*/ ctx[2];
},
m(target, anchor) {
insert(target, progress_1, anchor);
},
p(ctx, dirty) {
if (dirty & /*progress*/ 4) {
progress_1.value = /*progress*/ ctx[2];
}
},
d(detaching) {
if (detaching) detach(progress_1);
}
};
}
// (190:6) {#if botAction}
function create_if_block_2$4(ctx) {
let ul;
let li0;
let t0;
let t1;
let t2;
let li1;
let t3;
let t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "";
let t4;
return {
c() {
ul = element("ul");
li0 = element("li");
t0 = text("Action: ");
t1 = text(/*botAction*/ ctx[5]);
t2 = space();
li1 = element("li");
t3 = text("Args: ");
t4 = text(t4_value);
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
append(li0, t0);
append(li0, t1);
append(ul, t2);
append(ul, li1);
append(li1, t3);
append(li1, t4);
},
p(ctx, dirty) {
if (dirty & /*botAction*/ 32) set_data(t1, /*botAction*/ ctx[5]);
if (dirty & /*botActionArgs*/ 64 && t4_value !== (t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "")) set_data(t4, t4_value);
},
d(detaching) {
if (detaching) detach(ul);
}
};
}
function create_fragment$x(ctx) {
let section;
let current_block_type_index;
let if_block;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$d, create_if_block_5, create_else_block$3];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*client*/ ctx[0].game.ai && !/*client*/ ctx[0].multiplayer) return 0;
if (/*client*/ ctx[0].multiplayer) return 1;
return 2;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
section = element("section");
if_block.c();
},
m(target, anchor) {
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[14]);
mounted = true;
}
},
p(ctx, [dirty]) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
}
transition_in(if_block, 1);
if_block.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$x($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
const { secondaryPane } = getContext("secondaryPane");
const bots = { "MCTS": MCTSBot, "Random": RandomBot };
let debug = false;
let progress = null;
let iterationCounter = 0;
let metadata = null;
const iterationCallback = ({ iterationCounter: c, numIterations, metadata: m }) => {
$$invalidate(3, iterationCounter = c);
$$invalidate(2, progress = c / numIterations);
metadata = m;
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
};
function OnDebug() {
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
} else {
secondaryPane.set(null);
}
}
let bot;
if (client.game.ai) {
bot = new MCTSBot({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
});
bot.setOpt("async", true);
}
let selectedBot;
let botAction;
let botActionArgs;
function ChangeBot() {
const botConstructor = bots[selectedBot];
$$invalidate(7, bot = new botConstructor({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
}));
bot.setOpt("async", true);
$$invalidate(5, botAction = null);
metadata = null;
secondaryPane.set(null);
$$invalidate(3, iterationCounter = 0);
}
async function Step$1() {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const t = await Step(client, bot);
if (t) {
$$invalidate(5, botAction = t.payload.type);
$$invalidate(6, botActionArgs = t.payload.args);
}
}
function Simulate(iterations = 10000, sleepTimeout = 100) {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const step = async () => {
for (let i = 0; i < iterations; i++) {
const action = await Step(client, bot);
if (!action) break;
await new Promise(resolve => setTimeout(resolve, sleepTimeout));
}
};
return step();
}
function Exit() {
client.overrideGameState(null);
secondaryPane.set(null);
$$invalidate(1, debug = false);
}
function Reset() {
client.reset();
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
Exit();
}
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Exit();
}
}
onDestroy(Exit);
function select_change_handler() {
selectedBot = select_value(this);
$$invalidate(4, selectedBot);
$$invalidate(8, bots);
}
function input_change_handler() {
debug = this.checked;
$$invalidate(1, debug);
}
$$self.$set = $$props => {
if ("client" in $$props) $$invalidate(0, client = $$props.client);
if ("clientManager" in $$props) $$invalidate(15, clientManager = $$props.clientManager);
};
return [
client,
debug,
progress,
iterationCounter,
selectedBot,
botAction,
botActionArgs,
bot,
bots,
OnDebug,
ChangeBot,
Step$1,
Simulate,
Reset,
OnKeyDown,
clientManager,
select_change_handler,
input_change_handler
];
}
class AI extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-lifdi8-style")) add_css$p();
init(this, options, instance$x, create_fragment$x, safe_not_equal, { client: 0, clientManager: 15 });
}
}
/* src/client/debug/Debug.svelte generated by Svelte v3.24.0 */
function add_css$q() {
var style = element("style");
style.id = "svelte-1dhkl71-style";
style.textContent = ".debug-panel.svelte-1dhkl71{position:fixed;color:#555;font-family:monospace;display:flex;flex-direction:row;text-align:left;right:0;top:0;height:100%;font-size:14px;box-sizing:border-box;opacity:0.9;z-index:99999}.pane.svelte-1dhkl71{flex-grow:2;overflow-x:hidden;overflow-y:scroll;background:#fefefe;padding:20px;border-left:1px solid #ccc;box-shadow:-1px 0 5px rgba(0, 0, 0, 0.2);box-sizing:border-box;width:280px}.secondary-pane.svelte-1dhkl71{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-1dhkl71 button,.debug-panel.svelte-1dhkl71 select{cursor:pointer;font-size:14px;font-family:monospace}.debug-panel.svelte-1dhkl71 select{background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-1dhkl71 section{margin-bottom:20px}.debug-panel.svelte-1dhkl71 .screen-reader-only{clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px}";
append(document.head, style);
}
// (118:0) {#if visible}
function create_if_block$e(ctx) {
let section;
let menu;
let t0;
let div;
let switch_instance;
let t1;
let section_transition;
let current;
menu = new Menu({
props: {
panes: /*panes*/ ctx[6],
pane: /*pane*/ ctx[2]
}
});
menu.$on("change", /*MenuChange*/ ctx[8]);
var switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component;
function switch_props(ctx) {
return {
props: {
client: /*client*/ ctx[4],
clientManager: /*clientManager*/ ctx[0]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
let if_block = /*$secondaryPane*/ ctx[5] && create_if_block_1$7(ctx);
return {
c() {
section = element("section");
create_component(menu.$$.fragment);
t0 = space();
div = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
t1 = space();
if (if_block) if_block.c();
attr(div, "class", "pane svelte-1dhkl71");
attr(div, "role", "region");
attr(div, "aria-label", /*pane*/ ctx[2]);
attr(div, "tabindex", "-1");
attr(section, "aria-label", "boardgame.io Debug Panel");
attr(section, "class", "debug-panel svelte-1dhkl71");
},
m(target, anchor) {
insert(target, section, anchor);
mount_component(menu, section, null);
append(section, t0);
append(section, div);
if (switch_instance) {
mount_component(switch_instance, div, null);
}
/*div_binding*/ ctx[10](div);
append(section, t1);
if (if_block) if_block.m(section, null);
current = true;
},
p(ctx, dirty) {
const menu_changes = {};
if (dirty & /*pane*/ 4) menu_changes.pane = /*pane*/ ctx[2];
menu.$set(menu_changes);
const switch_instance_changes = {};
if (dirty & /*client*/ 16) switch_instance_changes.client = /*client*/ ctx[4];
if (dirty & /*clientManager*/ 1) switch_instance_changes.clientManager = /*clientManager*/ ctx[0];
if (switch_value !== (switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
if (!current || dirty & /*pane*/ 4) {
attr(div, "aria-label", /*pane*/ ctx[2]);
}
if (/*$secondaryPane*/ ctx[5]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*$secondaryPane*/ 32) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$7(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(section, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(menu.$$.fragment, local);
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
transition_in(if_block);
add_render_callback(() => {
if (!section_transition) section_transition = create_bidirectional_transition(section, fly, { x: 400 }, true);
section_transition.run(1);
});
current = true;
},
o(local) {
transition_out(menu.$$.fragment, local);
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
transition_out(if_block);
if (!section_transition) section_transition = create_bidirectional_transition(section, fly, { x: 400 }, false);
section_transition.run(0);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(menu);
if (switch_instance) destroy_component(switch_instance);
/*div_binding*/ ctx[10](null);
if (if_block) if_block.d();
if (detaching && section_transition) section_transition.end();
}
};
}
// (130:4) {#if $secondaryPane}
function create_if_block_1$7(ctx) {
let div;
let switch_instance;
let current;
var switch_value = /*$secondaryPane*/ ctx[5].component;
function switch_props(ctx) {
return {
props: {
metadata: /*$secondaryPane*/ ctx[5].metadata
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
div = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
attr(div, "class", "secondary-pane svelte-1dhkl71");
},
m(target, anchor) {
insert(target, div, anchor);
if (switch_instance) {
mount_component(switch_instance, div, null);
}
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*$secondaryPane*/ 32) switch_instance_changes.metadata = /*$secondaryPane*/ ctx[5].metadata;
if (switch_value !== (switch_value = /*$secondaryPane*/ ctx[5].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
if (switch_instance) destroy_component(switch_instance);
}
};
}
function create_fragment$y(ctx) {
let if_block_anchor;
let current;
let mounted;
let dispose;
let if_block = /*visible*/ ctx[3] && create_if_block$e(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
if (!mounted) {
dispose = listen(window, "keypress", /*Keypress*/ ctx[9]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*visible*/ ctx[3]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*visible*/ 8) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$e(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
mounted = false;
dispose();
}
};
}
function instance$y($$self, $$props, $$invalidate) {
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(11, $clientManager = $$value)), clientManager);
let $secondaryPane;
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const panes = {
main: {
label: "Main",
shortcut: "m",
component: Main
},
log: {
label: "Log",
shortcut: "l",
component: Log
},
info: {
label: "Info",
shortcut: "i",
component: Info
},
ai: {
label: "AI",
shortcut: "a",
component: AI
}
};
const disableHotkeys = writable(false);
const secondaryPane = writable(null);
component_subscribe($$self, secondaryPane, value => $$invalidate(5, $secondaryPane = value));
setContext("hotkeys", { disableHotkeys });
setContext("secondaryPane", { secondaryPane });
let paneDiv;
let pane = "main";
function MenuChange(e) {
$$invalidate(2, pane = e.detail);
paneDiv.focus();
}
let visible = true;
function Keypress(e) {
// Toggle debugger visibilty
if (e.key == ".") {
$$invalidate(3, visible = !visible);
return;
}
// Set displayed pane
if (!visible) return;
Object.entries(panes).forEach(([key, { shortcut }]) => {
if (e.key == shortcut) {
$$invalidate(2, pane = key);
}
});
}
function div_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
paneDiv = $$value;
$$invalidate(1, paneDiv);
});
}
$$self.$set = $$props => {
if ("clientManager" in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
let client;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 2048) {
$: $$invalidate(4, client = $clientManager.client);
}
};
return [
clientManager,
paneDiv,
pane,
visible,
client,
$secondaryPane,
panes,
secondaryPane,
MenuChange,
Keypress,
div_binding
];
}
class Debug extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1dhkl71-style")) add_css$q();
init(this, options, instance$y, create_fragment$y, safe_not_equal, { clientManager: 0 });
}
}
/**
* Class to manage boardgame.io clients and limit debug panel rendering.
*/
class ClientManager {
constructor() {
this.debugPanel = null;
this.currentClient = null;
this.clients = new Map();
this.subscribers = new Map();
}
/**
* Register a client with the client manager.
*/
register(client) {
// Add client to clients map.
this.clients.set(client, client);
// Mount debug for this client (no-op if another debug is already mounted).
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Unregister a client from the client manager.
*/
unregister(client) {
// Remove client from clients map.
this.clients.delete(client);
if (this.currentClient === client) {
// If the removed client owned the debug panel, unmount it.
this.unmountDebug();
// Mount debug panel for next available client.
for (const [client] of this.clients) {
if (this.debugPanel)
break;
this.mountDebug(client);
}
}
this.notifySubscribers();
}
/**
* Subscribe to the client manager state.
* Calls the passed callback each time the current client changes or a client
* registers/unregisters.
* Returns a function to unsubscribe from the state updates.
*/
subscribe(callback) {
const id = Symbol();
this.subscribers.set(id, callback);
callback(this.getState());
return () => {
this.subscribers.delete(id);
};
}
/**
* Switch to a client with a matching playerID.
*/
switchPlayerID(playerID) {
// For multiplayer clients, try switching control to a different client
// that is using the same transport layer.
if (this.currentClient.multiplayer) {
for (const [client] of this.clients) {
if (client.playerID === playerID &&
client.debugOpt !== false &&
client.multiplayer === this.currentClient.multiplayer) {
this.switchToClient(client);
return;
}
}
}
// If no client matches, update the playerID for the current client.
this.currentClient.updatePlayerID(playerID);
this.notifySubscribers();
}
/**
* Set the passed client as the active client for debugging.
*/
switchToClient(client) {
if (client === this.currentClient)
return;
this.unmountDebug();
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Notify all subscribers of changes to the client manager state.
*/
notifySubscribers() {
const arg = this.getState();
this.subscribers.forEach((cb) => {
cb(arg);
});
}
/**
* Get the client manager state.
*/
getState() {
return {
client: this.currentClient,
debuggableClients: this.getDebuggableClients(),
};
}
/**
* Get an array of the registered clients that haven’t disabled the debug panel.
*/
getDebuggableClients() {
return [...this.clients.values()].filter((client) => client.debugOpt !== false);
}
/**
* Mount the debug panel using the passed client.
*/
mountDebug(client) {
if (client.debugOpt === false ||
this.debugPanel !== null ||
typeof document === 'undefined') {
return;
}
let DebugImpl;
let target = document.body;
if (process.env.NODE_ENV !== 'production') {
DebugImpl = Debug;
}
if (client.debugOpt && client.debugOpt !== true) {
DebugImpl = client.debugOpt.impl || DebugImpl;
target = client.debugOpt.target || target;
}
if (DebugImpl) {
this.currentClient = client;
this.debugPanel = new DebugImpl({
target,
props: { clientManager: this },
});
}
}
/**
* Unmount the debug panel.
*/
unmountDebug() {
this.debugPanel.$destroy();
this.debugPanel = null;
this.currentClient = null;
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Global client manager instance that all clients register with.
*/
const GlobalClientManager = new ClientManager();
/**
* Standardise the passed playerID, using currentPlayer if appropriate.
*/
function assumedPlayerID(playerID, store, multiplayer) {
// In singleplayer mode, if the client does not have a playerID
// associated with it, we attach the currentPlayer as playerID.
if (!multiplayer && (playerID === null || playerID === undefined)) {
const state = store.getState();
playerID = state.ctx.currentPlayer;
}
return playerID;
}
/**
* createDispatchers
*
* Create action dispatcher wrappers with bound playerID and credentials
*/
function createDispatchers(storeActionType, innerActionNames, store, playerID, credentials, multiplayer) {
return innerActionNames.reduce((dispatchers, name) => {
dispatchers[name] = function (...args) {
store.dispatch(ActionCreators[storeActionType](name, args, assumedPlayerID(playerID, store, multiplayer), credentials));
};
return dispatchers;
}, {});
}
// Creates a set of dispatchers to make moves.
const createMoveDispatchers = createDispatchers.bind(null, 'makeMove');
// Creates a set of dispatchers to dispatch game flow events.
const createEventDispatchers = createDispatchers.bind(null, 'gameEvent');
// Creates a set of dispatchers to dispatch actions to plugins.
const createPluginDispatchers = createDispatchers.bind(null, 'plugin');
/**
* Implementation of Client (see below).
*/
class _ClientImpl {
constructor({ game, debug, numPlayers, multiplayer, matchID: matchID, playerID, credentials, enhancer, }) {
this.game = ProcessGameConfig(game);
this.playerID = playerID;
this.matchID = matchID;
this.credentials = credentials;
this.multiplayer = multiplayer;
this.debugOpt = debug;
this.manager = GlobalClientManager;
this.gameStateOverride = null;
this.subscribers = {};
this._running = false;
this.reducer = CreateGameReducer({
game: this.game,
isClient: multiplayer !== undefined,
});
this.initialState = null;
if (!multiplayer) {
this.initialState = InitializeGame({ game: this.game, numPlayers });
}
this.reset = () => {
this.store.dispatch(reset(this.initialState));
};
this.undo = () => {
const undo$1 = undo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(undo$1);
};
this.redo = () => {
const redo$1 = redo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(redo$1);
};
this.log = [];
/**
* Middleware that manages the log object.
* Reducers generate deltalogs, which are log events
* that are the result of application of a single action.
* The master may also send back a deltalog or the entire
* log depending on the type of request.
* The middleware below takes care of all these cases while
* managing the log object.
*/
const LogMiddleware = (store) => (next) => (action) => {
const result = next(action);
const state = store.getState();
switch (action.type) {
case MAKE_MOVE:
case GAME_EVENT:
case UNDO:
case REDO: {
const deltalog = state.deltalog;
this.log = [...this.log, ...deltalog];
break;
}
case RESET: {
this.log = [];
break;
}
case UPDATE: {
let id = -1;
if (this.log.length > 0) {
id = this.log[this.log.length - 1]._stateID;
}
let deltalog = action.deltalog || [];
// Filter out actions that are already present
// in the current log. This may occur when the
// client adds an entry to the log followed by
// the update from the master here.
deltalog = deltalog.filter((l) => l._stateID > id);
this.log = [...this.log, ...deltalog];
break;
}
case SYNC: {
this.initialState = action.initialState;
this.log = action.log || [];
break;
}
}
return result;
};
/**
* Middleware that intercepts actions and sends them to the master,
* which keeps the authoritative version of the state.
*/
const TransportMiddleware = (store) => (next) => (action) => {
const baseState = store.getState();
const result = next(action);
if (!('clientOnly' in action)) {
this.transport.onAction(baseState, action);
}
return result;
};
/**
* Middleware that intercepts actions and invokes the subscription callback.
*/
const SubscriptionMiddleware = () => (next) => (action) => {
const result = next(action);
this.notifySubscribers();
return result;
};
const middleware = applyMiddleware(SubscriptionMiddleware, TransportMiddleware, LogMiddleware);
enhancer =
enhancer !== undefined ? compose(middleware, enhancer) : middleware;
this.store = createStore(this.reducer, this.initialState, enhancer);
if (!multiplayer)
multiplayer = DummyTransport;
this.transport = multiplayer({
gameKey: game,
game: this.game,
store: this.store,
matchID,
playerID,
credentials,
gameName: this.game.name,
numPlayers,
});
this.createDispatchers();
this.transport.subscribeMatchData((metadata) => {
this.matchData = metadata;
this.notifySubscribers();
});
this.chatMessages = [];
this.sendChatMessage = (payload) => {
this.transport.onChatMessage(this.matchID, {
id: nanoid(7),
sender: this.playerID,
payload: payload,
});
};
this.transport.subscribeChatMessage((message) => {
this.chatMessages = [...this.chatMessages, message];
this.notifySubscribers();
});
}
notifySubscribers() {
Object.values(this.subscribers).forEach((fn) => fn(this.getState()));
}
overrideGameState(state) {
this.gameStateOverride = state;
this.notifySubscribers();
}
start() {
this.transport.connect();
this._running = true;
this.manager.register(this);
}
stop() {
this.transport.disconnect();
this._running = false;
this.manager.unregister(this);
}
subscribe(fn) {
const id = Object.keys(this.subscribers).length;
this.subscribers[id] = fn;
this.transport.subscribe(() => this.notifySubscribers());
if (this._running || !this.multiplayer) {
fn(this.getState());
}
// Return a handle that allows the caller to unsubscribe.
return () => {
delete this.subscribers[id];
};
}
getInitialState() {
return this.initialState;
}
getState() {
let state = this.store.getState();
if (this.gameStateOverride !== null) {
state = this.gameStateOverride;
}
// This is the state before a sync with the game master.
if (state === null) {
return state;
}
// isActive.
let isActive = true;
const isPlayerActive = this.game.flow.isPlayerActive(state.G, state.ctx, this.playerID);
if (this.multiplayer && !isPlayerActive) {
isActive = false;
}
if (!this.multiplayer &&
this.playerID !== null &&
this.playerID !== undefined &&
!isPlayerActive) {
isActive = false;
}
if (state.ctx.gameover !== undefined) {
isActive = false;
}
// Secrets are normally stripped on the server,
// but we also strip them here so that game developers
// can see their effects while prototyping.
// Do not strip again if this is a multiplayer game
// since the server has already stripped secret info. (issue #818)
if (!this.multiplayer) {
state = {
...state,
G: this.game.playerView(state.G, state.ctx, this.playerID),
plugins: PlayerView(state, this),
};
}
// Combine into return value.
return {
...state,
log: this.log,
isActive,
isConnected: this.transport.isConnected,
};
}
createDispatchers() {
this.moves = createMoveDispatchers(this.game.moveNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.events = createEventDispatchers(this.game.flow.enabledEventNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.plugins = createPluginDispatchers(this.game.pluginNames, this.store, this.playerID, this.credentials, this.multiplayer);
}
updatePlayerID(playerID) {
this.playerID = playerID;
this.createDispatchers();
this.transport.updatePlayerID(playerID);
this.notifySubscribers();
}
updateMatchID(matchID) {
this.matchID = matchID;
this.createDispatchers();
this.transport.updateMatchID(matchID);
this.notifySubscribers();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.createDispatchers();
this.transport.updateCredentials(credentials);
this.notifySubscribers();
}
}
/**
* Client
*
* boardgame.io JS client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} matchID - The matchID that you want to connect to.
* @param {...object} playerID - The playerID associated with this client.
* @param {...string} credentials - The authentication credentials associated with this client.
*
* Returns:
* A JS object that provides an API to interact with the
* game by dispatching moves and events.
*/
function Client(opts) {
return new _ClientImpl(opts);
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Client
*
* boardgame.io React client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} debug - Enables the Debug UI.
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
* UNDO and REDO.
*/
function Client$1(opts) {
var _a;
let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts;
// Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting...");
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _a = class WrappedBoard extends React.Component {
constructor(props) {
super(props);
if (debug === undefined) {
debug = props.debug;
}
this.client = Client({
game,
debug,
numPlayers,
multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
enhancer,
});
}
componentDidMount() {
this.unsubscribe = this.client.subscribe(() => this.forceUpdate());
this.client.start();
}
componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
componentDidUpdate(prevProps) {
if (this.props.matchID != prevProps.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (this.props.playerID != prevProps.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (this.props.credentials != prevProps.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
render() {
const state = this.client.getState();
if (state === null) {
return React.createElement(loading);
}
let _board = null;
if (board) {
_board = React.createElement(board, {
...state,
...this.props,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
matchID: this.client.matchID,
playerID: this.client.playerID,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
log: this.client.log,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages,
});
}
return React.createElement("div", { className: "bgio-client" }, _board);
}
},
_a.propTypes = {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string,
// Enable / disable the Debug UI.
debug: PropTypes.any,
},
_a.defaultProps = {
matchID: 'default',
playerID: null,
credentials: null,
debug: true,
},
_a;
}
/**
* Client
*
* boardgame.io React Native client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React Native component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE.
*/
function Client$2(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer;
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
var _super = _createSuper(WrappedBoard);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _super.call(this, props);
_this.client = Client({
game: game,
numPlayers: numPlayers,
multiplayer: multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
debug: false,
enhancer: enhancer
});
return _this;
}
_createClass(WrappedBoard, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.client.subscribe(function () {
return _this2.forceUpdate();
});
this.client.start();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.matchID != this.props.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (prevProps.playerID != this.props.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (prevProps.credentials != this.props.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
}, {
key: "render",
value: function render() {
var _board = null;
var state = this.client.getState();
var _this$props = this.props,
matchID = _this$props.matchID,
playerID = _this$props.playerID,
rest = _objectWithoutProperties(_this$props, ["matchID", "playerID"]);
if (board) {
_board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, {
matchID: matchID,
playerID: playerID,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
step: this.client.step,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
var Type;
(function (Type) {
Type[Type["SYNC"] = 0] = "SYNC";
Type[Type["ASYNC"] = 1] = "ASYNC";
})(Type || (Type = {}));
/**
* Type guard that checks if a storage implementation is synchronous.
*/
function isSynchronous(storageAPI) {
return storageAPI.type() === Type.SYNC;
}
class Sync {
type() {
return Type.SYNC;
}
/**
* Connect.
*/
connect() {
return;
}
/**
* Create a new match.
*
* This might just need to call setState and setMetadata in
* most implementations.
*
* However, it exists as a separate call so that the
* implementation can provision things differently when
* a match is created. For example, it might stow away the
* initial match state in a separate field for easier retrieval.
*/
/* istanbul ignore next */
createMatch(matchID, opts) {
if (this.createGame) {
console.warn('The database connector does not implement a createMatch method.', '\nUsing the deprecated createGame method instead.');
return this.createGame(matchID, opts);
}
else {
console.error('The database connector does not implement a createMatch method.');
}
}
/**
* Return all matches.
*/
/* istanbul ignore next */
listMatches(opts) {
if (this.listGames) {
console.warn('The database connector does not implement a listMatches method.', '\nUsing the deprecated listGames method instead.');
return this.listGames(opts);
}
else {
console.error('The database connector does not implement a listMatches method.');
}
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* InMemory data storage.
*/
class InMemory extends Sync {
/**
* Creates a new InMemory storage.
*/
constructor() {
super();
this.state = new Map();
this.initial = new Map();
this.metadata = new Map();
this.log = new Map();
}
/**
* Create a new match.
*
* @override
*/
createMatch(matchID, opts) {
this.initial.set(matchID, opts.initialState);
this.setState(matchID, opts.initialState);
this.setMetadata(matchID, opts.metadata);
}
/**
* Write the match metadata to the in-memory object.
*/
setMetadata(matchID, metadata) {
this.metadata.set(matchID, metadata);
}
/**
* Write the match state to the in-memory object.
*/
setState(matchID, state, deltalog) {
if (deltalog && deltalog.length > 0) {
const log = this.log.get(matchID) || [];
this.log.set(matchID, log.concat(deltalog));
}
this.state.set(matchID, state);
}
/**
* Fetches state for a particular matchID.
*/
fetch(matchID, opts) {
const result = {};
if (opts.state) {
result.state = this.state.get(matchID);
}
if (opts.metadata) {
result.metadata = this.metadata.get(matchID);
}
if (opts.log) {
result.log = this.log.get(matchID) || [];
}
if (opts.initialState) {
result.initialState = this.initial.get(matchID);
}
return result;
}
/**
* Remove the match state from the in-memory object.
*/
wipe(matchID) {
this.state.delete(matchID);
this.metadata.delete(matchID);
}
/**
* Return all keys.
*
* @override
*/
listMatches(opts) {
return [...this.metadata.entries()]
.filter(([, metadata]) => {
if (!opts) {
return true;
}
if (opts.gameName !== undefined &&
metadata.gameName !== opts.gameName) {
return false;
}
if (opts.where !== undefined) {
if (opts.where.isGameover !== undefined) {
const isGameover = metadata.gameover !== undefined;
if (isGameover !== opts.where.isGameover) {
return false;
}
}
if (opts.where.updatedBefore !== undefined &&
metadata.updatedAt >= opts.where.updatedBefore) {
return false;
}
if (opts.where.updatedAfter !== undefined &&
metadata.updatedAt <= opts.where.updatedAfter) {
return false;
}
}
return true;
})
.map(([key]) => key);
}
}
class WithLocalStorageMap extends Map {
constructor(key) {
super();
this.key = key;
const cache = JSON.parse(localStorage.getItem(this.key)) || [];
cache.forEach((entry) => this.set(...entry));
}
sync() {
const entries = [...this.entries()];
localStorage.setItem(this.key, JSON.stringify(entries));
}
set(key, value) {
super.set(key, value);
this.sync();
return this;
}
delete(key) {
const result = super.delete(key);
this.sync();
return result;
}
}
/**
* locaStorage data storage.
*/
class LocalStorage extends InMemory {
constructor(storagePrefix = 'bgio') {
super();
const StorageMap = (stateKey) => new WithLocalStorageMap(`${storagePrefix}_${stateKey}`);
this.state = StorageMap('state');
this.initial = StorageMap('initial');
this.metadata = StorageMap('metadata');
this.log = StorageMap('log');
}
}
/**
* Creates a new match metadata object.
*/
const createMetadata = ({ game, unlisted, setupData, numPlayers, }) => {
const metadata = {
gameName: game.name,
unlisted: !!unlisted,
players: {},
createdAt: Date.now(),
updatedAt: Date.now(),
};
if (setupData !== undefined)
metadata.setupData = setupData;
for (let playerIndex = 0; playerIndex < numPlayers; playerIndex++) {
metadata.players[playerIndex] = { id: playerIndex };
}
return metadata;
};
/**
* Creates matchID, initial state and metadata for a new match.
* If the provided `setupData` doesn’t pass the game’s validation,
* an error object is returned instead.
*/
const createMatch = ({ game, numPlayers, setupData, unlisted, }) => {
if (!numPlayers || typeof numPlayers !== 'number')
numPlayers = 2;
const setupDataError = game.validateSetupData && game.validateSetupData(setupData, numPlayers);
if (setupDataError !== undefined)
return { setupDataError };
const metadata = createMetadata({ game, numPlayers, setupData, unlisted });
const initialState = InitializeGame({ game, numPlayers, setupData });
return { metadata, initialState };
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Filter match data to get a player metadata object with credentials stripped.
*/
const filterMatchData = (matchData) => Object.values(matchData.players).map((player) => {
const { credentials, ...filteredData } = player;
return filteredData;
});
/**
* Redact the log.
*
* @param {Array} log - The game log (or deltalog).
* @param {String} playerID - The playerID that this log is
* to be sent to.
*/
function redactLog(log, playerID) {
if (log === undefined) {
return log;
}
return log.map((logEvent) => {
// filter for all other players and spectators.
if (playerID !== null && +playerID === +logEvent.action.payload.playerID) {
return logEvent;
}
if (logEvent.redact !== true) {
return logEvent;
}
const payload = {
...logEvent.action.payload,
args: null,
};
const filteredEvent = {
...logEvent,
action: { ...logEvent.action, payload },
};
const { redact, ...remaining } = filteredEvent;
return remaining;
});
}
/**
* Remove player credentials from action payload
*/
const stripCredentialsFromAction = (action) => {
const { credentials, ...payload } = action.payload;
return { ...action, payload };
};
/**
* Master
*
* Class that runs the game and maintains the authoritative state.
* It uses the transportAPI to communicate with clients and the
* storageAPI to communicate with the database.
*/
class Master {
constructor(game, storageAPI, transportAPI, auth) {
this.game = ProcessGameConfig(game);
this.storageAPI = storageAPI;
this.transportAPI = transportAPI;
this.subscribeCallback = () => { };
this.auth = auth;
}
subscribe(fn) {
this.subscribeCallback = fn;
}
/**
* Called on each move / event made by the client.
* Computes the new value of the game state and returns it
* along with a deltalog.
*/
async onUpdate(credAction, stateID, matchID, playerID) {
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(matchID, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(matchID, { metadata: true }));
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials: credAction.payload.credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized action' };
}
}
const action = stripCredentialsFromAction(credAction);
const key = matchID;
let state;
if (isSynchronous(this.storageAPI)) {
({ state } = this.storageAPI.fetch(key, { state: true }));
}
else {
({ state } = await this.storageAPI.fetch(key, { state: true }));
}
if (state === undefined) {
error(`game not found, matchID=[${key}]`);
return { error: 'game not found' };
}
if (state.ctx.gameover !== undefined) {
error(`game over - matchID=[${key}] - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
const reducer = CreateGameReducer({
game: this.game,
});
const store = createStore(reducer, state);
// Only allow UNDO / REDO if there is exactly one player
// that can make moves right now and the person doing the
// action is that player.
if (action.type == UNDO || action.type == REDO) {
const hasActivePlayers = state.ctx.activePlayers !== null;
const isCurrentPlayer = state.ctx.currentPlayer === playerID;
if (
// If activePlayers is empty, non-current players can’t undo.
(!hasActivePlayers && !isCurrentPlayer) ||
// If player is not active or multiple players are active, can’t undo.
(hasActivePlayers &&
(state.ctx.activePlayers[playerID] === undefined ||
Object.keys(state.ctx.activePlayers).length > 1))) {
error(`playerID=[${playerID}] cannot undo / redo right now`);
return;
}
}
// Check whether the player is active.
if (!this.game.flow.isPlayerActive(state.G, state.ctx, playerID)) {
error(`player not active - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Get move for further checkings
const move = action.type == MAKE_MOVE
? this.game.flow.getMove(state.ctx, action.payload.type, playerID)
: null;
// Check whether the player is allowed to make the move.
if (action.type == MAKE_MOVE && !move) {
error(`move not processed - canPlayerMakeMove=false - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Check if action's stateID is different than store's stateID
// and if move does not have ignoreStaleStateID truthy.
if (state._stateID !== stateID &&
!(move && IsLongFormMove(move) && move.ignoreStaleStateID)) {
error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]` +
` - playerID=[${playerID}] - action[${action.payload.type}]`);
return;
}
// Update server's version of the store.
store.dispatch(action);
state = store.getState();
this.subscribeCallback({
state,
action,
matchID,
});
this.transportAPI.sendAll((playerID) => {
const filteredState = {
...state,
G: this.game.playerView(state.G, state.ctx, playerID),
plugins: PlayerView(state, { playerID, game: this.game }),
deltalog: undefined,
_undo: [],
_redo: [],
};
const log = redactLog(state.deltalog, playerID);
return {
type: 'update',
args: [matchID, filteredState, log],
};
});
const { deltalog, ...stateWithoutDeltalog } = state;
let newMetadata;
if (metadata && !('gameover' in metadata)) {
newMetadata = {
...metadata,
updatedAt: Date.now(),
};
if (state.ctx.gameover !== undefined) {
newMetadata.gameover = state.ctx.gameover;
}
}
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog);
if (newMetadata)
this.storageAPI.setMetadata(key, newMetadata);
}
else {
const writes = [
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog),
];
if (newMetadata) {
writes.push(this.storageAPI.setMetadata(key, newMetadata));
}
await Promise.all(writes);
}
}
/**
* Called when the client connects / reconnects.
* Returns the latest game state and the entire log.
*/
async onSync(matchID, playerID, credentials, numPlayers = 2) {
const key = matchID;
const fetchOpts = {
state: true,
metadata: true,
log: true,
initialState: true,
};
const fetchResult = isSynchronous(this.storageAPI)
? this.storageAPI.fetch(key, fetchOpts)
: await this.storageAPI.fetch(key, fetchOpts);
let { state, initialState, log, metadata } = fetchResult;
if (this.auth && playerID !== undefined && playerID !== null) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
// If the game doesn't exist, then create one on demand.
// TODO: Move this out of the sync call.
if (state === undefined) {
const match = createMatch({
game: this.game,
unlisted: true,
numPlayers,
setupData: undefined,
});
if ('setupDataError' in match) {
return { error: 'game requires setupData' };
}
initialState = state = match.initialState;
metadata = match.metadata;
this.subscribeCallback({ state, matchID });
if (isSynchronous(this.storageAPI)) {
this.storageAPI.createMatch(key, { initialState, metadata });
}
else {
await this.storageAPI.createMatch(key, { initialState, metadata });
}
}
const filteredMetadata = metadata ? filterMatchData(metadata) : undefined;
const filteredState = {
...state,
G: this.game.playerView(state.G, state.ctx, playerID),
plugins: PlayerView(state, { playerID, game: this.game }),
deltalog: undefined,
_undo: [],
_redo: [],
};
log = redactLog(log, playerID);
const syncInfo = {
state: filteredState,
log,
filteredMetadata,
initialState,
};
this.transportAPI.send({
playerID,
type: 'sync',
args: [matchID, syncInfo],
});
return;
}
/**
* Called when a client connects or disconnects.
* Updates and sends out metadata to reflect the player’s connection status.
*/
async onConnectionChange(matchID, playerID, credentials, connected) {
const key = matchID;
// Ignore changes for clients without a playerID, e.g. spectators.
if (playerID === undefined || playerID === null) {
return;
}
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(key, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(key, { metadata: true }));
}
if (metadata === undefined) {
error(`metadata not found for matchID=[${key}]`);
return { error: 'metadata not found' };
}
if (metadata.players[playerID] === undefined) {
error(`Player not in the match, matchID=[${key}] playerID=[${playerID}]`);
return { error: 'player not in the match' };
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
metadata.players[playerID].isConnected = connected;
const filteredMetadata = filterMatchData(metadata);
this.transportAPI.sendAll(() => ({
type: 'matchData',
args: [matchID, filteredMetadata],
}));
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setMetadata(key, metadata);
}
else {
await this.storageAPI.setMetadata(key, metadata);
}
}
async onChatMessage(matchID, chatMessage, credentials) {
const key = matchID;
if (this.auth) {
const { metadata } = await this.storageAPI.fetch(key, {
metadata: true,
});
const isAuthentic = await this.auth.authenticateCredentials({
playerID: chatMessage.sender,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
this.transportAPI.sendAll(() => ({
type: 'chat',
args: [matchID, chatMessage],
}));
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Returns null if it is not a bot's turn.
* Otherwise, returns a playerID of a bot that may play now.
*/
function GetBotPlayer(state, bots) {
if (state.ctx.gameover !== undefined) {
return null;
}
if (state.ctx.activePlayers) {
for (const key of Object.keys(bots)) {
if (key in state.ctx.activePlayers) {
return key;
}
}
}
else if (state.ctx.currentPlayer in bots) {
return state.ctx.currentPlayer;
}
return null;
}
/**
* Creates a local version of the master that the client
* can interact with.
*/
class LocalMaster extends Master {
constructor({ game, bots, storageKey, persist }) {
const clientCallbacks = {};
const initializedBots = {};
if (game && game.ai && bots) {
for (const playerID in bots) {
const bot = bots[playerID];
initializedBots[playerID] = new bot({
game,
enumerate: game.ai.enumerate,
seed: game.seed,
});
}
}
const send = ({ playerID, ...data }) => {
const callback = clientCallbacks[playerID];
if (callback !== undefined) {
callback(data);
}
};
const transportAPI = {
send,
sendAll: (makePlayerData) => {
for (const playerID in clientCallbacks) {
const data = makePlayerData(playerID);
send({ playerID, ...data });
}
},
};
const storage = persist ? new LocalStorage(storageKey) : new InMemory();
super(game, storage, transportAPI);
this.connect = (matchID, playerID, callback) => {
clientCallbacks[playerID] = callback;
};
this.subscribe(({ state, matchID }) => {
if (!bots) {
return;
}
const botPlayer = GetBotPlayer(state, initializedBots);
if (botPlayer !== null) {
setTimeout(async () => {
const botAction = await initializedBots[botPlayer].play(state, botPlayer);
await this.onUpdate(botAction.action, state._stateID, matchID, botAction.action.payload.playerID);
}, 100);
}
});
}
}
/**
* Local
*
* Transport interface that embeds a GameMaster within it
* that you can connect multiple clients to.
*/
class LocalTransport extends Transport {
/**
* Creates a new Mutiplayer instance.
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
*/
constructor({ master, ...opts }) {
super(opts);
this.master = master;
this.isConnected = true;
}
/**
* Called when any player sends a chat message and the
* master broadcasts the update to other clients (including
* this one).
*/
onChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.master.onChatMessage(...args);
}
/**
* Called when another player makes a move and the
* master broadcasts the update to other clients (including
* this one).
*/
async onUpdate(matchID, state, deltalog) {
const currentState = this.store.getState();
if (matchID == this.matchID && state._stateID >= currentState._stateID) {
const action = update$1(state, deltalog);
this.store.dispatch(action);
}
}
/**
* Called when the client first connects to the master
* and requests the current game state.
*/
onSync(matchID, syncInfo) {
if (matchID == this.matchID) {
const action = sync(syncInfo);
this.store.dispatch(action);
}
}
/**
* Called when an action that has to be relayed to the
* game master is made.
*/
onAction(state, action) {
this.master.onUpdate(action, state._stateID, this.matchID, this.playerID);
}
/**
* Connect to the master.
*/
connect() {
this.master.connect(this.matchID, this.playerID, (data) => {
switch (data.type) {
case 'sync':
return this.onSync(...data.args);
case 'update':
return this.onUpdate(...data.args);
case 'chat':
return this.chatMessageCallback(data.args[1]);
}
});
this.master.onSync(this.matchID, this.playerID, this.credentials, this.numPlayers);
}
/**
* Disconnect from the master.
*/
disconnect() { }
/**
* Subscribe to connection state changes.
*/
subscribe() { }
subscribeMatchData() { }
subscribeChatMessage(fn) {
this.chatMessageCallback = fn;
}
/**
* Dispatches a reset action, then requests a fresh sync from the master.
*/
resetAndSync() {
const action = reset(null);
this.store.dispatch(action);
this.connect();
}
/**
* Updates the game id.
* @param {string} id - The new game id.
*/
updateMatchID(id) {
this.matchID = id;
this.resetAndSync();
}
/**
* Updates the player associated with this client.
* @param {string} id - The new player id.
*/
updatePlayerID(id) {
this.playerID = id;
this.resetAndSync();
}
/**
* Updates the credentials associated with this client.
* @param {string|undefined} credentials - The new credentials to use.
*/
updateCredentials(credentials) {
this.credentials = credentials;
this.resetAndSync();
}
}
/**
* Global map storing local master instances.
*/
const localMasters = new Map();
/**
* Create a local transport.
*/
function Local({ bots, persist, storageKey } = {}) {
return (transportOpts) => {
const { gameKey, game } = transportOpts;
let master;
const instance = localMasters.get(gameKey);
if (instance &&
instance.bots === bots &&
instance.storageKey === storageKey &&
instance.persist === persist) {
master = instance.master;
}
if (!master) {
master = new LocalMaster({ game, bots, persist, storageKey });
localMasters.set(gameKey, { master, bots, persist, storageKey });
}
return new LocalTransport({ master, ...transportOpts });
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const io = ioNamespace__default;
/**
* SocketIO
*
* Transport interface that interacts with the Master via socket.io.
*/
class SocketIOTransport extends Transport {
/**
* Creates a new Mutiplayer instance.
* @param {object} socket - Override for unit tests.
* @param {object} socketOpts - Options to pass to socket.io.
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
* @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided.
*/
constructor({ socket, socketOpts, server, ...opts } = {}) {
super(opts);
this.server = server;
this.socket = socket;
this.socketOpts = socketOpts;
this.isConnected = false;
this.callback = () => { };
this.matchDataCallback = () => { };
this.chatMessageCallback = () => { };
}
/**
* Called when an action that has to be relayed to the
* game master is made.
*/
onAction(state, action) {
const args = [
action,
state._stateID,
this.matchID,
this.playerID,
];
this.socket.emit('update', ...args);
}
onChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.socket.emit('chat', ...args);
}
/**
* Connect to the server.
*/
connect() {
if (!this.socket) {
if (this.server) {
let server = this.server;
if (server.search(/^https?:\/\//) == -1) {
server = 'http://' + this.server;
}
if (server.slice(-1) != '/') {
// add trailing slash if not already present
server = server + '/';
}
this.socket = io(server + this.gameName, this.socketOpts);
}
else {
this.socket = io('/' + this.gameName, this.socketOpts);
}
}
// Called when another player makes a move and the
// master broadcasts the update to other clients (including
// this one).
this.socket.on('update', (matchID, state, deltalog) => {
const currentState = this.store.getState();
if (matchID == this.matchID &&
state._stateID >= currentState._stateID) {
const action = update$1(state, deltalog);
this.store.dispatch(action);
}
});
// Called when the client first connects to the master
// and requests the current game state.
this.socket.on('sync', (matchID, syncInfo) => {
if (matchID == this.matchID) {
const action = sync(syncInfo);
this.matchDataCallback(syncInfo.filteredMetadata);
this.store.dispatch(action);
}
});
// Called when new player joins the match or changes
// it's connection status
this.socket.on('matchData', (matchID, matchData) => {
if (matchID == this.matchID) {
this.matchDataCallback(matchData);
}
});
this.socket.on('chat', (matchID, chatMessage) => {
if (matchID === this.matchID) {
this.chatMessageCallback(chatMessage);
}
});
// Keep track of connection status.
this.socket.on('connect', () => {
// Initial sync to get game state.
this.sync();
this.isConnected = true;
this.callback();
});
this.socket.on('disconnect', () => {
this.isConnected = false;
this.callback();
});
}
/**
* Disconnect from the server.
*/
disconnect() {
this.socket.close();
this.socket = null;
this.isConnected = false;
this.callback();
}
/**
* Subscribe to connection state changes.
*/
subscribe(fn) {
this.callback = fn;
}
subscribeMatchData(fn) {
this.matchDataCallback = fn;
}
subscribeChatMessage(fn) {
this.chatMessageCallback = fn;
}
/**
* Send a “sync” event to the server.
*/
sync() {
if (this.socket) {
const args = [
this.matchID,
this.playerID,
this.credentials,
this.numPlayers,
];
this.socket.emit('sync', ...args);
}
}
/**
* Dispatches a reset action, then requests a fresh sync from the server.
*/
resetAndSync() {
const action = reset(null);
this.store.dispatch(action);
this.sync();
}
/**
* Updates the game id.
* @param {string} id - The new game id.
*/
updateMatchID(id) {
this.matchID = id;
this.resetAndSync();
}
/**
* Updates the player associated with this client.
* @param {string} id - The new player id.
*/
updatePlayerID(id) {
this.playerID = id;
this.resetAndSync();
}
/**
* Updates the credentials associated with this client.
* @param {string|undefined} credentials - The new credentials to use.
*/
updateCredentials(credentials) {
this.credentials = credentials;
this.resetAndSync();
}
}
function SocketIO({ server, socketOpts } = {}) {
return (transportOpts) => new SocketIOTransport({
server,
socketOpts,
...transportOpts,
});
}
export { Client, Local, MCTSBot, RandomBot, Client$1 as ReactClient, Client$2 as ReactNativeClient, Simulate, SocketIO, Step, TurnOrder };
|
ajax/libs/material-ui/5.0.0-alpha.6/es/utils/createSvgIcon.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import SvgIcon from '../SvgIcon';
/**
* Private module reserved for @material-ui/x packages.
*/
export default function createSvgIcon(path, displayName) {
const Component = (props, ref) => /*#__PURE__*/React.createElement(SvgIcon, _extends({
ref: ref
}, props), path);
if (process.env.NODE_ENV !== 'production') {
// Need to set `displayName` on the inner component for React.memo.
// React prior to 16.14 ignores `displayName` on the wrapper.
Component.displayName = `${displayName}Icon`;
}
Component.muiName = SvgIcon.muiName;
return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));
} |
ajax/libs/react-native-web/0.0.0-834df0271/exports/KeyboardAvoidingView/index.js | cdnjs/cdnjs | function _extends() { _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; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Copyright (c) Nicolas Gallagher.
* 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.
*
*
*/
import View from '../View';
import React from 'react';
var KeyboardAvoidingView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(KeyboardAvoidingView, _React$Component);
function KeyboardAvoidingView() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.frame = null;
_this.onLayout = function (event) {
_this.frame = event.nativeEvent.layout;
};
return _this;
}
var _proto = KeyboardAvoidingView.prototype;
_proto.relativeKeyboardHeight = function relativeKeyboardHeight(keyboardFrame) {
var frame = this.frame;
if (!frame || !keyboardFrame) {
return 0;
}
var keyboardY = keyboardFrame.screenY - (this.props.keyboardVerticalOffset || 0);
return Math.max(frame.y + frame.height - keyboardY, 0);
};
_proto.onKeyboardChange = function onKeyboardChange(event) {};
_proto.render = function render() {
var _this$props = this.props,
behavior = _this$props.behavior,
contentContainerStyle = _this$props.contentContainerStyle,
keyboardVerticalOffset = _this$props.keyboardVerticalOffset,
rest = _objectWithoutPropertiesLoose(_this$props, ["behavior", "contentContainerStyle", "keyboardVerticalOffset"]);
return React.createElement(View, _extends({
onLayout: this.onLayout
}, rest));
};
return KeyboardAvoidingView;
}(React.Component);
export default KeyboardAvoidingView; |
ajax/libs/material-ui/4.9.3/es/RootRef/RootRef.js | cdnjs/cdnjs | import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { exactProp, refType } from '@material-ui/utils';
import setRef from '../utils/setRef';
/**
* ⚠️⚠️⚠️
* If you want the DOM element of a Material-UI component check out
* [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element)
* first.
*
* This component uses `findDOMNode` which is deprecated in React.StrictMode.
*
* Helper component to allow attaching a ref to a
* wrapped element to access the underlying DOM element.
*
* It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801.
* For example:
* ```jsx
* import React from 'react';
* import RootRef from '@material-ui/core/RootRef';
*
* function MyComponent() {
* const domRef = React.useRef();
*
* React.useEffect(() => {
* console.log(domRef.current); // DOM node
* }, []);
*
* return (
* <RootRef rootRef={domRef}>
* <SomeChildComponent />
* </RootRef>
* );
* }
* ```
*/
class RootRef extends React.Component {
componentDidMount() {
this.ref = ReactDOM.findDOMNode(this);
setRef(this.props.rootRef, this.ref);
}
componentDidUpdate(prevProps) {
const ref = ReactDOM.findDOMNode(this);
if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) {
if (prevProps.rootRef !== this.props.rootRef) {
setRef(prevProps.rootRef, null);
}
this.ref = ref;
setRef(this.props.rootRef, this.ref);
}
}
componentWillUnmount() {
this.ref = null;
setRef(this.props.rootRef, null);
}
render() {
return this.props.children;
}
}
process.env.NODE_ENV !== "production" ? RootRef.propTypes = {
/**
* The wrapped element.
*/
children: PropTypes.element.isRequired,
/**
* A ref that points to the first DOM node of the wrapped element.
*/
rootRef: refType.isRequired
} : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? RootRef.propTypes = exactProp(RootRef.propTypes) : void 0;
}
export default RootRef; |
ajax/libs/primereact/6.5.0/tabview/tabview.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, UniqueComponentId, classNames, ObjectUtils, Ripple } from 'primereact/core';
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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var TabPanel = /*#__PURE__*/function (_Component) {
_inherits(TabPanel, _Component);
var _super = _createSuper(TabPanel);
function TabPanel() {
_classCallCheck(this, TabPanel);
return _super.apply(this, arguments);
}
return TabPanel;
}(Component);
_defineProperty(TabPanel, "defaultProps", {
header: null,
headerTemplate: null,
leftIcon: null,
rightIcon: null,
disabled: false,
headerStyle: null,
headerClassName: null,
contentStyle: null,
contentClassName: null
});
var TabView = /*#__PURE__*/function (_Component2) {
_inherits(TabView, _Component2);
var _super2 = _createSuper(TabView);
function TabView(props) {
var _this;
_classCallCheck(this, TabView);
_this = _super2.call(this, props);
var state = {
id: props.id
};
if (!_this.props.onTabChange) {
state = _objectSpread(_objectSpread({}, state), {}, {
activeIndex: props.activeIndex
});
}
_this.state = state;
return _this;
}
_createClass(TabView, [{
key: "getActiveIndex",
value: function getActiveIndex() {
return this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex;
}
}, {
key: "isSelected",
value: function isSelected(index) {
return index === this.getActiveIndex();
}
}, {
key: "onTabHeaderClick",
value: function onTabHeaderClick(event, tab, index) {
if (!tab.props.disabled) {
if (this.props.onTabChange) {
this.props.onTabChange({
originalEvent: event,
index: index
});
} else {
this.setState({
activeIndex: index
});
}
}
event.preventDefault();
}
}, {
key: "updateInkBar",
value: function updateInkBar() {
var activeIndex = this.getActiveIndex();
var tabHeader = this["tab_".concat(activeIndex)];
this.inkbar.style.width = DomHandler.getWidth(tabHeader) + 'px';
this.inkbar.style.left = DomHandler.getOffset(tabHeader).left - DomHandler.getOffset(this.nav).left + 'px';
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (!this.state.id) {
this.setState({
id: UniqueComponentId()
});
}
this.updateInkBar();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
this.updateInkBar();
}
}, {
key: "renderTabHeader",
value: function renderTabHeader(tab, index) {
var _this2 = this;
var selected = this.isSelected(index);
var className = classNames('p-unselectable-text', {
'p-tabview-selected p-highlight': selected,
'p-disabled': tab.props.disabled
}, tab.props.headerClassName);
var id = this.state.id + '_header_' + index;
var ariaControls = this.state.id + '_content_' + index;
var tabIndex = tab.props.disabled ? null : 0;
var leftIconElement = tab.props.leftIcon && /*#__PURE__*/React.createElement("i", {
className: tab.props.leftIcon
});
var titleElement = /*#__PURE__*/React.createElement("span", {
className: "p-tabview-title"
}, tab.props.header);
var rightIconElement = tab.props.rightIcon && /*#__PURE__*/React.createElement("i", {
className: tab.props.rightIcon
});
var content =
/*#__PURE__*/
/* eslint-disable */
React.createElement("a", {
role: "tab",
className: "p-tabview-nav-link",
onClick: function onClick(event) {
return _this2.onTabHeaderClick(event, tab, index);
},
id: id,
"aria-controls": ariaControls,
"aria-selected": selected,
tabIndex: tabIndex
}, leftIconElement, titleElement, rightIconElement, /*#__PURE__*/React.createElement(Ripple, null))
/* eslint-enable */
;
if (tab.props.headerTemplate) {
var defaultContentOptions = {
className: 'p-tabview-nav-link',
titleClassName: 'p-tabview-title',
onClick: function onClick(event) {
return _this2.onTabHeaderClick(event, tab, index);
},
leftIconElement: leftIconElement,
titleElement: titleElement,
rightIconElement: rightIconElement,
element: content,
props: this.props,
index: index,
selected: selected,
ariaControls: ariaControls
};
content = ObjectUtils.getJSXElement(tab.props.headerTemplate, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
ref: function ref(el) {
return _this2["tab_".concat(index)] = el;
},
className: className,
style: tab.props.headerStyle,
role: "presentation"
}, content);
}
}, {
key: "renderTabHeaders",
value: function renderTabHeaders() {
var _this3 = this;
return React.Children.map(this.props.children, function (tab, index) {
return _this3.renderTabHeader(tab, index);
});
}
}, {
key: "renderNavigator",
value: function renderNavigator() {
var _this4 = this;
var headers = this.renderTabHeaders();
return /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this4.nav = el;
},
className: "p-tabview-nav",
role: "tablist"
}, headers, /*#__PURE__*/React.createElement("li", {
ref: function ref(el) {
return _this4.inkbar = el;
},
className: "p-tabview-ink-bar"
}));
}
}, {
key: "renderContent",
value: function renderContent() {
var _this5 = this;
var contents = React.Children.map(this.props.children, function (tab, index) {
if (!_this5.props.renderActiveOnly || _this5.isSelected(index)) {
return _this5.createContent(tab, index);
}
});
return /*#__PURE__*/React.createElement("div", {
className: "p-tabview-panels"
}, contents);
}
}, {
key: "createContent",
value: function createContent(tab, index) {
var selected = this.isSelected(index);
var className = classNames(tab.props.contentClassName, 'p-tabview-panel', {
'p-hidden': !selected
});
var id = this.state.id + '_content_' + index;
var ariaLabelledBy = this.state.id + '_header_' + index;
return /*#__PURE__*/React.createElement("div", {
id: id,
"aria-labelledby": ariaLabelledBy,
"aria-hidden": !selected,
className: className,
style: tab.props.contentStyle,
role: "tabpanel"
}, !this.props.renderActiveOnly ? tab.props.children : selected && tab.props.children);
}
}, {
key: "render",
value: function render() {
var className = classNames('p-tabview p-component', this.props.className);
var navigator = this.renderNavigator();
var content = this.renderContent();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: className,
style: this.props.style
}, navigator, content);
}
}]);
return TabView;
}(Component);
_defineProperty(TabView, "defaultProps", {
id: null,
activeIndex: 0,
style: null,
className: null,
renderActiveOnly: true,
onTabChange: null
});
export { TabPanel, TabView };
|
ajax/libs/material-ui/4.9.8/es/styles/useTheme.js | cdnjs/cdnjs | import { useTheme as useThemeWithoutDefault } from '@material-ui/styles';
import React from 'react';
import defaultTheme from './defaultTheme';
export default function useTheme() {
const theme = useThemeWithoutDefault() || defaultTheme;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useDebugValue(theme);
}
return theme;
} |
ajax/libs/material-ui/4.9.2/es/DialogContentText/DialogContentText.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from '../styles/withStyles';
import Typography from '../Typography';
export const styles = {
/* Styles applied to the root element. */
root: {
marginBottom: 12
}
};
const DialogContentText = React.forwardRef(function DialogContentText(props, ref) {
return React.createElement(Typography, _extends({
component: "p",
variant: "body1",
color: "textSecondary",
ref: ref
}, props));
});
process.env.NODE_ENV !== "production" ? DialogContentText.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired
} : void 0;
export default withStyles(styles, {
name: 'MuiDialogContentText'
})(DialogContentText); |
ajax/libs/material-ui/4.9.3/es/MobileStepper/MobileStepper.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import Paper from '../Paper';
import capitalize from '../utils/capitalize';
import LinearProgress from '../LinearProgress';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
background: theme.palette.background.default,
padding: 8
},
/* Styles applied to the root element if `position="bottom"`. */
positionBottom: {
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
zIndex: theme.zIndex.mobileStepper
},
/* Styles applied to the root element if `position="top"`. */
positionTop: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
zIndex: theme.zIndex.mobileStepper
},
/* Styles applied to the root element if `position="static"`. */
positionStatic: {},
/* Styles applied to the dots container if `variant="dots"`. */
dots: {
display: 'flex',
flexDirection: 'row'
},
/* Styles applied to each dot if `variant="dots"`. */
dot: {
backgroundColor: theme.palette.action.disabled,
borderRadius: '50%',
width: 8,
height: 8,
margin: '0 2px'
},
/* Styles applied to a dot if `variant="dots"` and this is the active step. */
dotActive: {
backgroundColor: theme.palette.primary.main
},
/* Styles applied to the Linear Progress component if `variant="progress"`. */
progress: {
width: '50%'
}
});
const MobileStepper = React.forwardRef(function MobileStepper(props, ref) {
const {
activeStep = 0,
backButton,
classes,
className,
LinearProgressProps,
nextButton,
position = 'bottom',
steps,
variant = 'dots'
} = props,
other = _objectWithoutPropertiesLoose(props, ["activeStep", "backButton", "classes", "className", "LinearProgressProps", "nextButton", "position", "steps", "variant"]);
return React.createElement(Paper, _extends({
square: true,
elevation: 0,
className: clsx(classes.root, classes[`position${capitalize(position)}`], className),
ref: ref
}, other), backButton, variant === 'text' && React.createElement(React.Fragment, null, activeStep + 1, " / ", steps), variant === 'dots' && React.createElement("div", {
className: classes.dots
}, [...new Array(steps)].map((_, index) => React.createElement("div", {
key: index,
className: clsx(classes.dot, index === activeStep && classes.dotActive)
}))), variant === 'progress' && React.createElement(LinearProgress, _extends({
className: classes.progress,
variant: "determinate",
value: Math.ceil(activeStep / (steps - 1) * 100)
}, LinearProgressProps)), nextButton);
});
process.env.NODE_ENV !== "production" ? MobileStepper.propTypes = {
/**
* Set the active step (zero based index).
* Defines which dot is highlighted when the variant is 'dots'.
*/
activeStep: PropTypes.number,
/**
* A back button element. For instance, it can be a `Button` or an `IconButton`.
*/
backButton: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Props applied to the `LinearProgress` element.
*/
LinearProgressProps: PropTypes.object,
/**
* A next button element. For instance, it can be a `Button` or an `IconButton`.
*/
nextButton: PropTypes.node,
/**
* Set the positioning type.
*/
position: PropTypes.oneOf(['bottom', 'top', 'static']),
/**
* The total steps.
*/
steps: PropTypes.number.isRequired,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['text', 'dots', 'progress'])
} : void 0;
export default withStyles(styles, {
name: 'MuiMobileStepper'
})(MobileStepper); |
ajax/libs/primereact/6.5.0-rc.1/orderlist/orderlist.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { Button } from 'primereact/button';
import { ObjectUtils, DomHandler, classNames } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 propTypes = {exports: {}};
/**
* 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$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
/**
* 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 = ReactPropTypesSecret_1;
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'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'
);
err.name = 'Invariant Violation';
throw err;
} 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,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/**
* 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
propTypes.exports = factoryWithThrowingShims();
}
var PropTypes = propTypes.exports;
function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderListControls = /*#__PURE__*/function (_Component) {
_inherits(OrderListControls, _Component);
var _super = _createSuper$2(OrderListControls);
function OrderListControls() {
var _this;
_classCallCheck(this, OrderListControls);
_this = _super.call(this);
_this.moveUp = _this.moveUp.bind(_assertThisInitialized(_this));
_this.moveTop = _this.moveTop.bind(_assertThisInitialized(_this));
_this.moveDown = _this.moveDown.bind(_assertThisInitialized(_this));
_this.moveBottom = _this.moveBottom.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderListControls, [{
key: "moveUp",
value: function moveUp(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = 0; i < this.props.selection.length; i++) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value);
if (selectedItemIndex !== 0) {
var movedItem = value[selectedItemIndex];
var temp = value[selectedItemIndex - 1];
value[selectedItemIndex - 1] = movedItem;
value[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'up'
});
}
}
}
}, {
key: "moveTop",
value: function moveTop(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = 0; i < this.props.selection.length; i++) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value);
if (selectedItemIndex !== 0) {
var movedItem = value.splice(selectedItemIndex, 1)[0];
value.unshift(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'top'
});
}
}
}
}, {
key: "moveDown",
value: function moveDown(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = this.props.selection.length - 1; i >= 0; i--) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value);
if (selectedItemIndex !== value.length - 1) {
var movedItem = value[selectedItemIndex];
var temp = value[selectedItemIndex + 1];
value[selectedItemIndex + 1] = movedItem;
value[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'down'
});
}
}
}
}, {
key: "moveBottom",
value: function moveBottom(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = this.props.selection.length - 1; i >= 0; i--) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value);
if (selectedItemIndex !== value.length - 1) {
var movedItem = value.splice(selectedItemIndex, 1)[0];
value.push(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'bottom'
});
}
}
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-controls"
}, /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-up",
onClick: this.moveUp
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-double-up",
onClick: this.moveTop
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-down",
onClick: this.moveDown
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-double-down",
onClick: this.moveBottom
}));
}
}]);
return OrderListControls;
}(Component);
_defineProperty(OrderListControls, "defaultProps", {
value: null,
selection: null,
onReorder: null
});
_defineProperty(OrderListControls, "propTypes", {
value: PropTypes.array,
selection: PropTypes.array,
onReorder: PropTypes.func
});
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderListSubList = /*#__PURE__*/function (_Component) {
_inherits(OrderListSubList, _Component);
var _super = _createSuper$1(OrderListSubList);
function OrderListSubList(props) {
var _this;
_classCallCheck(this, OrderListSubList);
_this = _super.call(this, props);
_this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this));
_this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this));
_this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this));
_this.onListMouseMove = _this.onListMouseMove.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderListSubList, [{
key: "isSelected",
value: function isSelected(item) {
return ObjectUtils.findIndexInList(item, this.props.selection) !== -1;
}
}, {
key: "onDragStart",
value: function onDragStart(event, index) {
this.dragging = true;
this.draggedItemIndex = index;
if (this.props.dragdropScope) {
event.dataTransfer.setData('text', 'orderlist');
}
}
}, {
key: "onDragOver",
value: function onDragOver(event, index) {
if (this.draggedItemIndex !== index && this.draggedItemIndex + 1 !== index) {
this.dragOverItemIndex = index;
DomHandler.addClass(event.target, 'p-orderlist-droppoint-highlight');
event.preventDefault();
}
}
}, {
key: "onDragLeave",
value: function onDragLeave(event) {
this.dragOverItemIndex = null;
DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight');
}
}, {
key: "onDrop",
value: function onDrop(event) {
var dropIndex = this.draggedItemIndex > this.dragOverItemIndex ? this.dragOverItemIndex : this.dragOverItemIndex === 0 ? 0 : this.dragOverItemIndex - 1;
var value = _toConsumableArray(this.props.value);
ObjectUtils.reorderArray(value, this.draggedItemIndex, dropIndex);
this.dragOverItemIndex = null;
DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight');
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: value
});
}
}
}, {
key: "onDragEnd",
value: function onDragEnd(event) {
this.dragging = false;
}
}, {
key: "onListMouseMove",
value: function onListMouseMove(event) {
if (this.dragging) {
var offsetY = this.listElement.getBoundingClientRect().top + DomHandler.getWindowScrollTop();
var bottomDiff = offsetY + this.listElement.clientHeight - event.pageY;
var topDiff = event.pageY - offsetY;
if (bottomDiff < 25 && bottomDiff > 0) this.listElement.scrollTop += 15;else if (topDiff < 25 && topDiff > 0) this.listElement.scrollTop -= 15;
}
}
}, {
key: "renderDropPoint",
value: function renderDropPoint(index, key) {
var _this2 = this;
return /*#__PURE__*/React.createElement("li", {
key: key,
className: "p-orderlist-droppoint",
onDragOver: function onDragOver(e) {
return _this2.onDragOver(e, index + 1);
},
onDragLeave: this.onDragLeave,
onDrop: this.onDrop
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var header = null;
var items = null;
if (this.props.header) {
header = /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-header"
}, this.props.header);
}
if (this.props.value) {
items = this.props.value.map(function (item, i) {
var content = _this3.props.itemTemplate ? _this3.props.itemTemplate(item) : item;
var itemClassName = classNames('p-orderlist-item', {
'p-highlight': _this3.isSelected(item)
}, _this3.props.className);
var key = JSON.stringify(item);
if (_this3.props.dragdrop) {
var _items = [_this3.renderDropPoint(i, key + '_droppoint'), /*#__PURE__*/React.createElement("li", {
key: key,
className: itemClassName,
onClick: function onClick(e) {
return _this3.props.onItemClick({
originalEvent: e,
value: item,
index: i
});
},
onKeyDown: function onKeyDown(e) {
return _this3.props.onItemKeyDown({
originalEvent: e,
value: item,
index: i
});
},
role: "option",
"aria-selected": _this3.isSelected(item),
draggable: "true",
onDragStart: function onDragStart(e) {
return _this3.onDragStart(e, i);
},
onDragEnd: _this3.onDragEnd,
tabIndex: _this3.props.tabIndex
}, content, /*#__PURE__*/React.createElement(Ripple, null))];
if (i === _this3.props.value.length - 1) {
_items.push(_this3.renderDropPoint(item, i, key + '_droppoint_end'));
}
return _items;
} else {
return /*#__PURE__*/React.createElement("li", {
key: JSON.stringify(item),
className: itemClassName,
role: "option",
"aria-selected": _this3.isSelected(item),
onClick: function onClick(e) {
return _this3.props.onItemClick({
originalEvent: e,
value: item,
index: i
});
},
onKeyDown: function onKeyDown(e) {
return _this3.props.onItemKeyDown({
originalEvent: e,
value: item,
index: i
});
},
tabIndex: _this3.props.tabIndex
}, content);
}
});
}
return /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-list-container"
}, header, /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this3.listElement = el;
},
className: "p-orderlist-list",
style: this.props.listStyle,
onDragOver: this.onListMouseMove,
role: "listbox",
"aria-multiselectable": true
}, items));
}
}]);
return OrderListSubList;
}(Component);
_defineProperty(OrderListSubList, "defaultProps", {
value: null,
selection: null,
header: null,
listStyle: null,
itemTemplate: null,
dragdrop: false,
tabIndex: null,
onItemClick: null,
onItemKeyDown: null,
onChange: null
});
_defineProperty(OrderListSubList, "propTypes", {
value: PropTypes.array,
selection: PropTypes.array,
header: PropTypes.string,
listStyle: PropTypes.object,
itemTemplate: PropTypes.func,
dragdrop: PropTypes.bool,
tabIndex: PropTypes.number,
onItemClick: PropTypes.func,
onItemKeyDown: PropTypes.func,
onChange: PropTypes.func
});
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderList = /*#__PURE__*/function (_Component) {
_inherits(OrderList, _Component);
var _super = _createSuper(OrderList);
function OrderList(props) {
var _this;
_classCallCheck(this, OrderList);
_this = _super.call(this, props);
_this.state = {
selection: []
};
_this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this));
_this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this));
_this.onReorder = _this.onReorder.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderList, [{
key: "onItemClick",
value: function onItemClick(event) {
var metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey;
var index = ObjectUtils.findIndexInList(event.value, this.state.selection);
var selected = index !== -1;
var selection;
if (selected) {
if (metaKey) selection = this.state.selection.filter(function (val, i) {
return i !== index;
});else selection = [event.value];
} else {
if (metaKey) selection = [].concat(_toConsumableArray(this.state.selection), [event.value]);else selection = [event.value];
}
this.setState({
selection: selection
});
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event) {
var listItem = event.originalEvent.currentTarget;
switch (event.originalEvent.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.focus();
}
event.originalEvent.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.focus();
}
event.originalEvent.preventDefault();
break;
//enter
case 13:
this.onItemClick(event);
event.originalEvent.preventDefault();
break;
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return !DomHandler.hasClass(nextItem, 'p-orderlist-item') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return !DomHandler.hasClass(prevItem, 'p-orderlist-item') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "onReorder",
value: function onReorder(event) {
if (this.props.onChange) {
this.props.onChange({
event: event.originalEvent,
value: event.value
});
}
this.reorderDirection = event.direction;
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this.reorderDirection) {
this.updateListScroll();
this.reorderDirection = null;
}
}
}, {
key: "updateListScroll",
value: function updateListScroll() {
var listItems = DomHandler.find(this.subList.listElement, '.p-orderlist-item.p-highlight');
if (listItems && listItems.length) {
switch (this.reorderDirection) {
case 'up':
DomHandler.scrollInView(this.subList.listElement, listItems[0]);
break;
case 'top':
this.subList.listElement.scrollTop = 0;
break;
case 'down':
DomHandler.scrollInView(this.subList.listElement, listItems[listItems.length - 1]);
break;
case 'bottom':
this.subList.listElement.scrollTop = this.subList.listElement.scrollHeight;
break;
}
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var className = classNames('p-orderlist p-component', this.props.className);
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this2.element = el;
},
id: this.props.id,
className: className,
style: this.props.style
}, /*#__PURE__*/React.createElement(OrderListControls, {
value: this.props.value,
selection: this.state.selection,
onReorder: this.onReorder
}), /*#__PURE__*/React.createElement(OrderListSubList, {
ref: function ref(el) {
return _this2.subList = el;
},
value: this.props.value,
selection: this.state.selection,
onItemClick: this.onItemClick,
onItemKeyDown: this.onItemKeyDown,
itemTemplate: this.props.itemTemplate,
header: this.props.header,
listStyle: this.props.listStyle,
dragdrop: this.props.dragdrop,
onDragStart: this.onDragStart,
onDragEnter: this.onDragEnter,
onDragEnd: this.onDragEnd,
onDragLeave: this.onDragEnter,
onDrop: this.onDrop,
onChange: this.props.onChange,
tabIndex: this.props.tabIndex
}));
}
}]);
return OrderList;
}(Component);
_defineProperty(OrderList, "defaultProps", {
id: null,
value: null,
header: null,
style: null,
className: null,
listStyle: null,
dragdrop: false,
tabIndex: 0,
onChange: null,
itemTemplate: null
});
_defineProperty(OrderList, "propTypes", {
id: PropTypes.string,
value: PropTypes.array,
header: PropTypes.string,
style: PropTypes.object,
className: PropTypes.string,
listStyle: PropTypes.object,
dragdrop: PropTypes.bool,
tabIndex: PropTypes.number,
onChange: PropTypes.func,
itemTemplate: PropTypes.func
});
export { OrderList };
|
ajax/libs/material-ui/4.9.4/es/Stepper/Stepper.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import Paper from '../Paper';
import StepConnector from '../StepConnector';
export const styles = {
/* Styles applied to the root element. */
root: {
display: 'flex',
padding: 24
},
/* Styles applied to the root element if `orientation="horizontal"`. */
horizontal: {
flexDirection: 'row',
alignItems: 'center'
},
/* Styles applied to the root element if `orientation="vertical"`. */
vertical: {
flexDirection: 'column'
},
/* Styles applied to the root element if `alternativeLabel={true}`. */
alternativeLabel: {
alignItems: 'flex-start'
}
};
const defaultConnector = React.createElement(StepConnector, null);
const Stepper = React.forwardRef(function Stepper(props, ref) {
const {
activeStep = 0,
alternativeLabel = false,
children,
classes,
className,
connector: connectorProp = defaultConnector,
nonLinear = false,
orientation = 'horizontal'
} = props,
other = _objectWithoutPropertiesLoose(props, ["activeStep", "alternativeLabel", "children", "classes", "className", "connector", "nonLinear", "orientation"]);
const connector = React.isValidElement(connectorProp) ? React.cloneElement(connectorProp, {
orientation
}) : null;
const childrenArray = React.Children.toArray(children);
const steps = childrenArray.map((step, index) => {
const controlProps = {
alternativeLabel,
connector: connectorProp,
last: index + 1 === childrenArray.length,
orientation
};
const state = {
index,
active: false,
completed: false,
disabled: false
};
if (activeStep === index) {
state.active = true;
} else if (!nonLinear && activeStep > index) {
state.completed = true;
} else if (!nonLinear && activeStep < index) {
state.disabled = true;
}
return [!alternativeLabel && connector && index !== 0 && React.cloneElement(connector, _extends({
key: index
}, state)), React.cloneElement(step, _extends({}, controlProps, {}, state, {}, step.props))];
});
return React.createElement(Paper, _extends({
square: true,
elevation: 0,
className: clsx(classes.root, classes[orientation], className, alternativeLabel && classes.alternativeLabel),
ref: ref
}, other), steps);
});
process.env.NODE_ENV !== "production" ? Stepper.propTypes = {
/**
* Set the active step (zero based index).
* Set to -1 to disable all the steps.
*/
activeStep: PropTypes.number,
/**
* If set to 'true' and orientation is horizontal,
* then the step label will be positioned under the icon.
*/
alternativeLabel: PropTypes.bool,
/**
* Two or more `<Step />` components.
*/
children: PropTypes.node.isRequired,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* An element to be placed between each step.
*/
connector: PropTypes.element,
/**
* If set the `Stepper` will not assist in controlling steps for linear flow.
*/
nonLinear: PropTypes.bool,
/**
* The stepper orientation (layout flow direction).
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical'])
} : void 0;
export default withStyles(styles, {
name: 'MuiStepper'
})(Stepper); |
ajax/libs/primereact/7.2.0/orderlist/orderlist.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { Button } from 'primereact/button';
import { ObjectUtils, DomHandler, classNames } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderListControls = /*#__PURE__*/function (_Component) {
_inherits(OrderListControls, _Component);
var _super = _createSuper$2(OrderListControls);
function OrderListControls() {
var _this;
_classCallCheck(this, OrderListControls);
_this = _super.call(this);
_this.moveUp = _this.moveUp.bind(_assertThisInitialized(_this));
_this.moveTop = _this.moveTop.bind(_assertThisInitialized(_this));
_this.moveDown = _this.moveDown.bind(_assertThisInitialized(_this));
_this.moveBottom = _this.moveBottom.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderListControls, [{
key: "moveUp",
value: function moveUp(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = 0; i < this.props.selection.length; i++) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey);
if (selectedItemIndex !== 0) {
var movedItem = value[selectedItemIndex];
var temp = value[selectedItemIndex - 1];
value[selectedItemIndex - 1] = movedItem;
value[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'up'
});
}
}
}
}, {
key: "moveTop",
value: function moveTop(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = 0; i < this.props.selection.length; i++) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey);
if (selectedItemIndex !== 0) {
var movedItem = value.splice(selectedItemIndex, 1)[0];
value.unshift(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'top'
});
}
}
}
}, {
key: "moveDown",
value: function moveDown(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = this.props.selection.length - 1; i >= 0; i--) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey);
if (selectedItemIndex !== value.length - 1) {
var movedItem = value[selectedItemIndex];
var temp = value[selectedItemIndex + 1];
value[selectedItemIndex + 1] = movedItem;
value[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'down'
});
}
}
}
}, {
key: "moveBottom",
value: function moveBottom(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = this.props.selection.length - 1; i >= 0; i--) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey);
if (selectedItemIndex !== value.length - 1) {
var movedItem = value.splice(selectedItemIndex, 1)[0];
value.push(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'bottom'
});
}
}
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-controls"
}, /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-up",
onClick: this.moveUp
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-double-up",
onClick: this.moveTop
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-down",
onClick: this.moveDown
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-double-down",
onClick: this.moveBottom
}));
}
}]);
return OrderListControls;
}(Component);
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderListSubList = /*#__PURE__*/function (_Component) {
_inherits(OrderListSubList, _Component);
var _super = _createSuper$1(OrderListSubList);
function OrderListSubList(props) {
var _this;
_classCallCheck(this, OrderListSubList);
_this = _super.call(this, props);
_this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this));
_this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this));
_this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this));
_this.onListMouseMove = _this.onListMouseMove.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderListSubList, [{
key: "isSelected",
value: function isSelected(item) {
return ObjectUtils.findIndexInList(item, this.props.selection, this.props.dataKey) !== -1;
}
}, {
key: "onDragStart",
value: function onDragStart(event, index) {
this.dragging = true;
this.draggedItemIndex = index;
if (this.props.dragdropScope) {
event.dataTransfer.setData('text', 'orderlist');
}
}
}, {
key: "onDragOver",
value: function onDragOver(event, index) {
if (this.draggedItemIndex !== index && this.draggedItemIndex + 1 !== index) {
this.dragOverItemIndex = index;
DomHandler.addClass(event.target, 'p-orderlist-droppoint-highlight');
event.preventDefault();
}
}
}, {
key: "onDragLeave",
value: function onDragLeave(event) {
this.dragOverItemIndex = null;
DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight');
}
}, {
key: "onDrop",
value: function onDrop(event) {
var dropIndex = this.draggedItemIndex > this.dragOverItemIndex ? this.dragOverItemIndex : this.dragOverItemIndex === 0 ? 0 : this.dragOverItemIndex - 1;
var value = _toConsumableArray(this.props.value);
ObjectUtils.reorderArray(value, this.draggedItemIndex, dropIndex);
this.dragOverItemIndex = null;
DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight');
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: value
});
}
}
}, {
key: "onDragEnd",
value: function onDragEnd(event) {
this.dragging = false;
}
}, {
key: "onListMouseMove",
value: function onListMouseMove(event) {
if (this.dragging) {
var offsetY = this.listElement.getBoundingClientRect().top + DomHandler.getWindowScrollTop();
var bottomDiff = offsetY + this.listElement.clientHeight - event.pageY;
var topDiff = event.pageY - offsetY;
if (bottomDiff < 25 && bottomDiff > 0) this.listElement.scrollTop += 15;else if (topDiff < 25 && topDiff > 0) this.listElement.scrollTop -= 15;
}
}
}, {
key: "renderDropPoint",
value: function renderDropPoint(index, key) {
var _this2 = this;
return /*#__PURE__*/React.createElement("li", {
key: key,
className: "p-orderlist-droppoint",
onDragOver: function onDragOver(e) {
return _this2.onDragOver(e, index + 1);
},
onDragLeave: this.onDragLeave,
onDrop: this.onDrop
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var header = null;
var items = null;
if (this.props.header) {
header = /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-header"
}, this.props.header);
}
if (this.props.value) {
items = this.props.value.map(function (item, i) {
var content = _this3.props.itemTemplate ? _this3.props.itemTemplate(item) : item;
var itemClassName = classNames('p-orderlist-item', {
'p-highlight': _this3.isSelected(item)
}, _this3.props.className);
var key = JSON.stringify(item);
if (_this3.props.dragdrop) {
var _items = [_this3.renderDropPoint(i, key + '_droppoint'), /*#__PURE__*/React.createElement("li", {
key: key,
className: itemClassName,
onClick: function onClick(e) {
return _this3.props.onItemClick({
originalEvent: e,
value: item,
index: i
});
},
onKeyDown: function onKeyDown(e) {
return _this3.props.onItemKeyDown({
originalEvent: e,
value: item,
index: i
});
},
role: "option",
"aria-selected": _this3.isSelected(item),
draggable: "true",
onDragStart: function onDragStart(e) {
return _this3.onDragStart(e, i);
},
onDragEnd: _this3.onDragEnd,
tabIndex: _this3.props.tabIndex
}, content, /*#__PURE__*/React.createElement(Ripple, null))];
if (i === _this3.props.value.length - 1) {
_items.push(_this3.renderDropPoint(item, i, key + '_droppoint_end'));
}
return _items;
} else {
return /*#__PURE__*/React.createElement("li", {
key: JSON.stringify(item),
className: itemClassName,
role: "option",
"aria-selected": _this3.isSelected(item),
onClick: function onClick(e) {
return _this3.props.onItemClick({
originalEvent: e,
value: item,
index: i
});
},
onKeyDown: function onKeyDown(e) {
return _this3.props.onItemKeyDown({
originalEvent: e,
value: item,
index: i
});
},
tabIndex: _this3.props.tabIndex
}, content);
}
});
}
return /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-list-container"
}, header, /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this3.listElement = el;
},
className: "p-orderlist-list",
style: this.props.listStyle,
onDragOver: this.onListMouseMove,
role: "listbox",
"aria-multiselectable": true
}, items));
}
}]);
return OrderListSubList;
}(Component);
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderList = /*#__PURE__*/function (_Component) {
_inherits(OrderList, _Component);
var _super = _createSuper(OrderList);
function OrderList(props) {
var _this;
_classCallCheck(this, OrderList);
_this = _super.call(this, props);
_this.state = {
selection: []
};
_this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this));
_this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this));
_this.onReorder = _this.onReorder.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderList, [{
key: "onItemClick",
value: function onItemClick(event) {
var metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey;
var index = ObjectUtils.findIndexInList(event.value, this.state.selection, this.props.dataKey);
var selected = index !== -1;
var selection;
if (selected) {
if (metaKey) selection = this.state.selection.filter(function (val, i) {
return i !== index;
});else selection = [event.value];
} else {
if (metaKey) selection = [].concat(_toConsumableArray(this.state.selection), [event.value]);else selection = [event.value];
}
this.setState({
selection: selection
});
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event) {
var listItem = event.originalEvent.currentTarget;
switch (event.originalEvent.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.focus();
}
event.originalEvent.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.focus();
}
event.originalEvent.preventDefault();
break;
//enter
case 13:
this.onItemClick(event);
event.originalEvent.preventDefault();
break;
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return !DomHandler.hasClass(nextItem, 'p-orderlist-item') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return !DomHandler.hasClass(prevItem, 'p-orderlist-item') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "onReorder",
value: function onReorder(event) {
if (this.props.onChange) {
this.props.onChange({
event: event.originalEvent,
value: event.value
});
}
this.reorderDirection = event.direction;
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this.reorderDirection) {
this.updateListScroll();
this.reorderDirection = null;
}
}
}, {
key: "updateListScroll",
value: function updateListScroll() {
var listItems = DomHandler.find(this.subList.listElement, '.p-orderlist-item.p-highlight');
if (listItems && listItems.length) {
switch (this.reorderDirection) {
case 'up':
DomHandler.scrollInView(this.subList.listElement, listItems[0]);
break;
case 'top':
this.subList.listElement.scrollTop = 0;
break;
case 'down':
DomHandler.scrollInView(this.subList.listElement, listItems[listItems.length - 1]);
break;
case 'bottom':
this.subList.listElement.scrollTop = this.subList.listElement.scrollHeight;
break;
}
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var className = classNames('p-orderlist p-component', this.props.className);
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this2.element = el;
},
id: this.props.id,
className: className,
style: this.props.style
}, /*#__PURE__*/React.createElement(OrderListControls, {
value: this.props.value,
selection: this.state.selection,
onReorder: this.onReorder,
dataKey: this.props.dataKey
}), /*#__PURE__*/React.createElement(OrderListSubList, {
ref: function ref(el) {
return _this2.subList = el;
},
value: this.props.value,
selection: this.state.selection,
onItemClick: this.onItemClick,
onItemKeyDown: this.onItemKeyDown,
itemTemplate: this.props.itemTemplate,
header: this.props.header,
listStyle: this.props.listStyle,
dataKey: this.props.dataKey,
dragdrop: this.props.dragdrop,
onDragStart: this.onDragStart,
onDragEnter: this.onDragEnter,
onDragEnd: this.onDragEnd,
onDragLeave: this.onDragEnter,
onDrop: this.onDrop,
onChange: this.props.onChange,
tabIndex: this.props.tabIndex
}));
}
}]);
return OrderList;
}(Component);
_defineProperty(OrderList, "defaultProps", {
id: null,
value: null,
header: null,
style: null,
className: null,
listStyle: null,
dragdrop: false,
tabIndex: 0,
dataKey: null,
onChange: null,
itemTemplate: null
});
export { OrderList };
|
ajax/libs/react-native-web/0.15.5/modules/UnimplementedView/index.js | cdnjs/cdnjs | function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* 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.
*
*
*/
import View from '../../exports/View';
import React from 'react';
/**
* Common implementation for a simple stubbed view.
*/
var UnimplementedView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(UnimplementedView, _React$Component);
function UnimplementedView() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = UnimplementedView.prototype;
_proto.setNativeProps = function setNativeProps() {// Do nothing.
};
_proto.render = function render() {
return (
/*#__PURE__*/
React.createElement(View, {
style: [unimplementedViewStyles, this.props.style]
}, this.props.children)
);
};
return UnimplementedView;
}(React.Component);
var unimplementedViewStyles = process.env.NODE_ENV !== 'production' ? {
alignSelf: 'flex-start',
borderColor: 'red',
borderWidth: 1
} : {};
export default UnimplementedView; |
ajax/libs/material-ui/4.11.3/esm/utils/createSvgIcon.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import SvgIcon from '../SvgIcon';
/**
* Private module reserved for @material-ui/x packages.
*/
export default function createSvgIcon(path, displayName) {
var Component = function Component(props, ref) {
return /*#__PURE__*/React.createElement(SvgIcon, _extends({
ref: ref
}, props), path);
};
if (process.env.NODE_ENV !== 'production') {
// Need to set `displayName` on the inner component for React.memo.
// React prior to 16.14 ignores `displayName` on the wrapper.
Component.displayName = "".concat(displayName, "Icon");
}
Component.muiName = SvgIcon.muiName;
return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));
} |
ajax/libs/material-ui/4.9.3/es/Tooltip/Tooltip.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { elementAcceptingRef } from '@material-ui/utils';
import { fade } from '../styles/colorManipulator';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
import Grow from '../Grow';
import Popper from '../Popper';
import useForkRef from '../utils/useForkRef';
import setRef from '../utils/setRef';
import { useIsFocusVisible } from '../utils/focusVisible';
import useControlled from '../utils/useControlled';
import useTheme from '../styles/useTheme';
function round(value) {
return Math.round(value * 1e5) / 1e5;
}
function arrowGenerator() {
return {
'&[x-placement*="bottom"] $arrow': {
flip: false,
top: 0,
left: 0,
marginTop: '-0.95em',
marginLeft: 4,
marginRight: 4,
width: '2em',
height: '1em',
'&::before': {
flip: false,
borderWidth: '0 1em 1em 1em',
borderColor: 'transparent transparent currentcolor transparent'
}
},
'&[x-placement*="top"] $arrow': {
flip: false,
bottom: 0,
left: 0,
marginBottom: '-0.95em',
marginLeft: 4,
marginRight: 4,
width: '2em',
height: '1em',
'&::before': {
flip: false,
borderWidth: '1em 1em 0 1em',
borderColor: 'currentcolor transparent transparent transparent'
}
},
'&[x-placement*="right"] $arrow': {
flip: false,
left: 0,
marginLeft: '-0.95em',
marginTop: 4,
marginBottom: 4,
height: '2em',
width: '1em',
'&::before': {
flip: false,
borderWidth: '1em 1em 1em 0',
borderColor: 'transparent currentcolor transparent transparent'
}
},
'&[x-placement*="left"] $arrow': {
flip: false,
right: 0,
marginRight: '-0.95em',
marginTop: 4,
marginBottom: 4,
height: '2em',
width: '1em',
'&::before': {
flip: false,
borderWidth: '1em 0 1em 1em',
borderColor: 'transparent transparent transparent currentcolor'
}
}
};
}
export const styles = theme => ({
/* Styles applied to the Popper component. */
popper: {
zIndex: theme.zIndex.tooltip,
pointerEvents: 'none',
flip: false // disable jss-rtl plugin
},
/* Styles applied to the Popper component if `interactive={true}`. */
popperInteractive: {
pointerEvents: 'auto'
},
/* Styles applied to the Popper component if `arrow={true}`. */
popperArrow: arrowGenerator(),
/* Styles applied to the tooltip (label wrapper) element. */
tooltip: {
backgroundColor: fade(theme.palette.grey[700], 0.9),
borderRadius: theme.shape.borderRadius,
color: theme.palette.common.white,
fontFamily: theme.typography.fontFamily,
padding: '4px 8px',
fontSize: theme.typography.pxToRem(10),
lineHeight: `${round(14 / 10)}em`,
maxWidth: 300,
wordWrap: 'break-word',
fontWeight: theme.typography.fontWeightMedium
},
/* Styles applied to the tooltip (label wrapper) element if `arrow={true}`. */
tooltipArrow: {
position: 'relative',
margin: '0'
},
/* Styles applied to the arrow element. */
arrow: {
position: 'absolute',
fontSize: 6,
color: fade(theme.palette.grey[700], 0.9),
'&::before': {
content: '""',
margin: 'auto',
display: 'block',
width: 0,
height: 0,
borderStyle: 'solid'
}
},
/* Styles applied to the tooltip (label wrapper) element if the tooltip is opened by touch. */
touch: {
padding: '8px 16px',
fontSize: theme.typography.pxToRem(14),
lineHeight: `${round(16 / 14)}em`,
fontWeight: theme.typography.fontWeightRegular
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "left". */
tooltipPlacementLeft: {
transformOrigin: 'right center',
margin: '0 24px ',
[theme.breakpoints.up('sm')]: {
margin: '0 14px'
}
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "right". */
tooltipPlacementRight: {
transformOrigin: 'left center',
margin: '0 24px',
[theme.breakpoints.up('sm')]: {
margin: '0 14px'
}
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "top". */
tooltipPlacementTop: {
transformOrigin: 'center bottom',
margin: '24px 0',
[theme.breakpoints.up('sm')]: {
margin: '14px 0'
}
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "bottom". */
tooltipPlacementBottom: {
transformOrigin: 'center top',
margin: '24px 0',
[theme.breakpoints.up('sm')]: {
margin: '14px 0'
}
}
});
let hystersisOpen = false;
let hystersisTimer = null;
export function testReset() {
hystersisOpen = false;
clearTimeout(hystersisTimer);
}
const Tooltip = React.forwardRef(function Tooltip(props, ref) {
const {
arrow = false,
children,
classes,
disableFocusListener = false,
disableHoverListener = false,
disableTouchListener = false,
enterDelay = 0,
enterTouchDelay = 700,
id: idProp,
interactive = false,
leaveDelay = 0,
leaveTouchDelay = 1500,
onClose,
onOpen,
open: openProp,
placement = 'bottom',
PopperProps,
title,
TransitionComponent = Grow,
TransitionProps
} = props,
other = _objectWithoutPropertiesLoose(props, ["arrow", "children", "classes", "disableFocusListener", "disableHoverListener", "disableTouchListener", "enterDelay", "enterTouchDelay", "id", "interactive", "leaveDelay", "leaveTouchDelay", "onClose", "onOpen", "open", "placement", "PopperProps", "title", "TransitionComponent", "TransitionProps"]);
const theme = useTheme();
const [childNode, setChildNode] = React.useState();
const [arrowRef, setArrowRef] = React.useState(null);
const ignoreNonTouchEvents = React.useRef(false);
const closeTimer = React.useRef();
const enterTimer = React.useRef();
const leaveTimer = React.useRef();
const touchTimer = React.useRef();
const [openState, setOpenState] = useControlled({
controlled: openProp,
default: false,
name: 'Tooltip'
});
let open = openState;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
const {
current: isControlled
} = React.useRef(openProp !== undefined); // eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (childNode && childNode.disabled && !isControlled && title !== '' && childNode.tagName.toLowerCase() === 'button') {
console.error(['Material-UI: you are providing a disabled `button` child to the Tooltip component.', 'A disabled element does not fire events.', "Tooltip needs to listen to the child element's events to display the title.", '', 'Add a simple wrapper element, such as a `span`.'].join('\n'));
}
}, [title, childNode, isControlled]);
}
const [defaultId, setDefaultId] = React.useState();
const id = idProp || defaultId;
React.useEffect(() => {
if (!open || defaultId) {
return;
} // Fallback to this default id when possible.
// Use the random value for client-side rendering only.
// We can't use it server-side.
setDefaultId(`mui-tooltip-${Math.round(Math.random() * 1e5)}`);
}, [open, defaultId]);
React.useEffect(() => {
return () => {
clearTimeout(closeTimer.current);
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
clearTimeout(touchTimer.current);
};
}, []);
const handleOpen = event => {
clearTimeout(hystersisTimer);
hystersisOpen = true; // The mouseover event will trigger for every nested element in the tooltip.
// We can skip rerendering when the tooltip is already open.
// We are using the mouseover event instead of the mouseenter event to fix a hide/show issue.
setOpenState(true);
if (onOpen) {
onOpen(event);
}
};
const handleEnter = event => {
const childrenProps = children.props;
if (event.type === 'mouseover' && childrenProps.onMouseOver && event.currentTarget === childNode) {
childrenProps.onMouseOver(event);
}
if (ignoreNonTouchEvents.current && event.type !== 'touchstart') {
return;
} // Remove the title ahead of time.
// We don't want to wait for the next render commit.
// We would risk displaying two tooltips at the same time (native + this one).
if (childNode) {
childNode.removeAttribute('title');
}
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
if (enterDelay && !hystersisOpen) {
event.persist();
enterTimer.current = setTimeout(() => {
handleOpen(event);
}, enterDelay);
} else {
handleOpen(event);
}
};
const {
isFocusVisible,
onBlurVisible,
ref: focusVisibleRef
} = useIsFocusVisible();
const [childIsFocusVisible, setChildIsFocusVisible] = React.useState(false);
const handleBlur = () => {
if (childIsFocusVisible) {
setChildIsFocusVisible(false);
onBlurVisible();
}
};
const handleFocus = event => {
// Workaround for https://github.com/facebook/react/issues/7769
// The autoFocus of React might trigger the event before the componentDidMount.
// We need to account for this eventuality.
if (!childNode) {
setChildNode(event.currentTarget);
}
if (isFocusVisible(event)) {
setChildIsFocusVisible(true);
handleEnter(event);
}
const childrenProps = children.props;
if (childrenProps.onFocus && event.currentTarget === childNode) {
childrenProps.onFocus(event);
}
};
const handleClose = event => {
clearTimeout(hystersisTimer);
hystersisTimer = setTimeout(() => {
hystersisOpen = false;
}, 500); // Use 500 ms per https://github.com/reach/reach-ui/blob/3b5319027d763a3082880be887d7a29aee7d3afc/packages/tooltip/src/index.js#L214
setOpenState(false);
if (onClose) {
onClose(event);
}
clearTimeout(closeTimer.current);
closeTimer.current = setTimeout(() => {
ignoreNonTouchEvents.current = false;
}, theme.transitions.duration.shortest);
};
const handleLeave = event => {
const childrenProps = children.props;
if (event.type === 'blur') {
if (childrenProps.onBlur && event.currentTarget === childNode) {
childrenProps.onBlur(event);
}
handleBlur(event);
}
if (event.type === 'mouseleave' && childrenProps.onMouseLeave && event.currentTarget === childNode) {
childrenProps.onMouseLeave(event);
}
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
event.persist();
leaveTimer.current = setTimeout(() => {
handleClose(event);
}, leaveDelay);
};
const handleTouchStart = event => {
ignoreNonTouchEvents.current = true;
const childrenProps = children.props;
if (childrenProps.onTouchStart) {
childrenProps.onTouchStart(event);
}
clearTimeout(leaveTimer.current);
clearTimeout(closeTimer.current);
clearTimeout(touchTimer.current);
event.persist();
touchTimer.current = setTimeout(() => {
handleEnter(event);
}, enterTouchDelay);
};
const handleTouchEnd = event => {
if (children.props.onTouchEnd) {
children.props.onTouchEnd(event);
}
clearTimeout(touchTimer.current);
clearTimeout(leaveTimer.current);
event.persist();
leaveTimer.current = setTimeout(() => {
handleClose(event);
}, leaveTouchDelay);
};
const handleUseRef = useForkRef(setChildNode, ref);
const handleFocusRef = useForkRef(focusVisibleRef, handleUseRef); // can be removed once we drop support for non ref forwarding class components
const handleOwnRef = React.useCallback(instance => {
// #StrictMode ready
setRef(handleFocusRef, ReactDOM.findDOMNode(instance));
}, [handleFocusRef]);
const handleRef = useForkRef(children.ref, handleOwnRef); // There is no point in displaying an empty tooltip.
if (title === '') {
open = false;
} // For accessibility and SEO concerns, we render the title to the DOM node when
// the tooltip is hidden. However, we have made a tradeoff when
// `disableHoverListener` is set. This title logic is disabled.
// It's allowing us to keep the implementation size minimal.
// We are open to change the tradeoff.
const shouldShowNativeTitle = !open && !disableHoverListener;
const childrenProps = _extends({
'aria-describedby': open ? id : null,
title: shouldShowNativeTitle && typeof title === 'string' ? title : null
}, other, {}, children.props, {
className: clsx(other.className, children.props.className)
});
if (!disableTouchListener) {
childrenProps.onTouchStart = handleTouchStart;
childrenProps.onTouchEnd = handleTouchEnd;
}
if (!disableHoverListener) {
childrenProps.onMouseOver = handleEnter;
childrenProps.onMouseLeave = handleLeave;
}
if (!disableFocusListener) {
childrenProps.onFocus = handleFocus;
childrenProps.onBlur = handleLeave;
}
const interactiveWrapperListeners = interactive ? {
onMouseOver: childrenProps.onMouseOver,
onMouseLeave: childrenProps.onMouseLeave,
onFocus: childrenProps.onFocus,
onBlur: childrenProps.onBlur
} : {};
if (process.env.NODE_ENV !== 'production') {
if (children.props.title) {
console.error(['Material-UI: you have provided a `title` prop to the child of <Tooltip />.', `Remove this title prop \`${children.props.title}\` or the Tooltip component.`].join('\n'));
}
} // Avoid the creation of a new Popper.js instance at each render.
const popperOptions = React.useMemo(() => ({
modifiers: {
arrow: {
enabled: Boolean(arrowRef),
element: arrowRef
}
}
}), [arrowRef]);
return React.createElement(React.Fragment, null, React.cloneElement(children, _extends({
ref: handleRef
}, childrenProps)), React.createElement(Popper, _extends({
className: clsx(classes.popper, interactive && classes.popperInteractive, arrow && classes.popperArrow),
placement: placement,
anchorEl: childNode,
open: childNode ? open : false,
id: childrenProps['aria-describedby'],
transition: true,
popperOptions: popperOptions
}, interactiveWrapperListeners, PopperProps), ({
placement: placementInner,
TransitionProps: TransitionPropsInner
}) => React.createElement(TransitionComponent, _extends({
timeout: theme.transitions.duration.shorter
}, TransitionPropsInner, TransitionProps), React.createElement("div", {
className: clsx(classes.tooltip, classes[`tooltipPlacement${capitalize(placementInner.split('-')[0])}`], ignoreNonTouchEvents.current && classes.touch, arrow && classes.tooltipArrow)
}, title, arrow ? React.createElement("span", {
className: classes.arrow,
ref: setArrowRef
}) : null))));
});
process.env.NODE_ENV !== "production" ? Tooltip.propTypes = {
/**
* If `true`, adds an arrow to the tooltip.
*/
arrow: PropTypes.bool,
/**
* Tooltip reference element.
*/
children: elementAcceptingRef.isRequired,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* Do not respond to focus events.
*/
disableFocusListener: PropTypes.bool,
/**
* Do not respond to hover events.
*/
disableHoverListener: PropTypes.bool,
/**
* Do not respond to long press touch events.
*/
disableTouchListener: PropTypes.bool,
/**
* The number of milliseconds to wait before showing the tooltip.
* This prop won't impact the enter touch delay (`enterTouchDelay`).
*/
enterDelay: PropTypes.number,
/**
* The number of milliseconds a user must touch the element before showing the tooltip.
*/
enterTouchDelay: PropTypes.number,
/**
* This prop is used to help implement the accessibility logic.
* If you don't provide this prop. It falls back to a randomly generated id.
*/
id: PropTypes.string,
/**
* Makes a tooltip interactive, i.e. will not close when the user
* hovers over the tooltip before the `leaveDelay` is expired.
*/
interactive: PropTypes.bool,
/**
* The number of milliseconds to wait before hiding the tooltip.
* This prop won't impact the leave touch delay (`leaveTouchDelay`).
*/
leaveDelay: PropTypes.number,
/**
* The number of milliseconds after the user stops touching an element before hiding the tooltip.
*/
leaveTouchDelay: PropTypes.number,
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* Callback fired when the component requests to be open.
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* If `true`, the tooltip is shown.
*/
open: PropTypes.bool,
/**
* Tooltip placement.
*/
placement: PropTypes.oneOf(['bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),
/**
* Props applied to the [`Popper`](/api/popper/) element.
*/
PopperProps: PropTypes.object,
/**
* Tooltip title. Zero-length titles string are never displayed.
*/
title: PropTypes.node.isRequired,
/**
* The component used for the transition.
* [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
*/
TransitionComponent: PropTypes.elementType,
/**
* Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element.
*/
TransitionProps: PropTypes.object
} : void 0;
export default withStyles(styles, {
name: 'MuiTooltip'
})(Tooltip); |
ajax/libs/material-ui/4.9.4/es/StepLabel/StepLabel.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import Typography from '../Typography';
import StepIcon from '../StepIcon';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
display: 'flex',
alignItems: 'center',
'&$alternativeLabel': {
flexDirection: 'column'
},
'&$disabled': {
cursor: 'default'
}
},
/* Styles applied to the root element if `orientation="horizontal". */
horizontal: {},
/* Styles applied to the root element if `orientation="vertical". */
vertical: {},
/* Styles applied to the `Typography` component which wraps `children`. */
label: {
color: theme.palette.text.secondary,
'&$active': {
color: theme.palette.text.primary,
fontWeight: 500
},
'&$completed': {
color: theme.palette.text.primary,
fontWeight: 500
},
'&$alternativeLabel': {
textAlign: 'center',
marginTop: 16
},
'&$error': {
color: theme.palette.error.main
}
},
/* Pseudo-class applied to the `Typography` component if `active={true}`. */
active: {},
/* Pseudo-class applied to the `Typography` component if `completed={true}`. */
completed: {},
/* Pseudo-class applied to the root element and `Typography` component if `error={true}`. */
error: {},
/* Pseudo-class applied to the root element and `Typography` component if `disabled={true}`. */
disabled: {},
/* Styles applied to the `icon` container element. */
iconContainer: {
flexShrink: 0,
// Fix IE 11 issue
display: 'flex',
paddingRight: 8,
'&$alternativeLabel': {
paddingRight: 0
}
},
/* Pseudo-class applied to the root and icon container and `Typography` if `alternativeLabel={true}`. */
alternativeLabel: {},
/* Styles applied to the container element which wraps `Typography` and `optional`. */
labelContainer: {
width: '100%'
}
});
const StepLabel = React.forwardRef(function StepLabel(props, ref) {
const {
active = false,
alternativeLabel = false,
children,
classes,
className,
completed = false,
disabled = false,
error = false,
icon,
optional,
orientation = 'horizontal',
StepIconComponent: StepIconComponentProp,
StepIconProps
} = props,
other = _objectWithoutPropertiesLoose(props, ["active", "alternativeLabel", "children", "classes", "className", "completed", "disabled", "error", "expanded", "icon", "last", "optional", "orientation", "StepIconComponent", "StepIconProps"]);
let StepIconComponent = StepIconComponentProp;
if (icon && !StepIconComponent) {
StepIconComponent = StepIcon;
}
return React.createElement("span", _extends({
className: clsx(classes.root, classes[orientation], className, disabled && classes.disabled, alternativeLabel && classes.alternativeLabel, error && classes.error),
ref: ref
}, other), icon || StepIconComponent ? React.createElement("span", {
className: clsx(classes.iconContainer, alternativeLabel && classes.alternativeLabel)
}, React.createElement(StepIconComponent, _extends({
completed: completed,
active: active,
error: error,
icon: icon
}, StepIconProps))) : null, React.createElement("span", {
className: classes.labelContainer
}, React.createElement(Typography, {
variant: "body2",
component: "span",
className: clsx(classes.label, alternativeLabel && classes.alternativeLabel, completed && classes.completed, active && classes.active, error && classes.error),
display: "block"
}, children), optional));
});
process.env.NODE_ENV !== "production" ? StepLabel.propTypes = {
/**
* @ignore
*/
active: PropTypes.bool,
/**
* @ignore
*/
alternativeLabel: PropTypes.bool,
/**
* In most cases will simply be a string containing a title for the label.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
*/
completed: PropTypes.bool,
/**
* Mark the step as disabled, will also disable the button if
* `StepLabelButton` is a child of `StepLabel`. Is passed to child components.
*/
disabled: PropTypes.bool,
/**
* Mark the step as failed.
*/
error: PropTypes.bool,
/**
* @ignore
*/
expanded: PropTypes.bool,
/**
* Override the default label of the step icon.
*/
icon: PropTypes.node,
/**
* @ignore
*/
last: PropTypes.bool,
/**
* The optional node to display.
*/
optional: PropTypes.node,
/**
* @ignore
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* The component to render in place of the [`StepIcon`](/api/step-icon/).
*/
StepIconComponent: PropTypes.elementType,
/**
* Props applied to the [`StepIcon`](/api/step-icon/) element.
*/
StepIconProps: PropTypes.object
} : void 0;
StepLabel.muiName = 'StepLabel';
export default withStyles(styles, {
name: 'MuiStepLabel'
})(StepLabel); |
ajax/libs/material-ui/4.9.2/es/Typography/Typography.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
margin: 0
},
/* Styles applied to the root element if `variant="body2"`. */
body2: theme.typography.body2,
/* Styles applied to the root element if `variant="body1"`. */
body1: theme.typography.body1,
/* Styles applied to the root element if `variant="caption"`. */
caption: theme.typography.caption,
/* Styles applied to the root element if `variant="button"`. */
button: theme.typography.button,
/* Styles applied to the root element if `variant="h1"`. */
h1: theme.typography.h1,
/* Styles applied to the root element if `variant="h2"`. */
h2: theme.typography.h2,
/* Styles applied to the root element if `variant="h3"`. */
h3: theme.typography.h3,
/* Styles applied to the root element if `variant="h4"`. */
h4: theme.typography.h4,
/* Styles applied to the root element if `variant="h5"`. */
h5: theme.typography.h5,
/* Styles applied to the root element if `variant="h6"`. */
h6: theme.typography.h6,
/* Styles applied to the root element if `variant="subtitle1"`. */
subtitle1: theme.typography.subtitle1,
/* Styles applied to the root element if `variant="subtitle2"`. */
subtitle2: theme.typography.subtitle2,
/* Styles applied to the root element if `variant="overline"`. */
overline: theme.typography.overline,
/* Styles applied to the root element if `variant="srOnly"`. Only accessible to screen readers. */
srOnly: {
position: 'absolute',
height: 1,
width: 1,
overflow: 'hidden'
},
/* Styles applied to the root element if `align="left"`. */
alignLeft: {
textAlign: 'left'
},
/* Styles applied to the root element if `align="center"`. */
alignCenter: {
textAlign: 'center'
},
/* Styles applied to the root element if `align="right"`. */
alignRight: {
textAlign: 'right'
},
/* Styles applied to the root element if `align="justify"`. */
alignJustify: {
textAlign: 'justify'
},
/* Styles applied to the root element if `nowrap={true}`. */
noWrap: {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
},
/* Styles applied to the root element if `gutterBottom={true}`. */
gutterBottom: {
marginBottom: '0.35em'
},
/* Styles applied to the root element if `paragraph={true}`. */
paragraph: {
marginBottom: 16
},
/* Styles applied to the root element if `color="inherit"`. */
colorInherit: {
color: 'inherit'
},
/* Styles applied to the root element if `color="primary"`. */
colorPrimary: {
color: theme.palette.primary.main
},
/* Styles applied to the root element if `color="secondary"`. */
colorSecondary: {
color: theme.palette.secondary.main
},
/* Styles applied to the root element if `color="textPrimary"`. */
colorTextPrimary: {
color: theme.palette.text.primary
},
/* Styles applied to the root element if `color="textSecondary"`. */
colorTextSecondary: {
color: theme.palette.text.secondary
},
/* Styles applied to the root element if `color="error"`. */
colorError: {
color: theme.palette.error.main
},
/* Styles applied to the root element if `display="inline"`. */
displayInline: {
display: 'inline'
},
/* Styles applied to the root element if `display="block"`. */
displayBlock: {
display: 'block'
}
});
const defaultVariantMapping = {
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
subtitle1: 'h6',
subtitle2: 'h6',
body1: 'p',
body2: 'p'
};
const Typography = React.forwardRef(function Typography(props, ref) {
const {
align = 'inherit',
classes,
className,
color = 'initial',
component,
display = 'initial',
gutterBottom = false,
noWrap = false,
paragraph = false,
variant = 'body1',
variantMapping = defaultVariantMapping
} = props,
other = _objectWithoutPropertiesLoose(props, ["align", "classes", "className", "color", "component", "display", "gutterBottom", "noWrap", "paragraph", "variant", "variantMapping"]);
const Component = component || (paragraph ? 'p' : variantMapping[variant] || defaultVariantMapping[variant]) || 'span';
return React.createElement(Component, _extends({
className: clsx(classes.root, className, variant !== 'inherit' && classes[variant], color !== 'initial' && classes[`color${capitalize(color)}`], noWrap && classes.noWrap, gutterBottom && classes.gutterBottom, paragraph && classes.paragraph, align !== 'inherit' && classes[`align${capitalize(align)}`], display !== 'initial' && classes[`display${capitalize(display)}`]),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? Typography.propTypes = {
/**
* Set the text-align on the component.
*/
align: PropTypes.oneOf(['inherit', 'left', 'center', 'right', 'justify']),
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['initial', 'inherit', 'primary', 'secondary', 'textPrimary', 'textSecondary', 'error']),
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
* Overrides the behavior of the `variantMapping` prop.
*/
component: PropTypes.elementType,
/**
* Controls the display type
*/
display: PropTypes.oneOf(['initial', 'block', 'inline']),
/**
* If `true`, the text will have a bottom margin.
*/
gutterBottom: PropTypes.bool,
/**
* If `true`, the text will not wrap, but instead will truncate with a text overflow ellipsis.
*
* Note that text overflow can only happen with block or inline-block level elements
* (the element needs to have a width in order to overflow).
*/
noWrap: PropTypes.bool,
/**
* If `true`, the text will have a bottom margin.
*/
paragraph: PropTypes.bool,
/**
* Applies the theme typography styles.
*/
variant: PropTypes.oneOf(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1', 'subtitle2', 'body1', 'body2', 'caption', 'button', 'overline', 'srOnly', 'inherit']),
/**
* The component maps the variant prop to a range of different DOM element types.
* For instance, subtitle1 to `<h6>`.
* If you wish to change that mapping, you can provide your own.
* Alternatively, you can use the `component` prop.
*/
variantMapping: PropTypes.object
} : void 0;
export default withStyles(styles, {
name: 'MuiTypography'
})(Typography); |
ajax/libs/material-ui/4.9.4/esm/ButtonBase/ButtonBase.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import clsx from 'clsx';
import { elementTypeAcceptingRef, refType } from '@material-ui/utils';
import useForkRef from '../utils/useForkRef';
import useEventCallback from '../utils/useEventCallback';
import withStyles from '../styles/withStyles';
import NoSsr from '../NoSsr';
import { useIsFocusVisible } from '../utils/focusVisible';
import TouchRipple from './TouchRipple';
export var styles = {
/* Styles applied to the root element. */
root: {
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
position: 'relative',
WebkitTapHighlightColor: 'transparent',
backgroundColor: 'transparent',
// Reset default value
// We disable the focus ring for mouse, touch and keyboard users.
outline: 0,
border: 0,
margin: 0,
// Remove the margin in Safari
borderRadius: 0,
padding: 0,
// Remove the padding in Firefox
cursor: 'pointer',
userSelect: 'none',
verticalAlign: 'middle',
'-moz-appearance': 'none',
// Reset
'-webkit-appearance': 'none',
// Reset
textDecoration: 'none',
// So we take precedent over the style of a native <a /> element.
color: 'inherit',
'&::-moz-focus-inner': {
borderStyle: 'none' // Remove Firefox dotted outline.
},
'&$disabled': {
pointerEvents: 'none',
// Disable link interactions
cursor: 'default'
}
},
/* Pseudo-class applied to the root element if `disabled={true}`. */
disabled: {},
/* Pseudo-class applied to the root element if keyboard focused. */
focusVisible: {}
};
/**
* `ButtonBase` contains as few styles as possible.
* It aims to be a simple building block for creating a button.
* It contains a load of style reset and some focus/ripple logic.
*/
var ButtonBase = React.forwardRef(function ButtonBase(props, ref) {
var action = props.action,
buttonRefProp = props.buttonRef,
_props$centerRipple = props.centerRipple,
centerRipple = _props$centerRipple === void 0 ? false : _props$centerRipple,
children = props.children,
classes = props.classes,
className = props.className,
_props$component = props.component,
component = _props$component === void 0 ? 'button' : _props$component,
_props$disabled = props.disabled,
disabled = _props$disabled === void 0 ? false : _props$disabled,
_props$disableRipple = props.disableRipple,
disableRipple = _props$disableRipple === void 0 ? false : _props$disableRipple,
_props$disableTouchRi = props.disableTouchRipple,
disableTouchRipple = _props$disableTouchRi === void 0 ? false : _props$disableTouchRi,
_props$focusRipple = props.focusRipple,
focusRipple = _props$focusRipple === void 0 ? false : _props$focusRipple,
focusVisibleClassName = props.focusVisibleClassName,
onBlur = props.onBlur,
onClick = props.onClick,
onFocus = props.onFocus,
onFocusVisible = props.onFocusVisible,
onKeyDown = props.onKeyDown,
onKeyUp = props.onKeyUp,
onMouseDown = props.onMouseDown,
onMouseLeave = props.onMouseLeave,
onMouseUp = props.onMouseUp,
onTouchEnd = props.onTouchEnd,
onTouchMove = props.onTouchMove,
onTouchStart = props.onTouchStart,
onDragLeave = props.onDragLeave,
_props$tabIndex = props.tabIndex,
tabIndex = _props$tabIndex === void 0 ? 0 : _props$tabIndex,
TouchRippleProps = props.TouchRippleProps,
_props$type = props.type,
type = _props$type === void 0 ? 'button' : _props$type,
other = _objectWithoutProperties(props, ["action", "buttonRef", "centerRipple", "children", "classes", "className", "component", "disabled", "disableRipple", "disableTouchRipple", "focusRipple", "focusVisibleClassName", "onBlur", "onClick", "onFocus", "onFocusVisible", "onKeyDown", "onKeyUp", "onMouseDown", "onMouseLeave", "onMouseUp", "onTouchEnd", "onTouchMove", "onTouchStart", "onDragLeave", "tabIndex", "TouchRippleProps", "type"]);
var buttonRef = React.useRef(null);
function getButtonNode() {
// #StrictMode ready
return ReactDOM.findDOMNode(buttonRef.current);
}
var rippleRef = React.useRef(null);
var _React$useState = React.useState(false),
focusVisible = _React$useState[0],
setFocusVisible = _React$useState[1];
if (disabled && focusVisible) {
setFocusVisible(false);
}
var _useIsFocusVisible = useIsFocusVisible(),
isFocusVisible = _useIsFocusVisible.isFocusVisible,
onBlurVisible = _useIsFocusVisible.onBlurVisible,
focusVisibleRef = _useIsFocusVisible.ref;
React.useImperativeHandle(action, function () {
return {
focusVisible: function focusVisible() {
setFocusVisible(true);
buttonRef.current.focus();
}
};
}, []);
React.useEffect(function () {
if (focusVisible && focusRipple && !disableRipple) {
rippleRef.current.pulsate();
}
}, [disableRipple, focusRipple, focusVisible]);
function useRippleHandler(rippleAction, eventCallback) {
var skipRippleAction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : disableTouchRipple;
return useEventCallback(function (event) {
if (eventCallback) {
eventCallback(event);
}
var ignore = skipRippleAction;
if (!ignore && rippleRef.current) {
rippleRef.current[rippleAction](event);
}
return true;
});
}
var handleMouseDown = useRippleHandler('start', onMouseDown);
var handleDragLeave = useRippleHandler('stop', onDragLeave);
var handleMouseUp = useRippleHandler('stop', onMouseUp);
var handleMouseLeave = useRippleHandler('stop', function (event) {
if (focusVisible) {
event.preventDefault();
}
if (onMouseLeave) {
onMouseLeave(event);
}
});
var handleTouchStart = useRippleHandler('start', onTouchStart);
var handleTouchEnd = useRippleHandler('stop', onTouchEnd);
var handleTouchMove = useRippleHandler('stop', onTouchMove);
var handleBlur = useRippleHandler('stop', function (event) {
if (focusVisible) {
onBlurVisible(event);
setFocusVisible(false);
}
if (onBlur) {
onBlur(event);
}
}, false);
var handleFocus = useEventCallback(function (event) {
if (disabled) {
return;
} // Fix for https://github.com/facebook/react/issues/7769
if (!buttonRef.current) {
buttonRef.current = event.currentTarget;
}
if (isFocusVisible(event)) {
setFocusVisible(true);
if (onFocusVisible) {
onFocusVisible(event);
}
}
if (onFocus) {
onFocus(event);
}
});
var isNonNativeButton = function isNonNativeButton() {
var button = getButtonNode();
return component && component !== 'button' && !(button.tagName === 'A' && button.href);
};
/**
* IE 11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat
*/
var keydownRef = React.useRef(false);
var handleKeyDown = useEventCallback(function (event) {
// Check if key is already down to avoid repeats being counted as multiple activations
if (focusRipple && !keydownRef.current && focusVisible && rippleRef.current && event.key === ' ') {
keydownRef.current = true;
event.persist();
rippleRef.current.stop(event, function () {
rippleRef.current.start(event);
});
}
if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') {
event.preventDefault();
}
if (onKeyDown) {
onKeyDown(event);
} // Keyboard accessibility for non interactive elements
if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter') {
event.preventDefault();
if (onClick) {
onClick(event);
}
}
});
var handleKeyUp = useEventCallback(function (event) {
// calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed
// https://codesandbox.io/s/button-keyup-preventdefault-dn7f0
if (focusRipple && event.key === ' ' && rippleRef.current && focusVisible && !event.defaultPrevented) {
keydownRef.current = false;
event.persist();
rippleRef.current.stop(event, function () {
rippleRef.current.pulsate(event);
});
}
if (onKeyUp) {
onKeyUp(event);
} // Keyboard accessibility for non interactive elements
if (onClick && event.target === event.currentTarget && isNonNativeButton() && event.key === ' ' && !event.defaultPrevented) {
onClick(event);
}
});
var ComponentProp = component;
if (ComponentProp === 'button' && other.href) {
ComponentProp = 'a';
}
var buttonProps = {};
if (ComponentProp === 'button') {
buttonProps.type = type;
buttonProps.disabled = disabled;
} else {
if (ComponentProp !== 'a' || !other.href) {
buttonProps.role = 'button';
}
buttonProps['aria-disabled'] = disabled;
}
var handleUserRef = useForkRef(buttonRefProp, ref);
var handleOwnRef = useForkRef(focusVisibleRef, buttonRef);
var handleRef = useForkRef(handleUserRef, handleOwnRef);
return React.createElement(ComponentProp, _extends({
className: clsx(classes.root, className, focusVisible && [classes.focusVisible, focusVisibleClassName], disabled && classes.disabled),
onBlur: handleBlur,
onClick: onClick,
onFocus: handleFocus,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
onMouseDown: handleMouseDown,
onMouseLeave: handleMouseLeave,
onMouseUp: handleMouseUp,
onDragLeave: handleDragLeave,
onTouchEnd: handleTouchEnd,
onTouchMove: handleTouchMove,
onTouchStart: handleTouchStart,
ref: handleRef,
tabIndex: disabled ? -1 : tabIndex
}, buttonProps, other), children, !disableRipple && !disabled ? React.createElement(NoSsr, null, React.createElement(TouchRipple, _extends({
ref: rippleRef,
center: centerRipple
}, TouchRippleProps))) : null);
});
process.env.NODE_ENV !== "production" ? ButtonBase.propTypes = {
/**
* A ref for imperative actions.
* It currently only supports `focusVisible()` action.
*/
action: refType,
/**
* @ignore
*
* Use that prop to pass a ref to the native button component.
* @deprecated Use `ref` instead.
*/
buttonRef: refType,
/**
* If `true`, the ripples will be centered.
* They won't start at the cursor interaction position.
*/
centerRipple: PropTypes.bool,
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: elementTypeAcceptingRef,
/**
* If `true`, the base button will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the ripple effect will be disabled.
*
* ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
* to highlight the element by applying separate styles with the `focusVisibleClassName`.
*/
disableRipple: PropTypes.bool,
/**
* If `true`, the touch ripple effect will be disabled.
*/
disableTouchRipple: PropTypes.bool,
/**
* If `true`, the base button will have a keyboard focus ripple.
* `disableRipple` must also be `false`.
*/
focusRipple: PropTypes.bool,
/**
* This prop can help a person know which element has the keyboard focus.
* The class name will be applied when the element gain the focus through a keyboard interaction.
* It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).
* The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/master/explainer.md).
* A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components
* if needed.
*/
focusVisibleClassName: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* @ignore
*/
onClick: PropTypes.func,
/**
* @ignore
*/
onDragLeave: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* Callback fired when the component is focused with a keyboard.
* We trigger a `onFocus` callback too.
*/
onFocusVisible: PropTypes.func,
/**
* @ignore
*/
onKeyDown: PropTypes.func,
/**
* @ignore
*/
onKeyUp: PropTypes.func,
/**
* @ignore
*/
onMouseDown: PropTypes.func,
/**
* @ignore
*/
onMouseLeave: PropTypes.func,
/**
* @ignore
*/
onMouseUp: PropTypes.func,
/**
* @ignore
*/
onTouchEnd: PropTypes.func,
/**
* @ignore
*/
onTouchMove: PropTypes.func,
/**
* @ignore
*/
onTouchStart: PropTypes.func,
/**
* @ignore
*/
role: PropTypes.string,
/**
* @ignore
*/
tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Props applied to the `TouchRipple` element.
*/
TouchRippleProps: PropTypes.object,
/**
* Used to control the button's purpose.
* This prop passes the value to the `type` attribute of the native button component.
*/
type: PropTypes.oneOf(['submit', 'reset', 'button'])
} : void 0;
export default withStyles(styles, {
name: 'MuiButtonBase'
})(ButtonBase); |
ajax/libs/material-ui/4.9.3/es/MenuList/MenuList.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import ownerDocument from '../utils/ownerDocument';
import List from '../List';
import getScrollbarSize from '../utils/getScrollbarSize';
import useForkRef from '../utils/useForkRef';
function nextItem(list, item, disableListWrap) {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return disableListWrap ? null : list.firstChild;
}
function previousItem(list, item, disableListWrap) {
if (list === item) {
return disableListWrap ? list.firstChild : list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(nextFocus, textCriteria) {
if (textCriteria === undefined) {
return true;
}
let text = nextFocus.innerText;
if (text === undefined) {
// jsdom doesn't support innerText
text = nextFocus.textContent;
}
text = text.trim().toLowerCase();
if (text.length === 0) {
return false;
}
if (textCriteria.repeating) {
return text[0] === textCriteria.keys[0];
}
return text.indexOf(textCriteria.keys.join('')) === 0;
}
function moveFocus(list, currentFocus, disableListWrap, traversalFunction, textCriteria) {
let wrappedOnce = false;
let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);
while (nextFocus) {
// Prevent infinite loop.
if (nextFocus === list.firstChild) {
if (wrappedOnce) {
return false;
}
wrappedOnce = true;
} // Move to the next element.
if (!nextFocus.hasAttribute('tabindex') || nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true' || !textCriteriaMatches(nextFocus, textCriteria)) {
nextFocus = traversalFunction(list, nextFocus, disableListWrap);
} else {
nextFocus.focus();
return true;
}
}
return false;
}
const useEnhancedEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;
/**
* A permanently displayed menu following https://www.w3.org/TR/wai-aria-practices/#menubutton
* It's exposed to help customization of the [`Menu`](/api/menu/) component. If you
* use it separately you need to move focus into the component manually. Once
* the focus is placed inside the component it is fully keyboard accessible.
*/
const MenuList = React.forwardRef(function MenuList(props, ref) {
const {
actions,
autoFocus = false,
autoFocusItem = false,
children,
className,
onKeyDown,
disableListWrap = false,
variant = 'selectedMenu'
} = props,
other = _objectWithoutPropertiesLoose(props, ["actions", "autoFocus", "autoFocusItem", "children", "className", "onKeyDown", "disableListWrap", "variant"]);
const listRef = React.useRef(null);
const textCriteriaRef = React.useRef({
keys: [],
repeating: true,
previousKeyMatched: true,
lastTime: null
});
useEnhancedEffect(() => {
if (autoFocus) {
listRef.current.focus();
}
}, [autoFocus]);
React.useImperativeHandle(actions, () => ({
adjustStyleForScrollbar: (containerElement, theme) => {
// Let's ignore that piece of logic if users are already overriding the width
// of the menu.
const noExplicitWidth = !listRef.current.style.width;
if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
const scrollbarSize = `${getScrollbarSize(true)}px`;
listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;
listRef.current.style.width = `calc(100% + ${scrollbarSize})`;
}
return listRef.current;
}
}), []);
const handleKeyDown = event => {
const list = listRef.current;
const key = event.key;
/**
* @type {Element} - will always be defined since we are in a keydown handler
* attached to an element. A keydown event is either dispatched to the activeElement
* or document.body or document.documentElement. Only the first case will
* trigger this specific handler.
*/
const currentFocus = ownerDocument(list).activeElement;
if (key === 'ArrowDown') {
// Prevent scroll of the page
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, nextItem);
} else if (key === 'ArrowUp') {
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, previousItem);
} else if (key === 'Home') {
event.preventDefault();
moveFocus(list, null, disableListWrap, nextItem);
} else if (key === 'End') {
event.preventDefault();
moveFocus(list, null, disableListWrap, previousItem);
} else if (key.length === 1) {
const criteria = textCriteriaRef.current;
const lowerKey = key.toLowerCase();
const currTime = performance.now();
if (criteria.keys.length > 0) {
// Reset
if (currTime - criteria.lastTime > 500) {
criteria.keys = [];
criteria.repeating = true;
criteria.previousKeyMatched = true;
} else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
criteria.repeating = false;
}
}
criteria.lastTime = currTime;
criteria.keys.push(lowerKey);
const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);
if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, nextItem, criteria))) {
event.preventDefault();
} else {
criteria.previousKeyMatched = false;
}
}
if (onKeyDown) {
onKeyDown(event);
}
};
const handleOwnRef = React.useCallback(instance => {
// #StrictMode ready
listRef.current = ReactDOM.findDOMNode(instance);
}, []);
const handleRef = useForkRef(handleOwnRef, ref);
/**
* the index of the item should receive focus
* in a `variant="selectedMenu"` it's the first `selected` item
* otherwise it's the very first item.
*/
let activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead
// to check if there is a `selected` item. We're looking for the last `selected`
// item and use the first valid item as a fallback
React.Children.forEach(children, (child, index) => {
if (!React.isValidElement(child)) {
return;
}
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(["Material-UI: the Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
if (!child.props.disabled) {
if (variant === 'selectedMenu' && child.props.selected) {
activeItemIndex = index;
} else if (activeItemIndex === -1) {
activeItemIndex = index;
}
}
});
const items = React.Children.map(children, (child, index) => {
if (index === activeItemIndex) {
const newChildProps = {};
if (autoFocusItem) {
newChildProps.autoFocus = true;
}
if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
newChildProps.tabIndex = 0;
}
if (newChildProps !== null) {
return React.cloneElement(child, newChildProps);
}
}
return child;
});
return React.createElement(List, _extends({
role: "menu",
ref: handleRef,
className: className,
onKeyDown: handleKeyDown,
tabIndex: autoFocus ? 0 : -1
}, other), items);
});
process.env.NODE_ENV !== "production" ? MenuList.propTypes = {
/**
* @ignore
*/
actions: PropTypes.shape({
current: PropTypes.object
}),
/**
* If `true`, will focus the `[role="menu"]` container and move into tab order
*/
autoFocus: PropTypes.bool,
/**
* If `true`, will focus the first menuitem if `variant="menu"` or selected item
* if `variant="selectedMenu"`
*/
autoFocusItem: PropTypes.bool,
/**
* MenuList contents, normally `MenuItem`s.
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the menu items will not wrap focus.
*/
disableListWrap: PropTypes.bool,
/**
* @ignore
*/
onKeyDown: PropTypes.func,
/**
* The variant to use. Use `menu` to prevent selected items from impacting the initial focus
* and the vertical alignment relative to the anchor element.
*/
variant: PropTypes.oneOf(['menu', 'selectedMenu'])
} : void 0;
export default MenuList; |
ajax/libs/react-native-web/0.17.3/exports/YellowBox/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
* 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.
*
*
*/
import React from 'react';
import UnimplementedView from '../../modules/UnimplementedView';
function YellowBox(props) {
return /*#__PURE__*/React.createElement(UnimplementedView, props);
}
YellowBox.ignoreWarnings = function () {};
export default YellowBox; |
ajax/libs/zingchart-react/3.1.1/zingchart-react.es.js | cdnjs/cdnjs | import React, { Component } from 'react';
var EVENT_NAMES = [
'history_back',
'history_forward',
'destroy',
'beforedestroy',
'animation_step',
'animation_start',
'animation_end',
'guide_mouseout',
'guide_mousemove',
'dataload',
'dataparse',
'modulesready',
'dataready',
'resize',
'swipe',
'mousewheel',
'render',
'complete',
'load',
'about_show',
'about_hide',
'error',
'reload',
'menu_item_click',
'beforezoom',
'node_mousedown',
'node_mouseover',
'node_mouseout',
'node_mouseup',
'plot_mouseout',
'plot_mouseup',
'node_click',
'plot_click',
'node_doubleclick',
'plot_doubleclick',
'gload',
'gcomplete',
'maps.zoom',
'plot_add',
'plot_remove',
'modify',
'plot_modify',
'node_set',
'node_add',
'node_remove',
'setdata',
'legend_minimize',
'legend_hide',
'legend_maximize',
'legend_show',
'source_show',
'source_hide',
'dataexport',
'legend_mouseover',
'legend_mouseout',
'legend_item_click',
'legend_marker_click',
'shape_mouseover',
'shape_mousedown',
'shape_mouseout',
'shape_mouseup',
'shape_mousemove',
'shape_click',
'shape_dblclick',
'label_mouseover',
'label_mousedown',
'label_mouseout',
'label_mouseup',
'label_mousemove',
'label_click',
'label_dblclick',
'feed_clear',
'feed_step',
'feed_interval_modify',
'feed_stop',
'feed_start',
'zoom',
'postzoom',
'heatmap.mousemove',
'zingchart.plugins.selection-tool.mouseup',
'zingchart.plugins.selection-tool.selection',
'zingchart.plugins.selection-tool.beforeselection'
];
var METHOD_NAMES = [
'exec',
'goback',
'goforward',
'showmenu',
'hidemenu',
'destroy',
'getrender',
'clear',
'reload',
'load',
'enable',
'disable',
'closemodal',
'openmodal',
'print',
'fullscreen',
'exitfullscreen',
'resize',
'plothide',
'showguide',
'hideguide',
'showtooltip',
'hidetooltip',
'clicknode',
'locktooltip',
'unlocktooltip',
'showhoverstate',
'showplot',
'togglesource',
'togglebugreport',
'toggleabout',
'toggleplot',
'getcharttype',
'getversion',
'get3dview',
'set3dview',
'getpage',
'setpage',
'unbinddocument',
'addmenuitem',
'resetguide',
'setguide',
'zingchart.render',
'getMapByGraphIndex',
'zoomIn',
'zoomOut',
'destroyMap',
'setView',
'viewAll',
'zoomToItem',
'zoomTo',
'getInfo',
'getItems',
'getItemInfo',
'getXY',
'getLonLat',
'clearscroll',
'getbubblesize',
'getscaleinfo',
'getobjectinfo',
'getxyinfo',
'update',
'setcharttype',
'addgraph',
'addplot',
'removeplot',
'modify',
'modifyplot',
'setnodevalue',
'setscalevalues',
'addscalevalue',
'removescalevalue',
'addnode',
'removenode',
'setdata',
'getseriesdata',
'setseriesdata',
'appendseriesdata',
'getseriesvalues',
'setseriesvalues',
'appendseriesvalues',
'togglelegend',
'legendminimize',
'legendmaximize',
'legendscroll',
'toggledimension',
'getdata',
'getoriginaljson',
'getgraphlength',
'getplotlength',
'getscales',
'getnodelength',
'getnodevalue',
'getplotvalues',
'getimagedata',
'exportimage',
'saveasimage',
'exportdata',
'downloadCSV',
'downloadXLS',
'downloadRAW',
'viewDataTable',
'addobject',
'removeobject',
'updateobject',
'repaintobjects',
'getallobjects',
'getobjectsbyclass',
'getlabelinfo',
'getshapeinfo',
'setobjectsmode',
'clearfeed',
'getinterval',
'setinterval',
'startfeed',
'stopfeed',
'clearselection',
'getselection',
'setselection',
'select',
'deselect',
'getzoom',
'pan',
'zoomin',
'zoomout',
'zoomto',
'zoomtovalues',
'viewall',
'removenote',
'updatenote',
'getnotes',
'addnote',
'addmarker',
'updatemarker',
'removemarker',
'addrule',
'removerule',
'updaterule',
'getrules',
'bubblepack.setdata',
'calendar_setvalues',
'colorscale.setvalue',
'colorscale.update',
'colorscale.clear',
'colorscale.getinfo',
'heatmap.setdata',
'loadGeoJSON',
'loadTopoJSON',
'resetscales',
'resetsetseriesdata',
'getscaleminmax',
'tree.addnode',
'tree.removenode',
'tree.getdata',
'set',
'tree.addlink',
'tree.removelink',
'updateNode',
'addNode',
'removeNode',
'bind',
'unbind'
];
var MARKER_NAMES = [
'square',
'parallelogram',
'trapezoid',
'circle',
'diamond',
'triangle',
'ellipse',
'star5',
'star6',
'star7',
'star8',
'rpoly5',
'rpoly6',
'rpoly7',
'rpoly8',
'gear5',
'gear6',
'gear7',
'gear8',
'pie',
];
var MISC = {
DEFAULT_WIDTH: '100%',
DEFAULT_HEIGHT: 480,
DEFAULT_OUTPUT: 'svg',
};
const {DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_OUTPUT} = MISC;
var constants = {
EVENT_NAMES,
METHOD_NAMES,
MARKER_NAMES,
DEFAULT_WIDTH,
DEFAULT_HEIGHT,
DEFAULT_OUTPUT,
};
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 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 DEFAULT_WIDTH$1 = constants.DEFAULT_WIDTH,
DEFAULT_HEIGHT$1 = constants.DEFAULT_HEIGHT,
DEFAULT_OUTPUT$1 = constants.DEFAULT_OUTPUT,
EVENT_NAMES$1 = constants.EVENT_NAMES,
METHOD_NAMES$1 = constants.METHOD_NAMES;
// One time setup globally to handle all zingchart-react objects in the app space.
if (!window.ZCReact) {
window.ZCReact = {
instances: {},
count: 0
};
}
var ZingChart = function (_Component) {
inherits(ZingChart, _Component);
function ZingChart(props) {
classCallCheck(this, ZingChart);
var _this = possibleConstructorReturn(this, (ZingChart.__proto__ || Object.getPrototypeOf(ZingChart)).call(this, props));
_this.id = _this.props.id || 'zingchart-react-' + window.ZCReact.count++;
console.log(props);
// Bind all methods available to zingchart to be accessed via Refs.
METHOD_NAMES$1.forEach(function (name) {
_this[name] = function (args) {
return window.zingchart.exec(_this.id, name, args);
};
});
_this.state = {
style: {
height: _this.props.height || DEFAULT_HEIGHT$1,
width: _this.props.width || DEFAULT_WIDTH$1
}
};
return _this;
}
createClass(ZingChart, [{
key: 'render',
value: function render() {
return React.createElement('div', { id: this.id, style: this.state.style });
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
// Bind all events registered.
Object.keys(this.props).forEach(function (eventName) {
if (EVENT_NAMES$1.includes(eventName)) {
// Filter through the provided events list, then register it to zingchart.
window.zingchart.bind(_this2.id, eventName, function (result) {
_this2.props[eventName](result);
});
}
});
this.renderChart();
}
// Used to check the values being passed in to avoid unnecessary changes.
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
// Data change
if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data)) {
zingchart.exec(this.id, 'setdata', {
data: nextProps.data
});
// Series change
} else if (JSON.stringify(nextProps.series) !== JSON.stringify(this.props.series)) {
zingchart.exec(this.id, 'setseriesdata', {
graphid: 0,
plotindex: 0,
data: nextProps.series
});
// Resize
} else if (nextProps.width !== this.props.width || nextProps.height !== this.props.height) {
this.setState({
style: {
width: nextProps.width || DEFAULT_WIDTH$1,
height: nextProps.height || DEFAULT_HEIGHT$1
}
});
zingchart.exec(this.id, 'resize', {
width: nextProps.width || DEFAULT_WIDTH$1,
height: nextProps.height || DEFAULT_HEIGHT$1
});
}
// React should never re-render since ZingChart controls this component.
return false;
}
}, {
key: 'renderChart',
value: function renderChart() {
var _this3 = this;
var renderObject = {};
Object.keys(this.props).forEach(function (prop) {
renderObject[prop] = _this3.props[prop];
});
// Overwrite some existing props.
renderObject.id = this.id;
renderObject.width = this.props.width || DEFAULT_WIDTH$1;
renderObject.height = this.props.height || DEFAULT_HEIGHT$1;
renderObject.data = this.props.data;
renderObject.output = this.props.output || DEFAULT_OUTPUT$1;
if (this.props.series) {
renderObject.data.series = this.props.series;
}
if (this.props.theme) {
renderObject.defaults = this.props.theme;
}
if (this.props.modules) {
renderObject.modules = this.props.modules;
}
zingchart.render(renderObject);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
zingchart.exec(this.id, 'destroy');
}
}]);
return ZingChart;
}(Component);
export default ZingChart;
//# sourceMappingURL=zingchart-react.es.js.map
|
ajax/libs/material-ui/4.9.3/esm/Badge/Badge.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
var RADIUS_STANDARD = 10;
var RADIUS_DOT = 4;
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
position: 'relative',
display: 'inline-flex',
// For correct alignment with the text.
verticalAlign: 'middle',
flexShrink: 0
},
/* Styles applied to the badge `span` element. */
badge: {
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center',
position: 'absolute',
boxSizing: 'border-box',
fontFamily: theme.typography.fontFamily,
fontWeight: theme.typography.fontWeightMedium,
fontSize: theme.typography.pxToRem(12),
minWidth: RADIUS_STANDARD * 2,
lineHeight: 1,
padding: '0 6px',
height: RADIUS_STANDARD * 2,
borderRadius: RADIUS_STANDARD,
zIndex: 1,
// Render the badge on top of potential ripples.
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeInOut,
duration: theme.transitions.duration.enteringScreen
})
},
/* Styles applied to the root element if `color="primary"`. */
colorPrimary: {
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText
},
/* Styles applied to the root element if `color="secondary"`. */
colorSecondary: {
backgroundColor: theme.palette.secondary.main,
color: theme.palette.secondary.contrastText
},
/* Styles applied to the root element if `color="error"`. */
colorError: {
backgroundColor: theme.palette.error.main,
color: theme.palette.error.contrastText
},
/* Styles applied to the root element if `variant="dot"`. */
dot: {
borderRadius: RADIUS_DOT,
height: RADIUS_DOT * 2,
minWidth: RADIUS_DOT * 2,
padding: 0
},
/* Styles applied to the root element if `anchorOrigin={{ 'top', 'right' }} overlap="rectangle"`. */
anchorOriginTopRightRectangle: {
top: 0,
right: 0,
transform: 'scale(1) translate(50%, -50%)',
transformOrigin: '100% 0%',
'&$invisible': {
transform: 'scale(0) translate(50%, -50%)'
}
},
/* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'right' }} overlap="rectangle"`. */
anchorOriginBottomRightRectangle: {
bottom: 0,
right: 0,
transform: 'scale(1) translate(50%, 50%)',
transformOrigin: '100% 100%',
'&$invisible': {
transform: 'scale(0) translate(50%, 50%)'
}
},
/* Styles applied to the root element if `anchorOrigin={{ 'top', 'left' }} overlap="rectangle"`. */
anchorOriginTopLeftRectangle: {
top: 0,
left: 0,
transform: 'scale(1) translate(-50%, -50%)',
transformOrigin: '0% 0%',
'&$invisible': {
transform: 'scale(0) translate(-50%, -50%)'
}
},
/* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'left' }} overlap="rectangle"`. */
anchorOriginBottomLeftRectangle: {
bottom: 0,
left: 0,
transform: 'scale(1) translate(-50%, 50%)',
transformOrigin: '0% 100%',
'&$invisible': {
transform: 'scale(0) translate(-50%, 50%)'
}
},
/* Styles applied to the root element if `anchorOrigin={{ 'top', 'right' }} overlap="circle"`. */
anchorOriginTopRightCircle: {
top: '14%',
right: '14%',
transform: 'scale(1) translate(50%, -50%)',
transformOrigin: '100% 0%',
'&$invisible': {
transform: 'scale(0) translate(50%, -50%)'
}
},
/* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'right' }} overlap="circle"`. */
anchorOriginBottomRightCircle: {
bottom: '14%',
right: '14%',
transform: 'scale(1) translate(50%, 50%)',
transformOrigin: '100% 100%',
'&$invisible': {
transform: 'scale(0) translate(50%, 50%)'
}
},
/* Styles applied to the root element if `anchorOrigin={{ 'top', 'left' }} overlap="circle"`. */
anchorOriginTopLeftCircle: {
top: '14%',
left: '14%',
transform: 'scale(1) translate(-50%, -50%)',
transformOrigin: '0% 0%',
'&$invisible': {
transform: 'scale(0) translate(-50%, -50%)'
}
},
/* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'left' }} overlap="circle"`. */
anchorOriginBottomLeftCircle: {
bottom: '14%',
left: '14%',
transform: 'scale(1) translate(-50%, 50%)',
transformOrigin: '0% 100%',
'&$invisible': {
transform: 'scale(0) translate(-50%, 50%)'
}
},
/* Pseudo-class to the badge `span` element if `invisible={true}`. */
invisible: {
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeInOut,
duration: theme.transitions.duration.leavingScreen
})
}
};
};
var Badge = React.forwardRef(function Badge(props, ref) {
var _props$anchorOrigin = props.anchorOrigin,
anchorOrigin = _props$anchorOrigin === void 0 ? {
vertical: 'top',
horizontal: 'right'
} : _props$anchorOrigin,
badgeContent = props.badgeContent,
children = props.children,
classes = props.classes,
className = props.className,
_props$color = props.color,
color = _props$color === void 0 ? 'default' : _props$color,
_props$component = props.component,
ComponentProp = _props$component === void 0 ? 'span' : _props$component,
invisibleProp = props.invisible,
_props$max = props.max,
max = _props$max === void 0 ? 99 : _props$max,
_props$overlap = props.overlap,
overlap = _props$overlap === void 0 ? 'rectangle' : _props$overlap,
_props$showZero = props.showZero,
showZero = _props$showZero === void 0 ? false : _props$showZero,
_props$variant = props.variant,
variant = _props$variant === void 0 ? 'standard' : _props$variant,
other = _objectWithoutProperties(props, ["anchorOrigin", "badgeContent", "children", "classes", "className", "color", "component", "invisible", "max", "overlap", "showZero", "variant"]);
var invisible = invisibleProp;
if (invisibleProp == null && (badgeContent === 0 && !showZero || badgeContent == null && variant !== 'dot')) {
invisible = true;
}
var displayValue = '';
if (variant !== 'dot') {
displayValue = badgeContent > max ? "".concat(max, "+") : badgeContent;
}
return React.createElement(ComponentProp, _extends({
className: clsx(classes.root, className),
ref: ref
}, other), children, React.createElement("span", {
className: clsx(classes.badge, classes["".concat(anchorOrigin.horizontal).concat(capitalize(anchorOrigin.vertical), "}")], classes["anchorOrigin".concat(capitalize(anchorOrigin.vertical)).concat(capitalize(anchorOrigin.horizontal)).concat(capitalize(overlap))], color !== 'default' && classes["color".concat(capitalize(color))], invisible && classes.invisible, variant === 'dot' && classes.dot)
}, displayValue));
});
process.env.NODE_ENV !== "production" ? Badge.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The anchor of the badge.
*/
anchorOrigin: PropTypes.shape({
horizontal: PropTypes.oneOf(['left', 'right']).isRequired,
vertical: PropTypes.oneOf(['bottom', 'top']).isRequired
}),
/**
* The content rendered within the badge.
*/
badgeContent: PropTypes.node,
/**
* The badge will be added relative to this node.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['default', 'error', 'primary', 'secondary']),
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, the badge will be invisible.
*/
invisible: PropTypes.bool,
/**
* Max count to show.
*/
max: PropTypes.number,
/**
* Wrapped shape the badge should overlap.
*/
overlap: PropTypes.oneOf(['circle', 'rectangle']),
/**
* Controls whether the badge is hidden when `badgeContent` is zero.
*/
showZero: PropTypes.bool,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['dot', 'standard'])
} : void 0;
export default withStyles(styles, {
name: 'MuiBadge'
})(Badge); |
ajax/libs/react-native-web/0.0.0-e886427e3/modules/UnimplementedView/index.js | cdnjs/cdnjs | function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* 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.
*
*
*/
import View from '../../exports/View';
import React from 'react';
/**
* Common implementation for a simple stubbed view.
*/
var UnimplementedView = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(UnimplementedView, _React$Component);
function UnimplementedView() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = UnimplementedView.prototype;
_proto.setNativeProps = function setNativeProps() {// Do nothing.
};
_proto.render = function render() {
return /*#__PURE__*/React.createElement(View, {
style: [unimplementedViewStyles, this.props.style]
}, this.props.children);
};
return UnimplementedView;
}(React.Component);
var unimplementedViewStyles = process.env.NODE_ENV !== 'production' ? {
alignSelf: 'flex-start',
borderColor: 'red',
borderWidth: 1
} : {};
export default UnimplementedView; |
ajax/libs/react-native-web/0.13.10/exports/YellowBox/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
* 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.
*
*
*/
import React from 'react';
import UnimplementedView from '../../modules/UnimplementedView';
function YellowBox(props) {
return React.createElement(UnimplementedView, props);
}
YellowBox.ignoreWarnings = function () {};
export default YellowBox; |
ajax/libs/material-ui/4.9.10/es/RootRef/RootRef.js | cdnjs/cdnjs | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { exactProp, refType } from '@material-ui/utils';
import setRef from '../utils/setRef';
/**
* ⚠️⚠️⚠️
* If you want the DOM element of a Material-UI component check out
* [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element)
* first.
*
* This component uses `findDOMNode` which is deprecated in React.StrictMode.
*
* Helper component to allow attaching a ref to a
* wrapped element to access the underlying DOM element.
*
* It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801.
* For example:
* ```jsx
* import React from 'react';
* import RootRef from '@material-ui/core/RootRef';
*
* function MyComponent() {
* const domRef = React.useRef();
*
* React.useEffect(() => {
* console.log(domRef.current); // DOM node
* }, []);
*
* return (
* <RootRef rootRef={domRef}>
* <SomeChildComponent />
* </RootRef>
* );
* }
* ```
*/
class RootRef extends React.Component {
componentDidMount() {
this.ref = ReactDOM.findDOMNode(this);
setRef(this.props.rootRef, this.ref);
}
componentDidUpdate(prevProps) {
const ref = ReactDOM.findDOMNode(this);
if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) {
if (prevProps.rootRef !== this.props.rootRef) {
setRef(prevProps.rootRef, null);
}
this.ref = ref;
setRef(this.props.rootRef, this.ref);
}
}
componentWillUnmount() {
this.ref = null;
setRef(this.props.rootRef, null);
}
render() {
return this.props.children;
}
}
process.env.NODE_ENV !== "production" ? RootRef.propTypes = {
/**
* The wrapped element.
*/
children: PropTypes.element.isRequired,
/**
* A ref that points to the first DOM node of the wrapped element.
*/
rootRef: refType.isRequired
} : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? RootRef.propTypes = exactProp(RootRef.propTypes) : void 0;
}
export default RootRef; |
ajax/libs/react-native-web/0.0.0-7cbe1609b/vendor/react-native/Animated/createAnimatedComponent.js | cdnjs/cdnjs | /**
* Copyright (c) 2015-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.
*
*
* @format
*/
'use strict';
function _extends() { _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; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import { AnimatedEvent } from './AnimatedEvent';
import AnimatedProps from './nodes/AnimatedProps';
import React from 'react';
import invariant from 'fbjs/lib/invariant';
import mergeRefs from '../../../modules/mergeRefs';
function createAnimatedComponent(Component, defaultProps) {
invariant(typeof Component !== 'function' || Component.prototype && Component.prototype.isReactComponent, '`createAnimatedComponent` does not support stateless functional components; ' + 'use a class component instead.');
var AnimatedComponent =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(AnimatedComponent, _React$Component);
function AnimatedComponent(props) {
var _this;
_this = _React$Component.call(this, props) || this;
_this._invokeAnimatedPropsCallbackOnMount = false;
_this._eventDetachers = [];
_this._animatedPropsCallback = function () {
if (_this._component == null) {
// AnimatedProps is created in will-mount because it's used in render.
// But this callback may be invoked before mount in async mode,
// In which case we should defer the setNativeProps() call.
// React may throw away uncommitted work in async mode,
// So a deferred call won't always be invoked.
_this._invokeAnimatedPropsCallbackOnMount = true;
} else if (AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY || typeof _this._component.setNativeProps !== 'function') {
_this.forceUpdate();
} else if (!_this._propsAnimated.__isNative) {
_this._component.setNativeProps(_this._propsAnimated.__getAnimatedValue());
} else {
throw new Error('Attempting to run JS driven animation on animated ' + 'node that has been moved to "native" earlier by starting an ' + 'animation with `useNativeDriver: true`');
}
};
_this._setComponentRef = mergeRefs(_this.props.forwardedRef, function (ref) {
_this._prevComponent = _this._component;
_this._component = ref; // TODO: Delete this in a future release.
if (ref != null && ref.getNode == null) {
ref.getNode = function () {
var _ref$constructor$name;
console.warn('%s: Calling `getNode()` on the ref of an Animated component ' + 'is no longer necessary. You can now directly use the ref ' + 'instead. This method will be removed in a future release.', (_ref$constructor$name = ref.constructor.name) !== null && _ref$constructor$name !== void 0 ? _ref$constructor$name : '<<anonymous>>');
return ref;
};
}
});
return _this;
}
var _proto = AnimatedComponent.prototype;
_proto.componentWillUnmount = function componentWillUnmount() {
this._propsAnimated && this._propsAnimated.__detach();
this._detachNativeEvents();
};
_proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() {
this._attachProps(this.props);
};
_proto.componentDidMount = function componentDidMount() {
if (this._invokeAnimatedPropsCallbackOnMount) {
this._invokeAnimatedPropsCallbackOnMount = false;
this._animatedPropsCallback();
}
this._propsAnimated.setNativeView(this._component);
this._attachNativeEvents();
};
_proto._attachNativeEvents = function _attachNativeEvents() {
var _this2 = this;
// Make sure to get the scrollable node for components that implement
// `ScrollResponder.Mixin`.
var scrollableNode = this._component && this._component.getScrollableNode ? this._component.getScrollableNode() : this._component;
var _loop = function _loop(key) {
var prop = _this2.props[key];
if (prop instanceof AnimatedEvent && prop.__isNative) {
prop.__attach(scrollableNode, key);
_this2._eventDetachers.push(function () {
return prop.__detach(scrollableNode, key);
});
}
};
for (var key in this.props) {
_loop(key);
}
};
_proto._detachNativeEvents = function _detachNativeEvents() {
this._eventDetachers.forEach(function (remove) {
return remove();
});
this._eventDetachers = [];
} // The system is best designed when setNativeProps is implemented. It is
// able to avoid re-rendering and directly set the attributes that changed.
// However, setNativeProps can only be implemented on leaf native
// components. If you want to animate a composite component, you need to
// re-render it. In this case, we have a fallback that uses forceUpdate.
;
_proto._attachProps = function _attachProps(nextProps) {
var oldPropsAnimated = this._propsAnimated;
this._propsAnimated = new AnimatedProps(nextProps, this._animatedPropsCallback); // When you call detach, it removes the element from the parent list
// of children. If it goes to 0, then the parent also detaches itself
// and so on.
// An optimization is to attach the new elements and THEN detach the old
// ones instead of detaching and THEN attaching.
// This way the intermediate state isn't to go to 0 and trigger
// this expensive recursive detaching to then re-attach everything on
// the very next operation.
oldPropsAnimated && oldPropsAnimated.__detach();
};
_proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(newProps) {
this._attachProps(newProps);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
if (this._component !== this._prevComponent) {
this._propsAnimated.setNativeView(this._component);
}
if (this._component !== this._prevComponent || prevProps !== this.props) {
this._detachNativeEvents();
this._attachNativeEvents();
}
};
_proto.render = function render() {
var props = this._propsAnimated.__getValue();
return React.createElement(Component, _extends({}, defaultProps, props, {
ref: this._setComponentRef // The native driver updates views directly through the UI thread so we
// have to make sure the view doesn't get optimized away because it cannot
// go through the NativeViewHierarchyManager since it operates on the shadow
// thread.
,
collapsable: false
}));
};
return AnimatedComponent;
}(React.Component);
AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY = false;
var propTypes = Component.propTypes;
return React.forwardRef(function AnimatedComponentWrapper(props, ref) {
return React.createElement(AnimatedComponent, _extends({}, props, ref == null ? null : {
forwardedRef: ref
}));
});
}
export default createAnimatedComponent; |
ajax/libs/material-ui/4.9.4/es/ExpansionPanelSummary/ExpansionPanelSummary.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
/* eslint-disable jsx-a11y/aria-role */
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import ButtonBase from '../ButtonBase';
import IconButton from '../IconButton';
import withStyles from '../styles/withStyles';
import ExpansionPanelContext from '../ExpansionPanel/ExpansionPanelContext';
export const styles = theme => {
const transition = {
duration: theme.transitions.duration.shortest
};
return {
/* Styles applied to the root element. */
root: {
display: 'flex',
minHeight: 8 * 6,
transition: theme.transitions.create(['min-height', 'background-color'], transition),
padding: '0 24px 0 24px',
'&:hover:not($disabled)': {
cursor: 'pointer'
},
'&$expanded': {
minHeight: 64
},
'&$focused': {
backgroundColor: theme.palette.grey[300]
},
'&$disabled': {
opacity: 0.38
}
},
/* Pseudo-class applied to the root element, children wrapper element and `IconButton` component if `expanded={true}`. */
expanded: {},
/* Pseudo-class applied to the root element if `focused={true}`. */
focused: {},
/* Pseudo-class applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the children wrapper element. */
content: {
display: 'flex',
flexGrow: 1,
transition: theme.transitions.create(['margin'], transition),
margin: '12px 0',
'&$expanded': {
margin: '20px 0'
}
},
/* Styles applied to the `IconButton` component when `expandIcon` is supplied. */
expandIcon: {
transform: 'rotate(0deg)',
transition: theme.transitions.create('transform', transition),
'&:hover': {
// Disable the hover effect for the IconButton,
// because a hover effect should apply to the entire Expand button and
// not only to the IconButton.
backgroundColor: 'transparent'
},
'&$expanded': {
transform: 'rotate(180deg)'
}
}
};
};
const ExpansionPanelSummary = React.forwardRef(function ExpansionPanelSummary(props, ref) {
const {
children,
classes,
className,
expandIcon,
IconButtonProps,
onBlur,
onClick,
onFocusVisible
} = props,
other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "expandIcon", "IconButtonProps", "onBlur", "onClick", "onFocusVisible"]);
const [focusedState, setFocusedState] = React.useState(false);
const handleFocusVisible = event => {
setFocusedState(true);
if (onFocusVisible) {
onFocusVisible(event);
}
};
const handleBlur = event => {
setFocusedState(false);
if (onBlur) {
onBlur(event);
}
};
const {
disabled = false,
expanded,
toggle
} = React.useContext(ExpansionPanelContext);
const handleChange = event => {
if (toggle) {
toggle(event);
}
if (onClick) {
onClick(event);
}
};
return React.createElement(ButtonBase, _extends({
focusRipple: false,
disableRipple: true,
disabled: disabled,
component: "div",
"aria-expanded": expanded,
className: clsx(classes.root, className, disabled && classes.disabled, expanded && classes.expanded, focusedState && classes.focused),
onFocusVisible: handleFocusVisible,
onBlur: handleBlur,
onClick: handleChange,
ref: ref
}, other), React.createElement("div", {
className: clsx(classes.content, expanded && classes.expanded)
}, children), expandIcon && React.createElement(IconButton, _extends({
className: clsx(classes.expandIcon, expanded && classes.expanded),
edge: "end",
component: "div",
tabIndex: null,
role: null,
"aria-hidden": true
}, IconButtonProps), expandIcon));
});
process.env.NODE_ENV !== "production" ? ExpansionPanelSummary.propTypes = {
/**
* The content of the expansion panel summary.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The icon to display as the expand indicator.
*/
expandIcon: PropTypes.node,
/**
* Props applied to the `IconButton` element wrapping the expand icon.
*/
IconButtonProps: PropTypes.object,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* @ignore
*/
onClick: PropTypes.func,
/**
* @ignore
*/
onFocusVisible: PropTypes.func
} : void 0;
export default withStyles(styles, {
name: 'MuiExpansionPanelSummary'
})(ExpansionPanelSummary); |
ajax/libs/primereact/6.6.0/gmap/gmap.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var GMap = /*#__PURE__*/function (_Component) {
_inherits(GMap, _Component);
var _super = _createSuper(GMap);
function GMap() {
_classCallCheck(this, GMap);
return _super.apply(this, arguments);
}
_createClass(GMap, [{
key: "initMap",
value: function initMap() {
this.map = new google.maps.Map(this.container, this.props.options);
if (this.props.onMapReady) {
this.props.onMapReady({
map: this.map
});
}
this.initOverlays(this.props.overlays);
this.bindMapEvent('click', this.props.onMapClick);
this.bindMapEvent('dragend', this.props.onMapDragEnd);
this.bindMapEvent('zoom_changed', this.props.onZoomChanged);
}
}, {
key: "initOverlays",
value: function initOverlays(overlays) {
if (overlays) {
var _iterator = _createForOfIteratorHelper(overlays),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var overlay = _step.value;
overlay.setMap(this.map);
this.bindOverlayEvents(overlay);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
}
}, {
key: "bindOverlayEvents",
value: function bindOverlayEvents(overlay) {
var _this = this;
overlay.addListener('click', function (event) {
if (_this.props.onOverlayClick) {
_this.props.onOverlayClick({
originalEvent: event,
overlay: overlay,
map: _this.map
});
}
});
if (overlay.getDraggable()) {
this.bindDragEvents(overlay);
}
}
}, {
key: "bindDragEvents",
value: function bindDragEvents(overlay) {
this.bindDragEvent(overlay, 'dragstart', this.props.onOverlayDragStart);
this.bindDragEvent(overlay, 'drag', this.props.onOverlayDrag);
this.bindDragEvent(overlay, 'dragend', this.props.onOverlayDragEnd);
}
}, {
key: "bindMapEvent",
value: function bindMapEvent(eventName, callback) {
this.map.addListener(eventName, function (event) {
if (callback) {
callback(event);
}
});
}
}, {
key: "bindDragEvent",
value: function bindDragEvent(overlay, eventName, callback) {
var _this2 = this;
overlay.addListener(eventName, function (event) {
if (callback) {
callback({
originalEvent: event,
overlay: overlay,
map: _this2.map
});
}
});
}
}, {
key: "getMap",
value: function getMap() {
return this.map;
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState, snapshot) {
if (prevProps.overlays !== this.props.overlays) {
if (prevProps.overlays) {
var _iterator2 = _createForOfIteratorHelper(prevProps.overlays),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var overlay = _step2.value;
google.maps.event.clearInstanceListeners(overlay);
overlay.setMap(null);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
this.initOverlays(this.props.overlays);
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
this.initMap();
}
}, {
key: "render",
value: function render() {
var _this3 = this;
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this3.container = el;
},
style: this.props.style,
className: this.props.className
});
}
}]);
return GMap;
}(Component);
_defineProperty(GMap, "defaultProps", {
options: null,
overlays: null,
style: null,
className: null,
onMapReady: null,
onMapClick: null,
onMapDragEnd: null,
onZoomChanged: null,
onOverlayDragStart: null,
onOverlayDrag: null,
onOverlayDragEnd: null,
onOverlayClick: null
});
export { GMap };
|
ajax/libs/material-ui/4.9.4/es/FilledInput/FilledInput.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import InputBase from '../InputBase';
import withStyles from '../styles/withStyles';
export const styles = theme => {
const light = theme.palette.type === 'light';
const bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';
const backgroundColor = light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)';
return {
/* Styles applied to the root element. */
root: {
position: 'relative',
backgroundColor,
borderTopLeftRadius: theme.shape.borderRadius,
borderTopRightRadius: theme.shape.borderRadius,
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shorter,
easing: theme.transitions.easing.easeOut
}),
'&:hover': {
backgroundColor: light ? 'rgba(0, 0, 0, 0.13)' : 'rgba(255, 255, 255, 0.13)',
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor
}
},
'&$focused': {
backgroundColor: light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)'
},
'&$disabled': {
backgroundColor: light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)'
}
},
/* Styles applied to the root element if color secondary. */
colorSecondary: {
'&$underline:after': {
borderBottomColor: theme.palette.secondary.main
}
},
/* Styles applied to the root element if `disableUnderline={false}`. */
underline: {
'&:after': {
borderBottom: `2px solid ${theme.palette.primary.main}`,
left: 0,
bottom: 0,
// Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
content: '""',
position: 'absolute',
right: 0,
transform: 'scaleX(0)',
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shorter,
easing: theme.transitions.easing.easeOut
}),
pointerEvents: 'none' // Transparent to the hover style.
},
'&$focused:after': {
transform: 'scaleX(1)'
},
'&$error:after': {
borderBottomColor: theme.palette.error.main,
transform: 'scaleX(1)' // error is always underlined in red
},
'&:before': {
borderBottom: `1px solid ${bottomLineColor}`,
left: 0,
bottom: 0,
// Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
content: '"\\00a0"',
position: 'absolute',
right: 0,
transition: theme.transitions.create('border-bottom-color', {
duration: theme.transitions.duration.shorter
}),
pointerEvents: 'none' // Transparent to the hover style.
},
'&:hover:before': {
borderBottom: `1px solid ${theme.palette.text.primary}`
},
'&$disabled:before': {
borderBottomStyle: 'dotted'
}
},
/* Pseudo-class applied to the root element if the component is focused. */
focused: {},
/* Pseudo-class applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if `startAdornment` is provided. */
adornedStart: {
paddingLeft: 12
},
/* Styles applied to the root element if `endAdornment` is provided. */
adornedEnd: {
paddingRight: 12
},
/* Pseudo-class applied to the root element if `error={true}`. */
error: {},
/* Styles applied to the `input` element if `margin="dense"`. */
marginDense: {},
/* Styles applied to the root element if `multiline={true}`. */
multiline: {
padding: '27px 12px 10px',
'&$marginDense': {
paddingTop: 23,
paddingBottom: 6
}
},
/* Styles applied to the `input` element. */
input: {
padding: '27px 12px 10px',
'&:-webkit-autofill': {
WebkitBoxShadow: theme.palette.type === 'dark' ? '0 0 0 100px #266798 inset' : null,
WebkitTextFillColor: theme.palette.type === 'dark' ? '#fff' : null,
borderTopLeftRadius: 'inherit',
borderTopRightRadius: 'inherit'
}
},
/* Styles applied to the `input` element if `margin="dense"`. */
inputMarginDense: {
paddingTop: 23,
paddingBottom: 6
},
/* Styles applied to the `input` if in `<FormControl hiddenLabel />`. */
inputHiddenLabel: {
paddingTop: 18,
paddingBottom: 19,
'&$inputMarginDense': {
paddingTop: 10,
paddingBottom: 11
}
},
/* Styles applied to the `input` element if `multiline={true}`. */
inputMultiline: {
padding: 0
},
/* Styles applied to the `input` element if `startAdornment` is provided. */
inputAdornedStart: {
paddingLeft: 0
},
/* Styles applied to the `input` element if `endAdornment` is provided. */
inputAdornedEnd: {
paddingRight: 0
}
};
};
const FilledInput = React.forwardRef(function FilledInput(props, ref) {
const {
disableUnderline,
classes,
fullWidth = false,
inputComponent = 'input',
multiline = false,
type = 'text'
} = props,
other = _objectWithoutPropertiesLoose(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]);
return React.createElement(InputBase, _extends({
classes: _extends({}, classes, {
root: clsx(classes.root, !disableUnderline && classes.underline),
underline: null
}),
fullWidth: fullWidth,
inputComponent: inputComponent,
multiline: multiline,
ref: ref,
type: type
}, other));
});
process.env.NODE_ENV !== "production" ? FilledInput.propTypes = {
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element will be focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The CSS class name of the wrapper element.
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['primary', 'secondary']),
/**
* The default `input` element value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the `input` element will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the input will not have an underline.
*/
disableUnderline: PropTypes.bool,
/**
* End `InputAdornment` for this component.
*/
endAdornment: PropTypes.node,
/**
* If `true`, the input will indicate an error. This is normally obtained via context from
* FormControl.
*/
error: PropTypes.bool,
/**
* If `true`, the input will take up the full width of its container.
*/
fullWidth: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* The component used for the native input.
* Either a string to use a DOM element or a component.
*/
inputComponent: PropTypes.elementType,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
*/
margin: PropTypes.oneOf(['dense', 'none']),
/**
* If `true`, a textarea element will be rendered.
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* Callback fired when the value is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The short hint displayed in the input before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element will be required.
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Start `InputAdornment` for this component.
*/
startAdornment: PropTypes.node,
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
*/
type: PropTypes.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any
} : void 0;
FilledInput.muiName = 'Input';
export default withStyles(styles, {
name: 'MuiFilledInput'
})(FilledInput); |
ajax/libs/material-ui/4.9.4/esm/ListItemText/ListItemText.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import Typography from '../Typography';
import ListContext from '../List/ListContext';
export var styles = {
/* Styles applied to the root element. */
root: {
flex: '1 1 auto',
minWidth: 0,
marginTop: 4,
marginBottom: 4
},
/* Styles applied to the `Typography` components if primary and secondary are set. */
multiline: {
marginTop: 6,
marginBottom: 6
},
/* Styles applied to the `Typography` components if dense. */
dense: {},
/* Styles applied to the root element if `inset={true}`. */
inset: {
paddingLeft: 56
},
/* Styles applied to the primary `Typography` component. */
primary: {},
/* Styles applied to the secondary `Typography` component. */
secondary: {}
};
var ListItemText = React.forwardRef(function ListItemText(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$disableTypogra = props.disableTypography,
disableTypography = _props$disableTypogra === void 0 ? false : _props$disableTypogra,
_props$inset = props.inset,
inset = _props$inset === void 0 ? false : _props$inset,
primaryProp = props.primary,
primaryTypographyProps = props.primaryTypographyProps,
secondaryProp = props.secondary,
secondaryTypographyProps = props.secondaryTypographyProps,
other = _objectWithoutProperties(props, ["children", "classes", "className", "disableTypography", "inset", "primary", "primaryTypographyProps", "secondary", "secondaryTypographyProps"]);
var _React$useContext = React.useContext(ListContext),
dense = _React$useContext.dense;
var primary = primaryProp != null ? primaryProp : children;
if (primary != null && primary.type !== Typography && !disableTypography) {
primary = React.createElement(Typography, _extends({
variant: dense ? 'body2' : 'body1',
className: classes.primary,
component: "span"
}, primaryTypographyProps), primary);
}
var secondary = secondaryProp;
if (secondary != null && secondary.type !== Typography && !disableTypography) {
secondary = React.createElement(Typography, _extends({
variant: "body2",
className: classes.secondary,
color: "textSecondary"
}, secondaryTypographyProps), secondary);
}
return React.createElement("div", _extends({
className: clsx(classes.root, className, dense && classes.dense, inset && classes.inset, primary && secondary && classes.multiline),
ref: ref
}, other), primary, secondary);
});
process.env.NODE_ENV !== "production" ? ListItemText.propTypes = {
/**
* Alias for the `primary` property.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the children won't be wrapped by a Typography component.
* This can be useful to render an alternative Typography variant by wrapping
* the `children` (or `primary`) text, and optional `secondary` text
* with the Typography component.
*/
disableTypography: PropTypes.bool,
/**
* If `true`, the children will be indented.
* This should be used if there is no left avatar or left icon.
*/
inset: PropTypes.bool,
/**
* The main content element.
*/
primary: PropTypes.node,
/**
* These props will be forwarded to the primary typography component
* (as long as disableTypography is not `true`).
*/
primaryTypographyProps: PropTypes.object,
/**
* The secondary content element.
*/
secondary: PropTypes.node,
/**
* These props will be forwarded to the secondary typography component
* (as long as disableTypography is not `true`).
*/
secondaryTypographyProps: PropTypes.object
} : void 0;
export default withStyles(styles, {
name: 'MuiListItemText'
})(ListItemText); |
ajax/libs/material-ui/4.9.2/es/internal/svg-icons/RadioButtonChecked.js | cdnjs/cdnjs | import React from 'react';
import createSvgIcon from './createSvgIcon';
/**
* @ignore - internal component.
*/
export default createSvgIcon(React.createElement("path", {
d: "M8.465 8.465C9.37 7.56 10.62 7 12 7C14.76 7 17 9.24 17 12C17 13.38 16.44 14.63 15.535 15.535C14.63 16.44 13.38 17 12 17C9.24 17 7 14.76 7 12C7 10.62 7.56 9.37 8.465 8.465Z"
}), 'RadioButtonChecked'); |
ajax/libs/material-ui/4.9.4/esm/Checkbox/Checkbox.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import SwitchBase from '../internal/SwitchBase';
import CheckBoxOutlineBlankIcon from '../internal/svg-icons/CheckBoxOutlineBlank';
import CheckBoxIcon from '../internal/svg-icons/CheckBox';
import { fade } from '../styles/colorManipulator';
import IndeterminateCheckBoxIcon from '../internal/svg-icons/IndeterminateCheckBox';
import capitalize from '../utils/capitalize';
import withStyles from '../styles/withStyles';
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
color: theme.palette.text.secondary
},
/* Pseudo-class applied to the root element if `checked={true}`. */
checked: {},
/* Pseudo-class applied to the root element if `disabled={true}`. */
disabled: {},
/* Pseudo-class applied to the root element if `indeterminate={true}`. */
indeterminate: {},
/* Styles applied to the root element if `color="primary"`. */
colorPrimary: {
'&$checked': {
color: theme.palette.primary.main,
'&:hover': {
backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
'&$disabled': {
color: theme.palette.action.disabled
}
},
/* Styles applied to the root element if `color="secondary"`. */
colorSecondary: {
'&$checked': {
color: theme.palette.secondary.main,
'&:hover': {
backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
'&$disabled': {
color: theme.palette.action.disabled
}
}
};
};
var defaultCheckedIcon = React.createElement(CheckBoxIcon, null);
var defaultIcon = React.createElement(CheckBoxOutlineBlankIcon, null);
var defaultIndeterminateIcon = React.createElement(IndeterminateCheckBoxIcon, null);
var Checkbox = React.forwardRef(function Checkbox(props, ref) {
var _props$checkedIcon = props.checkedIcon,
checkedIcon = _props$checkedIcon === void 0 ? defaultCheckedIcon : _props$checkedIcon,
classes = props.classes,
_props$color = props.color,
color = _props$color === void 0 ? 'secondary' : _props$color,
_props$icon = props.icon,
icon = _props$icon === void 0 ? defaultIcon : _props$icon,
_props$indeterminate = props.indeterminate,
indeterminate = _props$indeterminate === void 0 ? false : _props$indeterminate,
_props$indeterminateI = props.indeterminateIcon,
indeterminateIcon = _props$indeterminateI === void 0 ? defaultIndeterminateIcon : _props$indeterminateI,
inputProps = props.inputProps,
_props$size = props.size,
size = _props$size === void 0 ? 'medium' : _props$size,
other = _objectWithoutProperties(props, ["checkedIcon", "classes", "color", "icon", "indeterminate", "indeterminateIcon", "inputProps", "size"]);
return React.createElement(SwitchBase, _extends({
type: "checkbox",
classes: {
root: clsx(classes.root, classes["color".concat(capitalize(color))], indeterminate && classes.indeterminate),
checked: classes.checked,
disabled: classes.disabled
},
color: color,
inputProps: _extends({
'data-indeterminate': indeterminate
}, inputProps),
icon: React.cloneElement(indeterminate ? indeterminateIcon : icon, {
fontSize: size === 'small' ? 'small' : 'default'
}),
checkedIcon: React.cloneElement(indeterminate ? indeterminateIcon : checkedIcon, {
fontSize: size === 'small' ? 'small' : 'default'
}),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? Checkbox.propTypes = {
/**
* If `true`, the component is checked.
*/
checked: PropTypes.bool,
/**
* The icon to display when the component is checked.
*/
checkedIcon: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['primary', 'secondary', 'default']),
/**
* If `true`, the checkbox will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the ripple effect will be disabled.
*/
disableRipple: PropTypes.bool,
/**
* The icon to display when the component is unchecked.
*/
icon: PropTypes.node,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* If `true`, the component appears indeterminate.
* This does not set the native input element to indeterminate due
* to inconsistent behavior across browsers.
* However, we set a `data-indeterminate` attribute on the input.
*/
indeterminate: PropTypes.bool,
/**
* The icon to display when the component is indeterminate.
*/
indeterminateIcon: PropTypes.node,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* Callback fired when the state is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new checked state by accessing `event.target.checked` (boolean).
*/
onChange: PropTypes.func,
/**
* If `true`, the `input` element will be required.
*/
required: PropTypes.bool,
/**
* The size of the checkbox.
* `small` is equivalent to the dense checkbox styling.
*/
size: PropTypes.oneOf(['small', 'medium']),
/**
* The input component prop `type`.
*/
type: PropTypes.string,
/**
* The value of the component. The DOM API casts this to a string.
*/
value: PropTypes.any
} : void 0;
export default withStyles(styles, {
name: 'MuiCheckbox'
})(Checkbox); |
ajax/libs/primereact/7.0.0-rc.1/deferredcontent/deferredcontent.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var DeferredContent = /*#__PURE__*/function (_Component) {
_inherits(DeferredContent, _Component);
var _super = _createSuper(DeferredContent);
function DeferredContent(props) {
var _this;
_classCallCheck(this, DeferredContent);
_this = _super.call(this, props);
_this.state = {
loaded: false
};
return _this;
}
_createClass(DeferredContent, [{
key: "componentDidMount",
value: function componentDidMount() {
if (!this.state.loaded) {
if (this.shouldLoad()) this.load();else this.bindScrollListener();
}
}
}, {
key: "bindScrollListener",
value: function bindScrollListener() {
var _this2 = this;
this.documentScrollListener = function () {
if (_this2.shouldLoad()) {
_this2.load();
_this2.unbindScrollListener();
}
};
window.addEventListener('scroll', this.documentScrollListener);
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.documentScrollListener) {
window.removeEventListener('scroll', this.documentScrollListener);
this.documentScrollListener = null;
}
}
}, {
key: "shouldLoad",
value: function shouldLoad() {
if (this.state.loaded) {
return false;
} else {
var rect = this.container.getBoundingClientRect();
var docElement = document.documentElement;
var winHeight = docElement.clientHeight;
return winHeight >= rect.top;
}
}
}, {
key: "load",
value: function load(event) {
this.setState({
loaded: true
});
if (this.props.onLoad) {
this.props.onLoad(event);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindScrollListener();
}
}, {
key: "render",
value: function render() {
var _this3 = this;
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this3.container = el;
}
}, this.state.loaded ? this.props.children : null);
}
}]);
return DeferredContent;
}(Component);
_defineProperty(DeferredContent, "defaultProps", {
onload: null
});
export { DeferredContent };
|
ajax/libs/material-ui/4.9.2/es/RadioGroup/useRadioGroup.js | cdnjs/cdnjs | import React from 'react';
import RadioGroupContext from './RadioGroupContext';
export default function useRadioGroup() {
return React.useContext(RadioGroupContext);
} |
ajax/libs/material-ui/4.9.2/esm/ExpansionPanel/ExpansionPanel.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _toArray from "@babel/runtime/helpers/esm/toArray";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { chainPropTypes } from '@material-ui/utils';
import Collapse from '../Collapse';
import Paper from '../Paper';
import withStyles from '../styles/withStyles';
import ExpansionPanelContext from './ExpansionPanelContext';
import useControlled from '../utils/useControlled';
export var styles = function styles(theme) {
var transition = {
duration: theme.transitions.duration.shortest
};
return {
/* Styles applied to the root element. */
root: {
position: 'relative',
transition: theme.transitions.create(['margin'], transition),
'&:before': {
position: 'absolute',
left: 0,
top: -1,
right: 0,
height: 1,
content: '""',
opacity: 1,
backgroundColor: theme.palette.divider,
transition: theme.transitions.create(['opacity', 'background-color'], transition)
},
'&:first-child': {
'&:before': {
display: 'none'
}
},
'&$expanded': {
margin: '16px 0',
'&:first-child': {
marginTop: 0
},
'&:last-child': {
marginBottom: 0
},
'&:before': {
opacity: 0
}
},
'&$expanded + &': {
'&:before': {
display: 'none'
}
},
'&$disabled': {
backgroundColor: theme.palette.action.disabledBackground
}
},
/* Styles applied to the root element if `square={false}`. */
rounded: {
borderRadius: 0,
'&:first-child': {
borderTopLeftRadius: theme.shape.borderRadius,
borderTopRightRadius: theme.shape.borderRadius
},
'&:last-child': {
borderBottomLeftRadius: theme.shape.borderRadius,
borderBottomRightRadius: theme.shape.borderRadius,
// Fix a rendering issue on Edge
'@supports (-ms-ime-align: auto)': {
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
}
}
},
/* Styles applied to the root element if `expanded={true}`. */
expanded: {},
/* Styles applied to the root element if `disabled={true}`. */
disabled: {}
};
};
var ExpansionPanel = React.forwardRef(function ExpansionPanel(props, ref) {
var childrenProp = props.children,
classes = props.classes,
className = props.className,
_props$defaultExpande = props.defaultExpanded,
defaultExpanded = _props$defaultExpande === void 0 ? false : _props$defaultExpande,
_props$disabled = props.disabled,
disabled = _props$disabled === void 0 ? false : _props$disabled,
expandedProp = props.expanded,
onChange = props.onChange,
_props$square = props.square,
square = _props$square === void 0 ? false : _props$square,
_props$TransitionComp = props.TransitionComponent,
TransitionComponent = _props$TransitionComp === void 0 ? Collapse : _props$TransitionComp,
TransitionProps = props.TransitionProps,
other = _objectWithoutProperties(props, ["children", "classes", "className", "defaultExpanded", "disabled", "expanded", "onChange", "square", "TransitionComponent", "TransitionProps"]);
var _useControlled = useControlled({
controlled: expandedProp,
default: defaultExpanded,
name: 'ExpansionPanel'
}),
_useControlled2 = _slicedToArray(_useControlled, 2),
expanded = _useControlled2[0],
setExpandedState = _useControlled2[1];
var handleChange = React.useCallback(function (event) {
setExpandedState(!expanded);
if (onChange) {
onChange(event, !expanded);
}
}, [expanded, onChange, setExpandedState]);
var _React$Children$toArr = React.Children.toArray(childrenProp),
_React$Children$toArr2 = _toArray(_React$Children$toArr),
summary = _React$Children$toArr2[0],
children = _React$Children$toArr2.slice(1);
var contextValue = React.useMemo(function () {
return {
expanded: expanded,
disabled: disabled,
toggle: handleChange
};
}, [expanded, disabled, handleChange]);
return React.createElement(Paper, _extends({
className: clsx(classes.root, className, expanded && classes.expanded, disabled && classes.disabled, !square && classes.rounded),
ref: ref,
square: square
}, other), React.createElement(ExpansionPanelContext.Provider, {
value: contextValue
}, summary), React.createElement(TransitionComponent, _extends({
in: expanded,
timeout: "auto"
}, TransitionProps), React.createElement("div", {
"aria-labelledby": summary.props.id,
id: summary.props['aria-controls'],
role: "region"
}, children)));
});
process.env.NODE_ENV !== "production" ? ExpansionPanel.propTypes = {
/**
* The content of the expansion panel.
*/
children: chainPropTypes(PropTypes.node.isRequired, function (props) {
var summary = React.Children.toArray(props.children)[0];
if (isFragment(summary)) {
return new Error("Material-UI: the ExpansionPanel doesn't accept a Fragment as a child. " + 'Consider providing an array instead.');
}
if (!React.isValidElement(summary)) {
return new Error('Material-UI: expected the first child of ExpansionPanel to be a valid element.');
}
return null;
}),
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, expands the panel by default.
*/
defaultExpanded: PropTypes.bool,
/**
* If `true`, the panel will be displayed in a disabled state.
*/
disabled: PropTypes.bool,
/**
* If `true`, expands the panel, otherwise collapse it.
* Setting this prop enables control over the panel.
*/
expanded: PropTypes.bool,
/**
* Callback fired when the expand/collapse state is changed.
*
* @param {object} event The event source of the callback.
* @param {boolean} expanded The `expanded` state of the panel.
*/
onChange: PropTypes.func,
/**
* @ignore
*/
square: PropTypes.bool,
/**
* The component used for the collapse effect.
* [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
*/
TransitionComponent: PropTypes.elementType,
/**
* Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element.
*/
TransitionProps: PropTypes.object
} : void 0;
export default withStyles(styles, {
name: 'MuiExpansionPanel'
})(ExpansionPanel); |
ajax/libs/react-native-web/0.17.2/exports/AppRegistry/renderApplication.js | cdnjs/cdnjs | function _extends() { _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; }; return _extends.apply(this, arguments); }
/**
* Copyright (c) Nicolas Gallagher.
* 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.
*
*
*/
import AppContainer from './AppContainer';
import invariant from 'fbjs/lib/invariant';
import render, { hydrate } from '../render';
import styleResolver from '../StyleSheet/styleResolver';
import React from 'react';
export default function renderApplication(RootComponent, WrapperComponent, callback, options) {
var shouldHydrate = options.hydrate,
initialProps = options.initialProps,
rootTag = options.rootTag;
var renderFn = shouldHydrate ? hydrate : render;
invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag);
renderFn( /*#__PURE__*/React.createElement(AppContainer, {
WrapperComponent: WrapperComponent,
rootTag: rootTag
}, /*#__PURE__*/React.createElement(RootComponent, initialProps)), rootTag, callback);
}
export function getApplication(RootComponent, initialProps, WrapperComponent) {
var element = /*#__PURE__*/React.createElement(AppContainer, {
WrapperComponent: WrapperComponent,
rootTag: {}
}, /*#__PURE__*/React.createElement(RootComponent, initialProps)); // Don't escape CSS text
var getStyleElement = function getStyleElement(props) {
var sheet = styleResolver.getStyleSheet();
return /*#__PURE__*/React.createElement("style", _extends({}, props, {
dangerouslySetInnerHTML: {
__html: sheet.textContent
},
id: sheet.id
}));
};
return {
element: element,
getStyleElement: getStyleElement
};
} |
ajax/libs/primereact/7.2.0/blockui/blockui.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, ZIndexUtils, classNames, ObjectUtils } from 'primereact/utils';
import { Portal } from 'primereact/portal';
import PrimeReact from 'primereact/api';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var BlockUI = /*#__PURE__*/function (_Component) {
_inherits(BlockUI, _Component);
var _super = _createSuper(BlockUI);
function BlockUI(props) {
var _this;
_classCallCheck(this, BlockUI);
_this = _super.call(this, props);
_this.state = {
visible: props.blocked
};
_this.block = _this.block.bind(_assertThisInitialized(_this));
_this.unblock = _this.unblock.bind(_assertThisInitialized(_this));
_this.onPortalMounted = _this.onPortalMounted.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(BlockUI, [{
key: "block",
value: function block() {
this.setState({
visible: true
});
}
}, {
key: "unblock",
value: function unblock() {
var _this2 = this;
var callback = function callback() {
_this2.setState({
visible: false
}, function () {
_this2.props.fullScreen && DomHandler.removeClass(document.body, 'p-overflow-hidden');
_this2.props.onUnblocked && _this2.props.onUnblocked();
});
};
if (this.mask) {
DomHandler.addClass(this.mask, 'p-component-overlay-leave');
this.mask.addEventListener('animationend', function () {
ZIndexUtils.clear(_this2.mask);
callback();
});
} else {
callback();
}
}
}, {
key: "onPortalMounted",
value: function onPortalMounted() {
if (this.props.fullScreen) {
DomHandler.addClass(document.body, 'p-overflow-hidden');
document.activeElement.blur();
}
if (this.props.autoZIndex) {
var key = this.props.fullScreen ? 'modal' : 'overlay';
ZIndexUtils.set(key, this.mask, PrimeReact.autoZIndex, this.props.baseZIndex || PrimeReact.zIndex[key]);
}
this.props.onBlocked && this.props.onBlocked();
}
}, {
key: "renderMask",
value: function renderMask() {
var _this3 = this;
if (this.state.visible) {
var className = classNames('p-blockui p-component-overlay p-component-overlay-enter', {
'p-blockui-document': this.props.fullScreen
}, this.props.className);
var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : null;
var mask = /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this3.mask = el;
},
className: className,
style: this.props.style
}, content);
return /*#__PURE__*/React.createElement(Portal, {
element: mask,
appendTo: this.props.fullScreen ? document.body : 'self',
onMounted: this.onPortalMounted
});
}
return null;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.state.visible) {
this.block();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
if (prevProps.blocked !== this.props.blocked) {
this.props.blocked ? this.block() : this.unblock();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.props.fullScreen) {
DomHandler.removeClass(document.body, 'p-overflow-hidden');
}
ZIndexUtils.clear(this.mask);
}
}, {
key: "render",
value: function render() {
var _this4 = this;
var mask = this.renderMask();
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this4.container = el;
},
id: this.props.id,
className: "p-blockui-container"
}, this.props.children, mask);
}
}]);
return BlockUI;
}(Component);
_defineProperty(BlockUI, "defaultProps", {
id: null,
blocked: false,
fullScreen: false,
baseZIndex: 0,
autoZIndex: true,
style: null,
className: null,
template: null,
onBlocked: null,
onUnblocked: null
});
export { BlockUI };
|
ajax/libs/material-ui/4.9.2/esm/Select/Select.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import { mergeClasses } from '@material-ui/styles';
import SelectInput from './SelectInput';
import formControlState from '../FormControl/formControlState';
import useFormControl from '../FormControl/useFormControl';
import withStyles from '../styles/withStyles';
import ArrowDropDownIcon from '../internal/svg-icons/ArrowDropDown';
import Input from '../Input';
import { styles as nativeSelectStyles } from '../NativeSelect/NativeSelect';
import NativeSelectInput from '../NativeSelect/NativeSelectInput';
import FilledInput from '../FilledInput';
import OutlinedInput from '../OutlinedInput';
export var styles = nativeSelectStyles;
var _ref = React.createElement(Input, null);
var _ref2 = React.createElement(FilledInput, null);
var Select = React.forwardRef(function Select(props, ref) {
var _props$autoWidth = props.autoWidth,
autoWidth = _props$autoWidth === void 0 ? false : _props$autoWidth,
children = props.children,
classes = props.classes,
_props$displayEmpty = props.displayEmpty,
displayEmpty = _props$displayEmpty === void 0 ? false : _props$displayEmpty,
_props$IconComponent = props.IconComponent,
IconComponent = _props$IconComponent === void 0 ? ArrowDropDownIcon : _props$IconComponent,
id = props.id,
input = props.input,
inputProps = props.inputProps,
label = props.label,
labelId = props.labelId,
_props$labelWidth = props.labelWidth,
labelWidth = _props$labelWidth === void 0 ? 0 : _props$labelWidth,
MenuProps = props.MenuProps,
_props$multiple = props.multiple,
multiple = _props$multiple === void 0 ? false : _props$multiple,
_props$native = props.native,
native = _props$native === void 0 ? false : _props$native,
onClose = props.onClose,
onOpen = props.onOpen,
open = props.open,
renderValue = props.renderValue,
SelectDisplayProps = props.SelectDisplayProps,
_props$variant = props.variant,
variantProps = _props$variant === void 0 ? 'standard' : _props$variant,
other = _objectWithoutProperties(props, ["autoWidth", "children", "classes", "displayEmpty", "IconComponent", "id", "input", "inputProps", "label", "labelId", "labelWidth", "MenuProps", "multiple", "native", "onClose", "onOpen", "open", "renderValue", "SelectDisplayProps", "variant"]);
var inputComponent = native ? NativeSelectInput : SelectInput;
var muiFormControl = useFormControl();
var fcs = formControlState({
props: props,
muiFormControl: muiFormControl,
states: ['variant']
});
var variant = fcs.variant || variantProps;
var InputComponent = input || {
standard: _ref,
outlined: React.createElement(OutlinedInput, {
label: label,
labelWidth: labelWidth
}),
filled: _ref2
}[variant];
return React.cloneElement(InputComponent, _extends({
// Most of the logic is implemented in `SelectInput`.
// The `Select` component is a simple API wrapper to expose something better to play with.
inputComponent: inputComponent,
inputProps: _extends({
children: children,
IconComponent: IconComponent,
variant: variant,
type: undefined,
// We render a select. We can ignore the type provided by the `Input`.
multiple: multiple
}, native ? {
id: id
} : {
autoWidth: autoWidth,
displayEmpty: displayEmpty,
labelId: labelId,
MenuProps: MenuProps,
onClose: onClose,
onOpen: onOpen,
open: open,
renderValue: renderValue,
SelectDisplayProps: _extends({
id: id
}, SelectDisplayProps)
}, {}, inputProps, {
classes: inputProps ? mergeClasses({
baseClasses: classes,
newClasses: inputProps.classes,
Component: Select
}) : classes
}, input ? input.props.inputProps : {}),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? Select.propTypes = {
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
*/
autoWidth: PropTypes.bool,
/**
* The option elements to populate the select with.
* Can be some `MenuItem` when `native` is false and `option` when `native` is true.
*
* ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The default element value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, a value is displayed even if no items are selected.
*
* In order to display a meaningful value, a function should be passed to the `renderValue` prop which returns the value to be displayed when no items are selected.
* You can only use it when the `native` prop is `false` (default).
*/
displayEmpty: PropTypes.bool,
/**
* The icon that displays the arrow.
*/
IconComponent: PropTypes.elementType,
/**
* @ignore
*/
id: PropTypes.string,
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
*/
input: PropTypes.element,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
* When `native` is `true`, the attributes are applied on the `select` element.
*/
inputProps: PropTypes.object,
/**
* See [OutlinedLabel#label](/api/outlined-input/#props)
*/
label: PropTypes.node,
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId: PropTypes.string,
/**
* See OutlinedLabel#label
*/
labelWidth: PropTypes.number,
/**
* Props applied to the [`Menu`](/api/menu/) element.
*/
MenuProps: PropTypes.object,
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
*/
multiple: PropTypes.bool,
/**
* If `true`, the component will be using a native `select` element.
*/
native: PropTypes.bool,
/**
* Callback function fired when a menu item is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* @param {object} [child] The react element that was selected when `native` is `false` (default).
*/
onChange: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* Callback fired when the component requests to be opened.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* Control `select` open state.
* You can only use it when the `native` prop is `false` (default).
*/
open: PropTypes.bool,
/**
* Render the selected value.
* You can only use it when the `native` prop is `false` (default).
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue: PropTypes.func,
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps: PropTypes.object,
/**
* The input value. Providing an empty string will select no options.
* This prop is required when the `native` prop is `false` (default).
* Set to an empty string `''` if you don't want any of the available options to be selected.
*
* If the value is an object it must have reference equality with the option in order to be selected.
* If the value is not an object, the string representation must match with the string representation of the option in order to be selected.
*/
value: PropTypes.any,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])
} : void 0;
Select.muiName = 'Select';
export default withStyles(styles, {
name: 'MuiSelect'
})(Select); |
ajax/libs/material-ui/4.9.4/es/internal/svg-icons/CheckBoxOutlineBlank.js | cdnjs/cdnjs | import React from 'react';
import createSvgIcon from './createSvgIcon';
/**
* @ignore - internal component.
*/
export default createSvgIcon(React.createElement("path", {
d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"
}), 'CheckBoxOutlineBlank'); |
ajax/libs/material-ui/4.9.4/es/useScrollTrigger/useScrollTrigger.js | cdnjs/cdnjs | import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
function getScrollY(ref) {
return ref.pageYOffset !== undefined ? ref.pageYOffset : ref.scrollTop;
}
function defaultTrigger(event, store, options) {
const {
disableHysteresis = false,
threshold = 100
} = options;
const previous = store.current;
store.current = event ? getScrollY(event.currentTarget) : previous;
if (!disableHysteresis && previous !== undefined) {
if (store.current < previous) {
return false;
}
}
return store.current > threshold;
}
const defaultTarget = typeof window !== 'undefined' ? window : null;
export default function useScrollTrigger(options = {}) {
const {
getTrigger = defaultTrigger,
target = defaultTarget
} = options,
other = _objectWithoutPropertiesLoose(options, ["getTrigger", "target"]);
const store = React.useRef();
const [trigger, setTrigger] = React.useState(() => getTrigger(null, store, other));
React.useEffect(() => {
const handleScroll = event => {
setTrigger(getTrigger(event, store, other));
};
handleScroll(null); // Re-evaluate trigger when dependencies change
target.addEventListener('scroll', handleScroll);
return () => {
target.removeEventListener('scroll', handleScroll);
}; // See Option 3. https://github.com/facebook/react/issues/14476#issuecomment-471199055
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [target, getTrigger, JSON.stringify(other)]);
return trigger;
} |
ajax/libs/react-redux/7.1.0-rc.1/react-redux.js | cdnjs/cdnjs | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('redux'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'redux', 'react-dom'], factory) :
(global = global || self, factory(global.ReactRedux = {}, global.React, global.Redux, global.ReactDOM));
}(this, function (exports, React, redux, reactDom) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
Object.defineProperty(exports, '__esModule', { value: true });
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' ||
// Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
}
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var lowPriorityWarning = function () {};
{
var printWarning = function (format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.warn(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function (condition, format) {
if (format === undefined) {
throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
var lowPriorityWarning$1 = lowPriorityWarning;
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
}
// AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
// AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.typeOf = typeOf;
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isValidElementType = isValidElementType;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
})();
}
});
unwrapExports(reactIs_development);
var reactIs_development_1 = reactIs_development.typeOf;
var reactIs_development_2 = reactIs_development.AsyncMode;
var reactIs_development_3 = reactIs_development.ConcurrentMode;
var reactIs_development_4 = reactIs_development.ContextConsumer;
var reactIs_development_5 = reactIs_development.ContextProvider;
var reactIs_development_6 = reactIs_development.Element;
var reactIs_development_7 = reactIs_development.ForwardRef;
var reactIs_development_8 = reactIs_development.Fragment;
var reactIs_development_9 = reactIs_development.Lazy;
var reactIs_development_10 = reactIs_development.Memo;
var reactIs_development_11 = reactIs_development.Portal;
var reactIs_development_12 = reactIs_development.Profiler;
var reactIs_development_13 = reactIs_development.StrictMode;
var reactIs_development_14 = reactIs_development.Suspense;
var reactIs_development_15 = reactIs_development.isValidElementType;
var reactIs_development_16 = reactIs_development.isAsyncMode;
var reactIs_development_17 = reactIs_development.isConcurrentMode;
var reactIs_development_18 = reactIs_development.isContextConsumer;
var reactIs_development_19 = reactIs_development.isContextProvider;
var reactIs_development_20 = reactIs_development.isElement;
var reactIs_development_21 = reactIs_development.isForwardRef;
var reactIs_development_22 = reactIs_development.isFragment;
var reactIs_development_23 = reactIs_development.isLazy;
var reactIs_development_24 = reactIs_development.isMemo;
var reactIs_development_25 = reactIs_development.isPortal;
var reactIs_development_26 = reactIs_development.isProfiler;
var reactIs_development_27 = reactIs_development.isStrictMode;
var reactIs_development_28 = reactIs_development.isSuspense;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
var reactIs_1 = reactIs.isValidElementType;
var reactIs_2 = reactIs.isContextConsumer;
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = 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.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 printWarning = function() {};
{
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
var loggedTypeFailures = {};
var has = Function.call.bind(Object.prototype.hasOwnProperty);
printWarning = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
{
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error(
(componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
);
err.name = 'Invariant Violation';
throw err;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
if (error && !(error instanceof Error)) {
printWarning(
(componentName || 'React class') + ': type specification of ' +
location + ' `' + typeSpecName + '` is invalid; the type checker ' +
'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
'You may have forgotten to pass an argument to the type checker ' +
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
'shape all require an argument).'
);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
}
}
}
}
/**
* Resets warning cache when testing.
*
* @private
*/
checkPropTypes.resetWarningCache = function() {
{
loggedTypeFailures = {};
}
};
var checkPropTypes_1 = checkPropTypes;
var has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
var printWarning$1 = function() {};
{
printWarning$1 = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
var err = new Error(
'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'
);
err.name = 'Invariant Violation';
throw err;
} else if (typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
printWarning$1(
'You are manually calling a React.PropTypes validation ' +
'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!reactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
{
if (arguments.length > 1) {
printWarning$1(
'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
);
} else {
printWarning$1('Invalid argument supplied to oneOf, expected an array.');
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
var type = getPreciseType(value);
if (type === 'symbol') {
return String(value);
}
return value;
});
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (has$1(propValue, key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.');
return emptyFunctionThatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
printWarning$1(
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// falsy value can't be a Symbol
if (!propValue) {
return false;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes_1;
ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache;
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.
*/
{
var ReactIs = reactIs;
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess);
}
});
var ReactReduxContext = React__default.createContext(null);
// Default to a dummy "batch" implementation that just runs the callback
function defaultNoopBatch(callback) {
callback();
}
var batch = defaultNoopBatch; // Allow injecting another batching function later
var setBatch = function setBatch(newBatch) {
return batch = newBatch;
}; // Supply a getter just to skip dealing with ESM bindings
var getBatch = function getBatch() {
return batch;
};
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants
var CLEARED = null;
var nullListeners = {
notify: function notify() {}
};
function createListenerCollection() {
var batch = getBatch(); // the current/next pattern is copied from redux's createStore code.
// TODO: refactor+expose that code to be reusable here?
var current = [];
var next = [];
return {
clear: function clear() {
next = CLEARED;
current = CLEARED;
},
notify: function notify() {
var listeners = current = next;
batch(function () {
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
});
},
get: function get() {
return next;
},
subscribe: function subscribe(listener) {
var isSubscribed = true;
if (next === current) next = current.slice();
next.push(listener);
return function unsubscribe() {
if (!isSubscribed || current === CLEARED) return;
isSubscribed = false;
if (next === current) next = current.slice();
next.splice(next.indexOf(listener), 1);
};
}
};
}
var Subscription =
/*#__PURE__*/
function () {
function Subscription(store, parentSub) {
this.store = store;
this.parentSub = parentSub;
this.unsubscribe = null;
this.listeners = nullListeners;
this.handleChangeWrapper = this.handleChangeWrapper.bind(this);
}
var _proto = Subscription.prototype;
_proto.addNestedSub = function addNestedSub(listener) {
this.trySubscribe();
return this.listeners.subscribe(listener);
};
_proto.notifyNestedSubs = function notifyNestedSubs() {
this.listeners.notify();
};
_proto.handleChangeWrapper = function handleChangeWrapper() {
if (this.onStateChange) {
this.onStateChange();
}
};
_proto.isSubscribed = function isSubscribed() {
return Boolean(this.unsubscribe);
};
_proto.trySubscribe = function trySubscribe() {
if (!this.unsubscribe) {
this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.handleChangeWrapper) : this.store.subscribe(this.handleChangeWrapper);
this.listeners = createListenerCollection();
}
};
_proto.tryUnsubscribe = function tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
this.listeners.clear();
this.listeners = nullListeners;
}
};
return Subscription;
}();
var Provider =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Provider, _Component);
function Provider(props) {
var _this;
_this = _Component.call(this, props) || this;
var store = props.store;
_this.notifySubscribers = _this.notifySubscribers.bind(_assertThisInitialized(_this));
var subscription = new Subscription(store);
subscription.onStateChange = _this.notifySubscribers;
_this.state = {
store: store,
subscription: subscription
};
_this.previousState = store.getState();
return _this;
}
var _proto = Provider.prototype;
_proto.componentDidMount = function componentDidMount() {
this._isMounted = true;
this.state.subscription.trySubscribe();
if (this.previousState !== this.props.store.getState()) {
this.state.subscription.notifyNestedSubs();
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.unsubscribe) this.unsubscribe();
this.state.subscription.tryUnsubscribe();
this._isMounted = false;
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
if (this.props.store !== prevProps.store) {
this.state.subscription.tryUnsubscribe();
var subscription = new Subscription(this.props.store);
subscription.onStateChange = this.notifySubscribers;
this.setState({
store: this.props.store,
subscription: subscription
});
}
};
_proto.notifySubscribers = function notifySubscribers() {
this.state.subscription.notifyNestedSubs();
};
_proto.render = function render() {
var Context = this.props.context || ReactReduxContext;
return React__default.createElement(Context.Provider, {
value: this.state
}, this.props.children);
};
return Provider;
}(React.Component);
Provider.propTypes = {
store: propTypes.shape({
subscribe: propTypes.func.isRequired,
dispatch: propTypes.func.isRequired,
getState: propTypes.func.isRequired
}),
context: propTypes.object,
children: propTypes.any
};
function _extends() {
_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;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
function getStatics(component) {
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
}
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols$1 = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols$1) {
keys = keys.concat(getOwnPropertySymbols$1(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
return targetComponent;
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
/**
* 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 invariant = function(condition, format, a, b, c, d, e, f) {
{
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
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;
var EMPTY_ARRAY = [];
var NO_SUBSCRIPTION_ARRAY = [null, null];
var stringifyComponent = function stringifyComponent(Comp) {
try {
return JSON.stringify(Comp);
} catch (err) {
return String(Comp);
}
};
function storeStateUpdatesReducer(state, action) {
var updateCount = state[1];
return [action.payload, updateCount + 1];
}
var initStateUpdates = function initStateUpdates() {
return [null, 0];
}; // React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser. We need useLayoutEffect because we want
// `connect` to perform sync updates to a ref to save the latest props after
// a render is actually committed to the DOM.
var useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? React.useLayoutEffect : React.useEffect;
function connectAdvanced(
/*
selectorFactory is a func that is responsible for returning the selector function used to
compute new props from state, props, and dispatch. For example:
export default connectAdvanced((dispatch, options) => (state, props) => ({
thing: state.things[props.thingId],
saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)),
}))(YourComponent)
Access to dispatch is provided to the factory so selectorFactories can bind actionCreators
outside of their selector as an optimization. Options passed to connectAdvanced are passed to
the selectorFactory, along with displayName and WrappedComponent, as the second argument.
Note that selectorFactory is responsible for all caching/memoization of inbound and outbound
props. Do not use connectAdvanced directly without memoizing results between calls to your
selector, otherwise the Connect component will re-render on every state or props change.
*/
selectorFactory, // options object:
_ref) {
if (_ref === void 0) {
_ref = {};
}
var _ref2 = _ref,
_ref2$getDisplayName = _ref2.getDisplayName,
getDisplayName = _ref2$getDisplayName === void 0 ? function (name) {
return "ConnectAdvanced(" + name + ")";
} : _ref2$getDisplayName,
_ref2$methodName = _ref2.methodName,
methodName = _ref2$methodName === void 0 ? 'connectAdvanced' : _ref2$methodName,
_ref2$renderCountProp = _ref2.renderCountProp,
renderCountProp = _ref2$renderCountProp === void 0 ? undefined : _ref2$renderCountProp,
_ref2$shouldHandleSta = _ref2.shouldHandleStateChanges,
shouldHandleStateChanges = _ref2$shouldHandleSta === void 0 ? true : _ref2$shouldHandleSta,
_ref2$storeKey = _ref2.storeKey,
storeKey = _ref2$storeKey === void 0 ? 'store' : _ref2$storeKey,
_ref2$withRef = _ref2.withRef,
withRef = _ref2$withRef === void 0 ? false : _ref2$withRef,
_ref2$forwardRef = _ref2.forwardRef,
forwardRef = _ref2$forwardRef === void 0 ? false : _ref2$forwardRef,
_ref2$context = _ref2.context,
context = _ref2$context === void 0 ? ReactReduxContext : _ref2$context,
connectOptions = _objectWithoutPropertiesLoose(_ref2, ["getDisplayName", "methodName", "renderCountProp", "shouldHandleStateChanges", "storeKey", "withRef", "forwardRef", "context"]);
invariant_1(renderCountProp === undefined, "renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension");
invariant_1(!withRef, 'withRef is removed. To access the wrapped instance, use a ref on the connected component');
var customStoreWarningMessage = 'To use a custom Redux store for specific components, create a custom React context with ' + "React.createContext(), and pass the context object to React Redux's Provider and specific components" + ' like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. ' + 'You may also pass a {context : MyContext} option to connect';
invariant_1(storeKey === 'store', 'storeKey has been removed and does not do anything. ' + customStoreWarningMessage);
var Context = context;
return function wrapWithConnect(WrappedComponent) {
{
invariant_1(reactIs_1(WrappedComponent), "You must pass a component to the function returned by " + (methodName + ". Instead received " + stringifyComponent(WrappedComponent)));
}
var wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
var displayName = getDisplayName(wrappedComponentName);
var selectorFactoryOptions = _extends({}, connectOptions, {
getDisplayName: getDisplayName,
methodName: methodName,
renderCountProp: renderCountProp,
shouldHandleStateChanges: shouldHandleStateChanges,
storeKey: storeKey,
displayName: displayName,
wrappedComponentName: wrappedComponentName,
WrappedComponent: WrappedComponent
});
var pure = connectOptions.pure;
function createChildSelector(store) {
return selectorFactory(store.dispatch, selectorFactoryOptions);
} // If we aren't running in "pure" mode, we don't want to memoize values.
// To avoid conditionally calling hooks, we fall back to a tiny wrapper
// that just executes the given callback immediately.
var usePureOnlyMemo = pure ? React.useMemo : function (callback) {
return callback();
};
function ConnectFunction(props) {
var _useMemo = React.useMemo(function () {
// Distinguish between actual "data" props that were passed to the wrapper component,
// and values needed to control behavior (forwarded refs, alternate context instances).
// To maintain the wrapperProps object reference, memoize this destructuring.
var forwardedRef = props.forwardedRef,
wrapperProps = _objectWithoutPropertiesLoose(props, ["forwardedRef"]);
return [props.context, forwardedRef, wrapperProps];
}, [props]),
propsContext = _useMemo[0],
forwardedRef = _useMemo[1],
wrapperProps = _useMemo[2];
var ContextToUse = React.useMemo(function () {
// Users may optionally pass in a custom context instance to use instead of our ReactReduxContext.
// Memoize the check that determines which context instance we should use.
return propsContext && propsContext.Consumer && reactIs_2(React__default.createElement(propsContext.Consumer, null)) ? propsContext : Context;
}, [propsContext, Context]); // Retrieve the store and ancestor subscription via context, if available
var contextValue = React.useContext(ContextToUse); // The store _must_ exist as either a prop or in context
var didStoreComeFromProps = Boolean(props.store);
var didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store);
invariant_1(didStoreComeFromProps || didStoreComeFromContext, "Could not find \"store\" in the context of " + ("\"" + displayName + "\". Either wrap the root component in a <Provider>, ") + "or pass a custom React context provider to <Provider> and the corresponding " + ("React context consumer to " + displayName + " in connect options."));
var store = props.store || contextValue.store;
var childPropsSelector = React.useMemo(function () {
// The child props selector needs the store reference as an input.
// Re-create this selector whenever the store changes.
return createChildSelector(store);
}, [store]);
var _useMemo2 = React.useMemo(function () {
if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY; // This Subscription's source should match where store came from: props vs. context. A component
// connected to the store via props shouldn't use subscription from context, or vice versa.
var subscription = new Subscription(store, didStoreComeFromProps ? null : contextValue.subscription); // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in
// the middle of the notification loop, where `subscription` will then be null. This can
// probably be avoided if Subscription's listeners logic is changed to not call listeners
// that have been unsubscribed in the middle of the notification loop.
var notifyNestedSubs = subscription.notifyNestedSubs.bind(subscription);
return [subscription, notifyNestedSubs];
}, [store, didStoreComeFromProps, contextValue]),
subscription = _useMemo2[0],
notifyNestedSubs = _useMemo2[1]; // Determine what {store, subscription} value should be put into nested context, if necessary,
// and memoize that value to avoid unnecessary context updates.
var overriddenContextValue = React.useMemo(function () {
if (didStoreComeFromProps) {
// This component is directly subscribed to a store from props.
// We don't want descendants reading from this store - pass down whatever
// the existing context value is from the nearest connected ancestor.
return contextValue;
} // Otherwise, put this component's subscription instance into context, so that
// connected descendants won't update until after this component is done
return _extends({}, contextValue, {
subscription: subscription
});
}, [didStoreComeFromProps, contextValue, subscription]); // We need to force this wrapper component to re-render whenever a Redux store update
// causes a change to the calculated child component props (or we caught an error in mapState)
var _useReducer = React.useReducer(storeStateUpdatesReducer, EMPTY_ARRAY, initStateUpdates),
_useReducer$ = _useReducer[0],
previousStateUpdateResult = _useReducer$[0],
forceComponentUpdateDispatch = _useReducer[1]; // Propagate any mapState/mapDispatch errors upwards
if (previousStateUpdateResult && previousStateUpdateResult.error) {
throw previousStateUpdateResult.error;
} // Set up refs to coordinate values between the subscription effect and the render logic
var lastChildProps = React.useRef();
var lastWrapperProps = React.useRef(wrapperProps);
var childPropsFromStoreUpdate = React.useRef();
var renderIsScheduled = React.useRef(false);
var actualChildProps = usePureOnlyMemo(function () {
// Tricky logic here:
// - This render may have been triggered by a Redux store update that produced new child props
// - However, we may have gotten new wrapper props after that
// If we have new child props, and the same wrapper props, we know we should use the new child props as-is.
// But, if we have new wrapper props, those might change the child props, so we have to recalculate things.
// So, we'll use the child props from store update only if the wrapper props are the same as last time.
if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) {
return childPropsFromStoreUpdate.current;
} // TODO We're reading the store directly in render() here. Bad idea?
// This will likely cause Bad Things (TM) to happen in Concurrent Mode.
// Note that we do this because on renders _not_ caused by store updates, we need the latest store state
// to determine what the child props should be.
return childPropsSelector(store.getState(), wrapperProps);
}, [store, previousStateUpdateResult, wrapperProps]); // We need this to execute synchronously every time we re-render. However, React warns
// about useLayoutEffect in SSR, so we try to detect environment and fall back to
// just useEffect instead to avoid the warning, since neither will run anyway.
useIsomorphicLayoutEffect(function () {
// We want to capture the wrapper props and child props we used for later comparisons
lastWrapperProps.current = wrapperProps;
lastChildProps.current = actualChildProps;
renderIsScheduled.current = false; // If the render was from a store update, clear out that reference and cascade the subscriber update
if (childPropsFromStoreUpdate.current) {
childPropsFromStoreUpdate.current = null;
notifyNestedSubs();
}
}); // Our re-subscribe logic only runs when the store/subscription setup changes
useIsomorphicLayoutEffect(function () {
// If we're not subscribed to the store, nothing to do here
if (!shouldHandleStateChanges) return; // Capture values for checking if and when this component unmounts
var didUnsubscribe = false;
var lastThrownError = null; // We'll run this callback every time a store subscription update propagates to this component
var checkForUpdates = function checkForUpdates() {
if (didUnsubscribe) {
// Don't run stale listeners.
// Redux doesn't guarantee unsubscriptions happen until next dispatch.
return;
}
var latestStoreState = store.getState();
var newChildProps, error;
try {
// Actually run the selector with the most recent store state and wrapper props
// to determine what the child props should be
newChildProps = childPropsSelector(latestStoreState, lastWrapperProps.current);
} catch (e) {
error = e;
lastThrownError = e;
}
if (!error) {
lastThrownError = null;
} // If the child props haven't changed, nothing to do here - cascade the subscription update
if (newChildProps === lastChildProps.current) {
if (!renderIsScheduled.current) {
notifyNestedSubs();
}
} else {
// Save references to the new child props. Note that we track the "child props from store update"
// as a ref instead of a useState/useReducer because we need a way to determine if that value has
// been processed. If this went into useState/useReducer, we couldn't clear out the value without
// forcing another re-render, which we don't want.
lastChildProps.current = newChildProps;
childPropsFromStoreUpdate.current = newChildProps;
renderIsScheduled.current = true; // If the child props _did_ change (or we caught an error), this wrapper component needs to re-render
forceComponentUpdateDispatch({
type: 'STORE_UPDATED',
payload: {
latestStoreState: latestStoreState,
error: error
}
});
}
}; // Actually subscribe to the nearest connected ancestor (or store)
subscription.onStateChange = checkForUpdates;
subscription.trySubscribe(); // Pull data from the store after first render in case the store has
// changed since we began.
checkForUpdates();
var unsubscribeWrapper = function unsubscribeWrapper() {
didUnsubscribe = true;
subscription.tryUnsubscribe();
if (lastThrownError) {
// It's possible that we caught an error due to a bad mapState function, but the
// parent re-rendered without this component and we're about to unmount.
// This shouldn't happen as long as we do top-down subscriptions correctly, but
// if we ever do those wrong, this throw will surface the error in our tests.
// In that case, throw the error from here so it doesn't get lost.
throw lastThrownError;
}
};
return unsubscribeWrapper;
}, [store, subscription, childPropsSelector]); // Now that all that's done, we can finally try to actually render the child component.
// We memoize the elements for the rendered child component as an optimization.
var renderedWrappedComponent = React.useMemo(function () {
return React__default.createElement(WrappedComponent, _extends({}, actualChildProps, {
ref: forwardedRef
}));
}, [forwardedRef, WrappedComponent, actualChildProps]); // If React sees the exact same element reference as last time, it bails out of re-rendering
// that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.
var renderedChild = React.useMemo(function () {
if (shouldHandleStateChanges) {
// If this component is subscribed to store updates, we need to pass its own
// subscription instance down to our descendants. That means rendering the same
// Context instance, and putting a different value into the context.
return React__default.createElement(ContextToUse.Provider, {
value: overriddenContextValue
}, renderedWrappedComponent);
}
return renderedWrappedComponent;
}, [ContextToUse, renderedWrappedComponent, overriddenContextValue]);
return renderedChild;
} // If we're in "pure" mode, ensure our wrapper component only re-renders when incoming props have changed.
var Connect = pure ? React__default.memo(ConnectFunction) : ConnectFunction;
Connect.WrappedComponent = WrappedComponent;
Connect.displayName = displayName;
if (forwardRef) {
var forwarded = React__default.forwardRef(function forwardConnectRef(props, ref) {
return React__default.createElement(Connect, _extends({}, props, {
forwardedRef: ref
}));
});
forwarded.displayName = displayName;
forwarded.WrappedComponent = WrappedComponent;
return hoistNonReactStatics_cjs(forwarded, WrappedComponent);
}
return hoistNonReactStatics_cjs(Connect, WrappedComponent);
};
}
var hasOwn = Object.prototype.hasOwnProperty;
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function shallowEqual(objA, objB) {
if (is(objA, objB)) return true;
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false;
var proto = Object.getPrototypeOf(obj);
if (proto === null) return true;
var baseProto = proto;
while (Object.getPrototypeOf(baseProto) !== null) {
baseProto = Object.getPrototypeOf(baseProto);
}
return proto === baseProto;
}
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that if you enable
// "break on all exceptions" in your console,
// it would pause the execution at this line.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
function verifyPlainObject(value, displayName, methodName) {
if (!isPlainObject(value)) {
warning(methodName + "() in " + displayName + " must return a plain object. Instead received " + value + ".");
}
}
function wrapMapToPropsConstant(getConstant) {
return function initConstantSelector(dispatch, options) {
var constant = getConstant(dispatch, options);
function constantSelector() {
return constant;
}
constantSelector.dependsOnOwnProps = false;
return constantSelector;
};
} // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args
// to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine
// whether mapToProps needs to be invoked when props have changed.
//
// A length of one signals that mapToProps does not depend on props from the parent component.
// A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and
// therefore not reporting its length accurately..
function getDependsOnOwnProps(mapToProps) {
return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;
} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,
// this function wraps mapToProps in a proxy function which does several things:
//
// * Detects whether the mapToProps function being called depends on props, which
// is used by selectorFactory to decide if it should reinvoke on props changes.
//
// * On first call, handles mapToProps if returns another function, and treats that
// new function as the true mapToProps for subsequent calls.
//
// * On first call, verifies the first result is a plain object, in order to warn
// the developer that their mapToProps function is not returning a valid result.
//
function wrapMapToPropsFunc(mapToProps, methodName) {
return function initProxySelector(dispatch, _ref) {
var displayName = _ref.displayName;
var proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {
return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch);
}; // allow detectFactoryAndVerify to get ownProps
proxy.dependsOnOwnProps = true;
proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {
proxy.mapToProps = mapToProps;
proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);
var props = proxy(stateOrDispatch, ownProps);
if (typeof props === 'function') {
proxy.mapToProps = props;
proxy.dependsOnOwnProps = getDependsOnOwnProps(props);
props = proxy(stateOrDispatch, ownProps);
}
verifyPlainObject(props, displayName, methodName);
return props;
};
return proxy;
};
}
function whenMapDispatchToPropsIsFunction(mapDispatchToProps) {
return typeof mapDispatchToProps === 'function' ? wrapMapToPropsFunc(mapDispatchToProps, 'mapDispatchToProps') : undefined;
}
function whenMapDispatchToPropsIsMissing(mapDispatchToProps) {
return !mapDispatchToProps ? wrapMapToPropsConstant(function (dispatch) {
return {
dispatch: dispatch
};
}) : undefined;
}
function whenMapDispatchToPropsIsObject(mapDispatchToProps) {
return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(function (dispatch) {
return redux.bindActionCreators(mapDispatchToProps, dispatch);
}) : undefined;
}
var defaultMapDispatchToPropsFactories = [whenMapDispatchToPropsIsFunction, whenMapDispatchToPropsIsMissing, whenMapDispatchToPropsIsObject];
function whenMapStateToPropsIsFunction(mapStateToProps) {
return typeof mapStateToProps === 'function' ? wrapMapToPropsFunc(mapStateToProps, 'mapStateToProps') : undefined;
}
function whenMapStateToPropsIsMissing(mapStateToProps) {
return !mapStateToProps ? wrapMapToPropsConstant(function () {
return {};
}) : undefined;
}
var defaultMapStateToPropsFactories = [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing];
function defaultMergeProps(stateProps, dispatchProps, ownProps) {
return _extends({}, ownProps, stateProps, dispatchProps);
}
function wrapMergePropsFunc(mergeProps) {
return function initMergePropsProxy(dispatch, _ref) {
var displayName = _ref.displayName,
pure = _ref.pure,
areMergedPropsEqual = _ref.areMergedPropsEqual;
var hasRunOnce = false;
var mergedProps;
return function mergePropsProxy(stateProps, dispatchProps, ownProps) {
var nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);
if (hasRunOnce) {
if (!pure || !areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps;
} else {
hasRunOnce = true;
mergedProps = nextMergedProps;
verifyPlainObject(mergedProps, displayName, 'mergeProps');
}
return mergedProps;
};
};
}
function whenMergePropsIsFunction(mergeProps) {
return typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : undefined;
}
function whenMergePropsIsOmitted(mergeProps) {
return !mergeProps ? function () {
return defaultMergeProps;
} : undefined;
}
var defaultMergePropsFactories = [whenMergePropsIsFunction, whenMergePropsIsOmitted];
function verify(selector, methodName, displayName) {
if (!selector) {
throw new Error("Unexpected value for " + methodName + " in " + displayName + ".");
} else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') {
if (!selector.hasOwnProperty('dependsOnOwnProps')) {
warning("The selector for " + methodName + " of " + displayName + " did not specify a value for dependsOnOwnProps.");
}
}
}
function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, displayName) {
verify(mapStateToProps, 'mapStateToProps', displayName);
verify(mapDispatchToProps, 'mapDispatchToProps', displayName);
verify(mergeProps, 'mergeProps', displayName);
}
function impureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch) {
return function impureFinalPropsSelector(state, ownProps) {
return mergeProps(mapStateToProps(state, ownProps), mapDispatchToProps(dispatch, ownProps), ownProps);
};
}
function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, _ref) {
var areStatesEqual = _ref.areStatesEqual,
areOwnPropsEqual = _ref.areOwnPropsEqual,
areStatePropsEqual = _ref.areStatePropsEqual;
var hasRunAtLeastOnce = false;
var state;
var ownProps;
var stateProps;
var dispatchProps;
var mergedProps;
function handleFirstCall(firstState, firstOwnProps) {
state = firstState;
ownProps = firstOwnProps;
stateProps = mapStateToProps(state, ownProps);
dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
hasRunAtLeastOnce = true;
return mergedProps;
}
function handleNewPropsAndNewState() {
stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewProps() {
if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewState() {
var nextStateProps = mapStateToProps(state, ownProps);
var statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps);
stateProps = nextStateProps;
if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleSubsequentCalls(nextState, nextOwnProps) {
var propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);
var stateChanged = !areStatesEqual(nextState, state);
state = nextState;
ownProps = nextOwnProps;
if (propsChanged && stateChanged) return handleNewPropsAndNewState();
if (propsChanged) return handleNewProps();
if (stateChanged) return handleNewState();
return mergedProps;
}
return function pureFinalPropsSelector(nextState, nextOwnProps) {
return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps);
};
} // TODO: Add more comments
// If pure is true, the selector returned by selectorFactory will memoize its results,
// allowing connectAdvanced's shouldComponentUpdate to return false if final
// props have not changed. If false, the selector will always return a new
// object and shouldComponentUpdate will always return true.
function finalPropsSelectorFactory(dispatch, _ref2) {
var initMapStateToProps = _ref2.initMapStateToProps,
initMapDispatchToProps = _ref2.initMapDispatchToProps,
initMergeProps = _ref2.initMergeProps,
options = _objectWithoutPropertiesLoose(_ref2, ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"]);
var mapStateToProps = initMapStateToProps(dispatch, options);
var mapDispatchToProps = initMapDispatchToProps(dispatch, options);
var mergeProps = initMergeProps(dispatch, options);
{
verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName);
}
var selectorFactory = options.pure ? pureFinalPropsSelectorFactory : impureFinalPropsSelectorFactory;
return selectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);
}
/*
connect is a facade over connectAdvanced. It turns its args into a compatible
selectorFactory, which has the signature:
(dispatch, options) => (nextState, nextOwnProps) => nextFinalProps
connect passes its args to connectAdvanced as options, which will in turn pass them to
selectorFactory each time a Connect component instance is instantiated or hot reloaded.
selectorFactory returns a final props selector from its mapStateToProps,
mapStateToPropsFactories, mapDispatchToProps, mapDispatchToPropsFactories, mergeProps,
mergePropsFactories, and pure args.
The resulting final props selector is called by the Connect component instance whenever
it receives new props or store state.
*/
function match(arg, factories, name) {
for (var i = factories.length - 1; i >= 0; i--) {
var result = factories[i](arg);
if (result) return result;
}
return function (dispatch, options) {
throw new Error("Invalid value of type " + typeof arg + " for " + name + " argument when connecting component " + options.wrappedComponentName + ".");
};
}
function strictEqual(a, b) {
return a === b;
} // createConnect with default args builds the 'official' connect behavior. Calling it with
// different options opens up some testing and extensibility scenarios
function createConnect(_temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$connectHOC = _ref.connectHOC,
connectHOC = _ref$connectHOC === void 0 ? connectAdvanced : _ref$connectHOC,
_ref$mapStateToPropsF = _ref.mapStateToPropsFactories,
mapStateToPropsFactories = _ref$mapStateToPropsF === void 0 ? defaultMapStateToPropsFactories : _ref$mapStateToPropsF,
_ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories,
mapDispatchToPropsFactories = _ref$mapDispatchToPro === void 0 ? defaultMapDispatchToPropsFactories : _ref$mapDispatchToPro,
_ref$mergePropsFactor = _ref.mergePropsFactories,
mergePropsFactories = _ref$mergePropsFactor === void 0 ? defaultMergePropsFactories : _ref$mergePropsFactor,
_ref$selectorFactory = _ref.selectorFactory,
selectorFactory = _ref$selectorFactory === void 0 ? finalPropsSelectorFactory : _ref$selectorFactory;
return function connect(mapStateToProps, mapDispatchToProps, mergeProps, _ref2) {
if (_ref2 === void 0) {
_ref2 = {};
}
var _ref3 = _ref2,
_ref3$pure = _ref3.pure,
pure = _ref3$pure === void 0 ? true : _ref3$pure,
_ref3$areStatesEqual = _ref3.areStatesEqual,
areStatesEqual = _ref3$areStatesEqual === void 0 ? strictEqual : _ref3$areStatesEqual,
_ref3$areOwnPropsEqua = _ref3.areOwnPropsEqual,
areOwnPropsEqual = _ref3$areOwnPropsEqua === void 0 ? shallowEqual : _ref3$areOwnPropsEqua,
_ref3$areStatePropsEq = _ref3.areStatePropsEqual,
areStatePropsEqual = _ref3$areStatePropsEq === void 0 ? shallowEqual : _ref3$areStatePropsEq,
_ref3$areMergedPropsE = _ref3.areMergedPropsEqual,
areMergedPropsEqual = _ref3$areMergedPropsE === void 0 ? shallowEqual : _ref3$areMergedPropsE,
extraOptions = _objectWithoutPropertiesLoose(_ref3, ["pure", "areStatesEqual", "areOwnPropsEqual", "areStatePropsEqual", "areMergedPropsEqual"]);
var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps');
var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps');
var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps');
return connectHOC(selectorFactory, _extends({
// used in error messages
methodName: 'connect',
// used to compute Connect's displayName from the wrapped component's displayName.
getDisplayName: function getDisplayName(name) {
return "Connect(" + name + ")";
},
// if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes
shouldHandleStateChanges: Boolean(mapStateToProps),
// passed through to selectorFactory
initMapStateToProps: initMapStateToProps,
initMapDispatchToProps: initMapDispatchToProps,
initMergeProps: initMergeProps,
pure: pure,
areStatesEqual: areStatesEqual,
areOwnPropsEqual: areOwnPropsEqual,
areStatePropsEqual: areStatePropsEqual,
areMergedPropsEqual: areMergedPropsEqual
}, extraOptions));
};
}
var connect = createConnect();
/**
* A hook to access the value of the `ReactReduxContext`. This is a low-level
* hook that you should usually not need to call directly.
*
* @returns {any} the value of the `ReactReduxContext`
*
* @example
*
* import React from 'react'
* import { useReduxContext } from 'react-redux'
*
* export const CounterComponent = ({ value }) => {
* const { store } = useReduxContext()
* return <div>{store.getState()}</div>
* }
*/
function useReduxContext() {
var contextValue = React.useContext(ReactReduxContext);
invariant_1(contextValue, 'could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
return contextValue;
}
/**
* A hook to access the redux store.
*
* @returns {any} the redux store
*
* @example
*
* import React from 'react'
* import { useStore } from 'react-redux'
*
* export const ExampleComponent = () => {
* const store = useStore()
* return <div>{store.getState()}</div>
* }
*/
function useStore() {
var _useReduxContext = useReduxContext(),
store = _useReduxContext.store;
return store;
}
/**
* A hook to access the redux `dispatch` function. Note that in most cases where you
* might want to use this hook it is recommended to use `useActions` instead to bind
* action creators to the `dispatch` function.
*
* @returns {any|function} redux store's `dispatch` function
*
* @example
*
* import React, { useCallback } from 'react'
* import { useReduxDispatch } from 'react-redux'
*
* export const CounterComponent = ({ value }) => {
* const dispatch = useDispatch()
* const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])
* return (
* <div>
* <span>{value}</span>
* <button onClick={increaseCounter}>Increase counter</button>
* </div>
* )
* }
*/
function useDispatch() {
var store = useStore();
return store.dispatch;
}
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser. We need useLayoutEffect to ensure the store
// subscription callback always has the selector from the latest render commit
// available, otherwise a store update may happen between render and the effect,
// which may cause missed updates; we also must ensure the store subscription
// is created synchronously, otherwise a store update may occur before the
// subscription is created and an inconsistent state may be observed
var useIsomorphicLayoutEffect$1 = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
var refEquality = function refEquality(a, b) {
return a === b;
};
/**
* A hook to access the redux store's state. This hook takes a selector function
* as an argument. The selector is called with the store state.
*
* This hook takes an optional equality comparison function as the second parameter
* that allows you to customize the way the selected state is compared to determine
* whether the component needs to be re-rendered.
*
* @param {Function} selector the selector function
* @param {Function=} equalityFn the function that will be used to determine equality
*
* @returns {any} the selected state
*
* @example
*
* import React from 'react'
* import { useSelector } from 'react-redux'
*
* export const CounterComponent = () => {
* const counter = useSelector(state => state.counter)
* return <div>{counter}</div>
* }
*/
function useSelector(selector, equalityFn) {
if (equalityFn === void 0) {
equalityFn = refEquality;
}
invariant_1(selector, "You must pass a selector to useSelectors");
var _useReduxContext = useReduxContext(),
store = _useReduxContext.store,
contextSub = _useReduxContext.subscription;
var _useReducer = React.useReducer(function (s) {
return s + 1;
}, 0),
forceRender = _useReducer[1];
var subscription = React.useMemo(function () {
return new Subscription(store, contextSub);
}, [store, contextSub]);
var latestSubscriptionCallbackError = React.useRef();
var latestSelector = React.useRef();
var latestSelectedState = React.useRef();
var selectedState;
try {
if (selector !== latestSelector.current || latestSubscriptionCallbackError.current) {
selectedState = selector(store.getState());
} else {
selectedState = latestSelectedState.current;
}
} catch (err) {
var errorMessage = "An error occured while selecting the store state: " + err.message + ".";
if (latestSubscriptionCallbackError.current) {
errorMessage += "\nThe error may be correlated with this previous error:\n" + latestSubscriptionCallbackError.current.stack + "\n\nOriginal stack trace:";
}
throw new Error(errorMessage);
}
useIsomorphicLayoutEffect$1(function () {
latestSelector.current = selector;
latestSelectedState.current = selectedState;
latestSubscriptionCallbackError.current = undefined;
});
useIsomorphicLayoutEffect$1(function () {
function checkForUpdates() {
try {
var newSelectedState = latestSelector.current(store.getState());
if (equalityFn(newSelectedState, latestSelectedState.current)) {
return;
}
latestSelectedState.current = newSelectedState;
} catch (err) {
// we ignore all errors here, since when the component
// is re-rendered, the selectors are called again, and
// will throw again, if neither props nor store state
// changed
latestSubscriptionCallbackError.current = err;
}
forceRender({});
}
subscription.onStateChange = checkForUpdates;
subscription.trySubscribe();
checkForUpdates();
return function () {
return subscription.tryUnsubscribe();
};
}, [store, subscription]);
return selectedState;
}
/* eslint-disable import/no-unresolved */
setBatch(reactDom.unstable_batchedUpdates);
Object.defineProperty(exports, 'batch', {
enumerable: true,
get: function () {
return reactDom.unstable_batchedUpdates;
}
});
exports.Provider = Provider;
exports.ReactReduxContext = ReactReduxContext;
exports.connect = connect;
exports.connectAdvanced = connectAdvanced;
exports.shallowEqual = shallowEqual;
exports.useDispatch = useDispatch;
exports.useSelector = useSelector;
exports.useStore = useStore;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
ajax/libs/material-ui/4.9.2/esm/RadioGroup/RadioGroup.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import FormGroup from '../FormGroup';
import useForkRef from '../utils/useForkRef';
import useControlled from '../utils/useControlled';
import RadioGroupContext from './RadioGroupContext';
var RadioGroup = React.forwardRef(function RadioGroup(props, ref) {
var actions = props.actions,
children = props.children,
name = props.name,
valueProp = props.value,
onChange = props.onChange,
other = _objectWithoutProperties(props, ["actions", "children", "name", "value", "onChange"]);
var rootRef = React.useRef(null);
var _useControlled = useControlled({
controlled: valueProp,
default: props.defaultValue,
name: 'RadioGroup'
}),
_useControlled2 = _slicedToArray(_useControlled, 2),
value = _useControlled2[0],
setValue = _useControlled2[1];
React.useImperativeHandle(actions, function () {
return {
focus: function focus() {
var input = rootRef.current.querySelector('input:not(:disabled):checked');
if (!input) {
input = rootRef.current.querySelector('input:not(:disabled)');
}
if (input) {
input.focus();
}
}
};
}, []);
var handleRef = useForkRef(ref, rootRef);
var handleChange = function handleChange(event) {
setValue(event.target.value);
if (onChange) {
onChange(event, event.target.value);
}
};
return React.createElement(RadioGroupContext.Provider, {
value: {
name: name,
onChange: handleChange,
value: value
}
}, React.createElement(FormGroup, _extends({
role: "radiogroup",
ref: handleRef
}, other), children));
});
process.env.NODE_ENV !== "production" ? RadioGroup.propTypes = {
/**
* @ignore
*/
actions: PropTypes.shape({
current: PropTypes.object
}),
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* The default `input` element value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* The name used to reference the value of the control.
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when a radio button is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onKeyDown: PropTypes.func,
/**
* Value of the selected radio button. The DOM API casts this to a string.
*/
value: PropTypes.any
} : void 0;
export default RadioGroup; |
ajax/libs/material-ui/4.9.2/esm/Table/Tablelvl2Context.js | cdnjs/cdnjs | import React from 'react';
/**
* @ignore - internal component.
*/
var Tablelvl2Context = React.createContext();
if (process.env.NODE_ENV !== 'production') {
Tablelvl2Context.displayName = 'Tablelvl2Context';
}
export default Tablelvl2Context; |
ajax/libs/material-ui/4.11.3/esm/styles/useTheme.js | cdnjs/cdnjs | import { useTheme as useThemeWithoutDefault } from '@material-ui/styles';
import React from 'react';
import defaultTheme from './defaultTheme';
export default function useTheme() {
var theme = useThemeWithoutDefault() || defaultTheme;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useDebugValue(theme);
}
return theme;
} |
ajax/libs/react-native-web/0.0.0-376ccc31b/modules/UnimplementedView/index.js | cdnjs/cdnjs | function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* 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.
*
*
*/
import View from '../../exports/View';
import React from 'react';
/**
* Common implementation for a simple stubbed view.
*/
var UnimplementedView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(UnimplementedView, _React$Component);
function UnimplementedView() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = UnimplementedView.prototype;
_proto.setNativeProps = function setNativeProps() {// Do nothing.
};
_proto.render = function render() {
return React.createElement(View, {
style: [unimplementedViewStyles, this.props.style]
}, this.props.children);
};
return UnimplementedView;
}(React.Component);
var unimplementedViewStyles = process.env.NODE_ENV !== 'production' ? {
alignSelf: 'flex-start',
borderColor: 'red',
borderWidth: 1
} : {};
export default UnimplementedView; |
ajax/libs/primereact/6.5.1/panelmenu/panelmenu.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { UniqueComponentId, classNames, ObjectUtils, CSSTransition } from 'primereact/core';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PanelMenuSub = /*#__PURE__*/function (_Component) {
_inherits(PanelMenuSub, _Component);
var _super = _createSuper(PanelMenuSub);
function PanelMenuSub(props) {
var _this;
_classCallCheck(this, PanelMenuSub);
_this = _super.call(this, props);
_this.state = {
activeItem: _this.findActiveItem()
};
return _this;
}
_createClass(PanelMenuSub, [{
key: "onItemClick",
value: function onItemClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
var activeItem = this.state.activeItem;
var active = this.isItemActive(item);
if (active) {
item.expanded = false;
this.setState({
activeItem: this.props.multiple ? activeItem.filter(function (a_item) {
return a_item !== item;
}) : null
});
} else {
if (!this.props.multiple && activeItem) {
activeItem.expanded = false;
}
item.expanded = true;
this.setState({
activeItem: this.props.multiple ? [].concat(_toConsumableArray(activeItem || []), [item]) : item
});
}
}
}, {
key: "findActiveItem",
value: function findActiveItem() {
if (this.props.model) {
if (this.props.multiple) {
return this.props.model.filter(function (item) {
return item.expanded;
});
} else {
var activeItem = null;
this.props.model.forEach(function (item) {
if (item.expanded) {
if (!activeItem) activeItem = item;else item.expanded = false;
}
});
return activeItem;
}
}
return null;
}
}, {
key: "isItemActive",
value: function isItemActive(item) {
return this.state.activeItem && (this.props.multiple ? this.state.activeItem.indexOf(item) > -1 : this.state.activeItem === item);
}
}, {
key: "renderSeparator",
value: function renderSeparator(index) {
return /*#__PURE__*/React.createElement("li", {
key: 'separator_' + index,
className: "p-menu-separator"
});
}
}, {
key: "renderSubmenu",
value: function renderSubmenu(item, active) {
var submenuWrapperClassName = classNames('p-toggleable-content', {
'p-toggleable-content-collapsed': !active
});
var submenuContentRef = /*#__PURE__*/React.createRef();
if (item.items) {
return /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: submenuContentRef,
classNames: "p-toggleable-content",
timeout: {
enter: 1000,
exit: 450
},
in: active,
unmountOnExit: true
}, /*#__PURE__*/React.createElement("div", {
ref: submenuContentRef,
className: submenuWrapperClassName
}, /*#__PURE__*/React.createElement(PanelMenuSub, {
model: item.items,
multiple: this.props.multiple
})));
}
return null;
}
}, {
key: "renderMenuitem",
value: function renderMenuitem(item, index) {
var _this2 = this;
var active = this.isItemActive(item);
var className = classNames('p-menuitem', item.className);
var linkClassName = classNames('p-menuitem-link', {
'p-disabled': item.disabled
});
var iconClassName = classNames('p-menuitem-icon', item.icon);
var submenuIconClassName = classNames('p-panelmenu-icon pi pi-fw', {
'pi-angle-right': !active,
'pi-angle-down': active
});
var icon = item.icon && /*#__PURE__*/React.createElement("span", {
className: iconClassName
});
var label = item.label && /*#__PURE__*/React.createElement("span", {
className: "p-menuitem-text"
}, item.label);
var submenuIcon = item.items && /*#__PURE__*/React.createElement("span", {
className: submenuIconClassName
});
var submenu = this.renderSubmenu(item, active);
var content = /*#__PURE__*/React.createElement("a", {
href: item.url || '#',
className: linkClassName,
target: item.target,
onClick: function onClick(event) {
return _this2.onItemClick(event, item, index);
},
role: "menuitem",
"aria-disabled": item.disabled
}, submenuIcon, icon, label);
if (item.template) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this2.onItemClick(event, item, index);
},
className: linkClassName,
labelClassName: 'p-menuitem-text',
iconClassName: iconClassName,
submenuIconClassName: submenuIconClassName,
element: content,
props: this.props,
leaf: !item.items,
active: active
};
content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
key: item.label + '_' + index,
className: className,
style: item.style,
role: "none"
}, content, submenu);
}
}, {
key: "renderItem",
value: function renderItem(item, index) {
if (item.separator) return this.renderSeparator(index);else return this.renderMenuitem(item, index);
}
}, {
key: "renderMenu",
value: function renderMenu() {
var _this3 = this;
if (this.props.model) {
return this.props.model.map(function (item, index) {
return _this3.renderItem(item, index);
});
}
return null;
}
}, {
key: "render",
value: function render() {
var className = classNames('p-submenu-list', this.props.className);
var menu = this.renderMenu();
return /*#__PURE__*/React.createElement("ul", {
className: className,
role: "tree"
}, menu);
}
}]);
return PanelMenuSub;
}(Component);
_defineProperty(PanelMenuSub, "defaultProps", {
model: null,
multiple: false
});
var PanelMenu = /*#__PURE__*/function (_Component2) {
_inherits(PanelMenu, _Component2);
var _super2 = _createSuper(PanelMenu);
function PanelMenu(props) {
var _this4;
_classCallCheck(this, PanelMenu);
_this4 = _super2.call(this, props);
_this4.state = {
id: props.id,
activeItem: _this4.findActiveItem()
};
return _this4;
}
_createClass(PanelMenu, [{
key: "onItemClick",
value: function onItemClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
var activeItem = this.state.activeItem;
var active = this.isItemActive(item);
if (active) {
item.expanded = false;
this.setState({
activeItem: this.props.multiple ? activeItem.filter(function (a_item) {
return a_item !== item;
}) : null
});
} else {
if (!this.props.multiple && activeItem) {
activeItem.expanded = false;
}
item.expanded = true;
this.setState({
activeItem: this.props.multiple ? [].concat(_toConsumableArray(activeItem || []), [item]) : item
});
}
}
}, {
key: "findActiveItem",
value: function findActiveItem() {
if (this.props.model) {
if (this.props.multiple) {
return this.props.model.filter(function (item) {
return item.expanded;
});
} else {
var activeItem = null;
this.props.model.forEach(function (item) {
if (item.expanded) {
if (!activeItem) activeItem = item;else item.expanded = false;
}
});
return activeItem;
}
}
return null;
}
}, {
key: "isItemActive",
value: function isItemActive(item) {
return this.state.activeItem && (this.props.multiple ? this.state.activeItem.indexOf(item) > -1 : this.state.activeItem === item);
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (!this.state.id) {
this.setState({
id: UniqueComponentId()
});
}
}
}, {
key: "renderPanel",
value: function renderPanel(item, index) {
var _this5 = this;
var active = this.isItemActive(item);
var className = classNames('p-panelmenu-panel', item.className);
var headerClassName = classNames('p-component p-panelmenu-header', {
'p-highlight': active,
'p-disabled': item.disabled
});
var submenuIconClassName = classNames('p-panelmenu-icon pi', {
'pi-chevron-right': !active,
' pi-chevron-down': active
});
var iconClassName = classNames('p-menuitem-icon', item.icon);
var submenuIcon = item.items && /*#__PURE__*/React.createElement("span", {
className: submenuIconClassName
});
var itemIcon = item.icon && /*#__PURE__*/React.createElement("span", {
className: iconClassName
});
var label = item.label && /*#__PURE__*/React.createElement("span", {
className: "p-menuitem-text"
}, item.label);
var contentWrapperClassName = classNames('p-toggleable-content', {
'p-toggleable-content-collapsed': !active
});
var menuContentRef = /*#__PURE__*/React.createRef();
var content = /*#__PURE__*/React.createElement("a", {
href: item.url || '#',
className: "p-panelmenu-header-link",
onClick: function onClick(e) {
return _this5.onItemClick(e, item);
},
"aria-expanded": active,
id: this.state.id + '_header',
"aria-controls": this.state.id + 'content',
"aria-disabled": item.disabled
}, submenuIcon, itemIcon, label);
if (item.template) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this5.onItemClick(event, item);
},
className: 'p-panelmenu-header-link',
labelClassName: 'p-menuitem-text',
submenuIconClassName: submenuIconClassName,
iconClassName: iconClassName,
element: content,
props: this.props,
leaf: !item.items,
active: active
};
content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("div", {
key: item.label + '_' + index,
className: className,
style: item.style
}, /*#__PURE__*/React.createElement("div", {
className: headerClassName,
style: item.style
}, content), /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: menuContentRef,
classNames: "p-toggleable-content",
timeout: {
enter: 1000,
exit: 450
},
in: active,
unmountOnExit: true,
options: this.props.transitionOptions
}, /*#__PURE__*/React.createElement("div", {
ref: menuContentRef,
className: contentWrapperClassName,
role: "region",
id: this.state.id + '_content',
"aria-labelledby": this.state.id + '_header'
}, /*#__PURE__*/React.createElement("div", {
className: "p-panelmenu-content"
}, /*#__PURE__*/React.createElement(PanelMenuSub, {
model: item.items,
className: "p-panelmenu-root-submenu",
multiple: this.props.multiple
})))));
}
}, {
key: "renderPanels",
value: function renderPanels() {
var _this6 = this;
if (this.props.model) {
return this.props.model.map(function (item, index) {
return _this6.renderPanel(item, index);
});
}
return null;
}
}, {
key: "render",
value: function render() {
var className = classNames('p-panelmenu p-component', this.props.className);
var panels = this.renderPanels();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: className,
style: this.props.style
}, panels);
}
}]);
return PanelMenu;
}(Component);
_defineProperty(PanelMenu, "defaultProps", {
id: null,
model: null,
style: null,
className: null,
multiple: false,
transitionOptions: null
});
export { PanelMenu };
|
ajax/libs/react-instantsearch/6.8.2/Dom.js | cdnjs/cdnjs | /*! React InstantSearch 6.8.2 | © Algolia, inc. | https://github.com/algolia/react-instantsearch */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = global || self, factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Dom = {}), global.React));
}(this, function (exports, React) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
function _extends() {
_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;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
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 _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
function _typeof(obj) {
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
_typeof = function _typeof(obj) {
return _typeof2(obj);
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
/* global Map:readonly, Set:readonly, ArrayBuffer:readonly */
var hasElementType = typeof Element !== 'undefined';
var hasMap = typeof Map === 'function';
var hasSet = typeof Set === 'function';
var hasArrayBuffer = typeof ArrayBuffer === 'function';
// Note: We **don't** need `envHasBigInt64Array` in fde es6/index.js
function equal(a, b) {
// START: fast-deep-equal es6/index.js 3.1.1
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
// START: Modifications:
// 1. Extra `has<Type> &&` helpers in initial condition allow es6 code
// to co-exist with es5.
// 2. Replace `for of` with es5 compliant iteration using `for`.
// Basically, take:
//
// ```js
// for (i of a.entries())
// if (!b.has(i[0])) return false;
// ```
//
// ... and convert to:
//
// ```js
// it = a.entries();
// while (!(i = it.next()).done)
// if (!b.has(i.value[0])) return false;
// ```
//
// **Note**: `i` access switches to `i.value`.
var it;
if (hasMap && (a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
it = a.entries();
while (!(i = it.next()).done)
if (!b.has(i.value[0])) return false;
it = a.entries();
while (!(i = it.next()).done)
if (!equal(i.value[1], b.get(i.value[0]))) return false;
return true;
}
if (hasSet && (a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
it = a.entries();
while (!(i = it.next()).done)
if (!b.has(i.value[0])) return false;
return true;
}
// END: Modifications
if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
// END: fast-deep-equal
// START: react-fast-compare
// custom handling for DOM elements
if (hasElementType && a instanceof Element) return false;
// custom handling for React
for (i = length; i-- !== 0;) {
if (keys[i] === '_owner' && a.$$typeof) {
// React-specific: avoid traversing React elements' _owner.
// _owner contains circular references
// and is not needed when comparing the actual elements (and not their owners)
// .$$typeof and ._store on just reasonable markers of a react element
continue;
}
// all other properties should be traversed as usual
if (!equal(a[keys[i]], b[keys[i]])) return false;
}
// END: react-fast-compare
// START: fast-deep-equal
return true;
}
return a !== a && b !== b;
}
// end fast-deep-equal
var reactFastCompare = function isEqual(a, b) {
try {
return equal(a, b);
} catch (error) {
if (((error.message || '').match(/stack|recursion/i))) {
// warn on circular references, don't crash
// browsers give this different errors name and messages:
// chrome/safari: "RangeError", "Maximum call stack size exceeded"
// firefox: "InternalError", too much recursion"
// edge: "Error", "Out of stack space"
console.warn('react-fast-compare cannot handle circular refs');
return false;
}
// some other error. we should definitely know about these
throw error;
}
};
var shallowEqual = 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;
};
var getDisplayName = function getDisplayName(Component) {
return Component.displayName || Component.name || 'UnknownComponent';
};
var resolved = Promise.resolve();
var defer = function defer(f) {
resolved.then(f);
};
var isPlainObject = function isPlainObject(value) {
return _typeof(value) === 'object' && value !== null && !Array.isArray(value);
};
var removeEmptyKey = function removeEmptyKey(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (!isPlainObject(value)) {
return;
}
if (!objectHasKeys(value)) {
delete obj[key];
} else {
removeEmptyKey(value);
}
});
return obj;
};
var removeEmptyArraysFromObject = function removeEmptyArraysFromObject(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (Array.isArray(value) && value.length === 0) {
delete obj[key];
}
});
return obj;
};
function addAbsolutePositions(hits, hitsPerPage, page) {
return hits.map(function (hit, index) {
return _objectSpread({}, hit, {
__position: hitsPerPage * page + index + 1
});
});
}
function addQueryID(hits, queryID) {
if (!queryID) {
return hits;
}
return hits.map(function (hit) {
return _objectSpread({}, hit, {
__queryID: queryID
});
});
}
function find(array, comparator) {
if (!Array.isArray(array)) {
return undefined;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return array[i];
}
}
return undefined;
}
function objectHasKeys(object) {
return object && Object.keys(object).length > 0;
} // https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620
function omit(source, excluded) {
if (source === null || source === undefined) {
return {};
}
var target = {};
var sourceKeys = Object.keys(source);
for (var i = 0; i < sourceKeys.length; i++) {
var _key = sourceKeys[i];
if (excluded.indexOf(_key) >= 0) {
// eslint-disable-next-line no-continue
continue;
}
target[_key] = source[_key];
}
return target;
}
/**
* Retrieve the value at a path of the object:
*
* @example
* getPropertyByPath(
* { test: { this: { function: [{ now: { everyone: true } }] } } },
* 'test.this.function[0].now.everyone'
* ); // true
*
* getPropertyByPath(
* { test: { this: { function: [{ now: { everyone: true } }] } } },
* ['test', 'this', 'function', 0, 'now', 'everyone']
* ); // true
*
* @param object Source object to query
* @param path either an array of properties, or a string form of the properties, separated by .
*/
var getPropertyByPath = function getPropertyByPath(object, path) {
return (Array.isArray(path) ? path : path.replace(/\[(\d+)]/g, '.$1').split('.')).reduce(function (current, key) {
return current ? current[key] : undefined;
}, object);
};
var _createContext = React.createContext({
onInternalStateUpdate: function onInternalStateUpdate() {
return undefined;
},
createHrefForState: function createHrefForState() {
return '#';
},
onSearchForFacetValues: function onSearchForFacetValues() {
return undefined;
},
onSearchStateChange: function onSearchStateChange() {
return undefined;
},
onSearchParameters: function onSearchParameters() {
return undefined;
},
store: {},
widgetsManager: {},
mainTargetedIndex: ''
}),
InstantSearchConsumer = _createContext.Consumer,
InstantSearchProvider = _createContext.Provider;
var _createContext2 = React.createContext(undefined),
IndexConsumer = _createContext2.Consumer,
IndexProvider = _createContext2.Provider;
/**
* 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 createConnectorWithoutContext(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var isWidget = typeof connectorDesc.getSearchParameters === 'function' || typeof connectorDesc.getMetadata === 'function' || typeof connectorDesc.transitionState === 'function';
return function (Composed) {
var Connector =
/*#__PURE__*/
function (_Component) {
_inherits(Connector, _Component);
function Connector(props) {
var _this;
_classCallCheck(this, Connector);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this, props));
_defineProperty(_assertThisInitialized(_this), "unsubscribe", void 0);
_defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0);
_defineProperty(_assertThisInitialized(_this), "isUnmounting", false);
_defineProperty(_assertThisInitialized(_this), "state", {
providedProps: _this.getProvidedProps(_this.props)
});
_defineProperty(_assertThisInitialized(_this), "refine", function () {
var _ref;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this.props.contextValue.onInternalStateUpdate( // refine will always be defined here because the prop is only given conditionally
(_ref = connectorDesc.refine).call.apply(_ref, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
_defineProperty(_assertThisInitialized(_this), "createURL", function () {
var _ref2;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _this.props.contextValue.createHrefForState( // refine will always be defined here because the prop is only given conditionally
(_ref2 = connectorDesc.refine).call.apply(_ref2, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
_defineProperty(_assertThisInitialized(_this), "searchForFacetValues", function () {
var _ref3;
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
_this.props.contextValue.onSearchForFacetValues( // searchForFacetValues will always be defined here because the prop is only given conditionally
(_ref3 = connectorDesc.searchForFacetValues).call.apply(_ref3, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
if (connectorDesc.getSearchParameters) {
_this.props.contextValue.onSearchParameters(connectorDesc.getSearchParameters.bind(_assertThisInitialized(_this)), {
ais: _this.props.contextValue,
multiIndexContext: _this.props.indexContextValue
}, _this.props, connectorDesc.getMetadata && connectorDesc.getMetadata.bind(_assertThisInitialized(_this)));
}
return _this;
}
_createClass(Connector, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.props.contextValue.store.subscribe(function () {
if (!_this2.isUnmounting) {
_this2.setState({
providedProps: _this2.getProvidedProps(_this2.props)
});
}
});
if (isWidget) {
this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this);
}
}
}, {
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps, nextState) {
if (typeof connectorDesc.shouldComponentUpdate === 'function') {
return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState);
}
var propsEqual = shallowEqual(this.props, nextProps);
if (this.state.providedProps === null || nextState.providedProps === null) {
if (this.state.providedProps === nextState.providedProps) {
return !propsEqual;
}
return true;
}
return !propsEqual || !shallowEqual(this.state.providedProps, nextState.providedProps);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (!reactFastCompare(prevProps, this.props)) {
this.setState({
providedProps: this.getProvidedProps(this.props)
});
if (isWidget) {
this.props.contextValue.widgetsManager.update();
if (typeof connectorDesc.transitionState === 'function') {
this.props.contextValue.onSearchStateChange(connectorDesc.transitionState.call(this, this.props, this.props.contextValue.store.getState().widgets, this.props.contextValue.store.getState().widgets));
}
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.isUnmounting = true;
if (this.unsubscribe) {
this.unsubscribe();
}
if (this.unregisterWidget) {
this.unregisterWidget();
if (typeof connectorDesc.cleanUp === 'function') {
var nextState = connectorDesc.cleanUp.call(this, this.props, this.props.contextValue.store.getState().widgets);
this.props.contextValue.store.setState(_objectSpread({}, this.props.contextValue.store.getState(), {
widgets: nextState
}));
this.props.contextValue.onSearchStateChange(removeEmptyKey(nextState));
}
}
}
}, {
key: "getProvidedProps",
value: function getProvidedProps(props) {
var _this$props$contextVa = this.props.contextValue.store.getState(),
widgets = _this$props$contextVa.widgets,
results = _this$props$contextVa.results,
resultsFacetValues = _this$props$contextVa.resultsFacetValues,
searching = _this$props$contextVa.searching,
searchingForFacetValues = _this$props$contextVa.searchingForFacetValues,
isSearchStalled = _this$props$contextVa.isSearchStalled,
metadata = _this$props$contextVa.metadata,
error = _this$props$contextVa.error;
var searchResults = {
results: results,
searching: searching,
searchingForFacetValues: searchingForFacetValues,
isSearchStalled: isSearchStalled,
error: error
};
return connectorDesc.getProvidedProps.call(this, props, widgets, searchResults, metadata, // @MAJOR: move this attribute on the `searchResults` it doesn't
// makes sense to have it into a separate argument. The search
// flags are on the object why not the results?
resultsFacetValues);
}
}, {
key: "getSearchParameters",
value: function getSearchParameters(searchParameters) {
if (typeof connectorDesc.getSearchParameters === 'function') {
return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.props.contextValue.store.getState().widgets);
}
return null;
}
}, {
key: "getMetadata",
value: function getMetadata(nextWidgetsState) {
if (typeof connectorDesc.getMetadata === 'function') {
return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState);
}
return {};
}
}, {
key: "transitionState",
value: function transitionState(prevWidgetsState, nextWidgetsState) {
if (typeof connectorDesc.transitionState === 'function') {
return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState);
}
return nextWidgetsState;
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
contextValue = _this$props.contextValue,
props = _objectWithoutProperties(_this$props, ["contextValue"]);
var providedProps = this.state.providedProps;
if (providedProps === null) {
return null;
}
var refineProps = typeof connectorDesc.refine === 'function' ? {
refine: this.refine,
createURL: this.createURL
} : {};
var searchForFacetValuesProps = typeof connectorDesc.searchForFacetValues === 'function' ? {
searchForItems: this.searchForFacetValues
} : {};
return React__default.createElement(Composed, _extends({}, props, providedProps, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(React.Component);
_defineProperty(Connector, "displayName", "".concat(connectorDesc.displayName, "(").concat(getDisplayName(Composed), ")"));
_defineProperty(Connector, "propTypes", connectorDesc.propTypes);
_defineProperty(Connector, "defaultProps", connectorDesc.defaultProps);
return Connector;
};
}
var createConnectorWithContext = function createConnectorWithContext(connectorDesc) {
return function (Composed) {
var Connector = createConnectorWithoutContext(connectorDesc)(Composed);
var ConnectorWrapper = function ConnectorWrapper(props) {
return React__default.createElement(InstantSearchConsumer, null, function (contextValue) {
return React__default.createElement(IndexConsumer, null, function (indexContextValue) {
return React__default.createElement(Connector, _extends({
contextValue: contextValue,
indexContextValue: indexContextValue
}, props));
});
});
};
return ConnectorWrapper;
};
};
var HIGHLIGHT_TAGS = {
highlightPreTag: "<ais-highlight-0000000000>",
highlightPostTag: "</ais-highlight-0000000000>"
};
/**
* 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, isHighlighted: boolean}.
*/
function parseHighlightedAttribute(_ref) {
var preTag = _ref.preTag,
postTag = _ref.postTag,
_ref$highlightedValue = _ref.highlightedValue,
highlightedValue = _ref$highlightedValue === void 0 ? '' : _ref$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;
}
/**
* Find an highlighted attribute given an `attribute` 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
* highlightPostTag 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} attribute - the highlighted attribute to look for
* @param {object} hit - the actual hit returned by Algolia.
* @return {object[]} - An array of {value: string, isHighlighted: boolean}.
*/
function parseAlgoliaHit(_ref2) {
var _ref2$preTag = _ref2.preTag,
preTag = _ref2$preTag === void 0 ? '<em>' : _ref2$preTag,
_ref2$postTag = _ref2.postTag,
postTag = _ref2$postTag === void 0 ? '</em>' : _ref2$postTag,
highlightProperty = _ref2.highlightProperty,
attribute = _ref2.attribute,
hit = _ref2.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = getPropertyByPath(hit[highlightProperty], attribute) || {};
if (Array.isArray(highlightObject)) {
return highlightObject.map(function (item) {
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: item.value
});
});
}
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: highlightObject.value
});
}
var version = '6.8.2';
function translatable(defaultTranslations) {
return function (Composed) {
var Translatable =
/*#__PURE__*/
function (_Component) {
_inherits(Translatable, _Component);
function Translatable() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, Translatable);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Translatable)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "translate", function (key) {
var translations = _this.props.translations;
var translation = translations && translations.hasOwnProperty(key) ? translations[key] : defaultTranslations[key];
if (typeof translation === 'function') {
for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
params[_key2 - 1] = arguments[_key2];
}
return translation.apply(void 0, params);
}
return translation;
});
return _this;
}
_createClass(Translatable, [{
key: "render",
value: function render() {
return React__default.createElement(Composed, _extends({
translate: this.translate
}, this.props));
}
}]);
return Translatable;
}(React.Component);
var name = Composed.displayName || Composed.name || 'UnknownComponent';
Translatable.displayName = "Translatable(".concat(name, ")");
return Translatable;
};
}
function getIndexId(context) {
return hasMultipleIndices(context) ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex;
}
function getResults(searchResults, context) {
if (searchResults.results) {
if (searchResults.results.hits) {
return searchResults.results;
}
var indexId = getIndexId(context);
if (searchResults.results[indexId]) {
return searchResults.results[indexId];
}
}
return null;
}
function hasMultipleIndices(context) {
return context && context.multiIndexContext;
} // eslint-disable-next-line max-params
function refineValue(searchState, nextRefinement, context, resetPage, namespace) {
if (hasMultipleIndices(context)) {
var indexId = getIndexId(context);
return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, indexId, resetPage);
} else {
// When we have a multi index page with shared widgets we should also
// reset their page to 1 if the resetPage is provided. Otherwise the
// indices will always be reset
// see: https://github.com/algolia/react-instantsearch/issues/310
// see: https://github.com/algolia/react-instantsearch/issues/637
if (searchState.indices && resetPage) {
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, indexId, resetPage) {
var page = resetPage ? {
page: 1
} : undefined;
var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], nextRefinement, page))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, nextRefinement, page)));
return _objectSpread({}, searchState, {
indices: state
});
}
function refineSingleIndex(searchState, nextRefinement, resetPage) {
var page = resetPage ? {
page: 1
} : undefined;
return _objectSpread({}, searchState, nextRefinement, page);
} // eslint-disable-next-line max-params
function refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) {
var _objectSpread4;
var page = resetPage ? {
page: 1
} : undefined;
var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], (_objectSpread4 = {}, _defineProperty(_objectSpread4, namespace, _objectSpread({}, searchState.indices[indexId][namespace], nextRefinement)), _defineProperty(_objectSpread4, "page", 1), _objectSpread4)))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread(_defineProperty({}, namespace, nextRefinement), page)));
return _objectSpread({}, searchState, {
indices: state
});
}
function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) {
var page = resetPage ? {
page: 1
} : undefined;
return _objectSpread({}, searchState, _defineProperty({}, namespace, _objectSpread({}, 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
};
}
function hasRefinements(_ref) {
var multiIndex = _ref.multiIndex,
indexId = _ref.indexId,
namespace = _ref.namespace,
attributeName = _ref.attributeName,
id = _ref.id,
searchState = _ref.searchState;
if (multiIndex && namespace) {
return searchState.indices && searchState.indices[indexId] && searchState.indices[indexId][namespace] && Object.hasOwnProperty.call(searchState.indices[indexId][namespace], attributeName);
}
if (multiIndex) {
return searchState.indices && searchState.indices[indexId] && Object.hasOwnProperty.call(searchState.indices[indexId], id);
}
if (namespace) {
return searchState[namespace] && Object.hasOwnProperty.call(searchState[namespace], attributeName);
}
return Object.hasOwnProperty.call(searchState, id);
}
function getRefinements(_ref2) {
var multiIndex = _ref2.multiIndex,
indexId = _ref2.indexId,
namespace = _ref2.namespace,
attributeName = _ref2.attributeName,
id = _ref2.id,
searchState = _ref2.searchState;
if (multiIndex && namespace) {
return searchState.indices[indexId][namespace][attributeName];
}
if (multiIndex) {
return searchState.indices[indexId][id];
}
if (namespace) {
return searchState[namespace][attributeName];
}
return searchState[id];
}
function getCurrentRefinementValue(props, searchState, context, id, defaultValue) {
var indexId = getIndexId(context);
var _getNamespaceAndAttri = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri.namespace,
attributeName = _getNamespaceAndAttri.attributeName;
var multiIndex = hasMultipleIndices(context);
var args = {
multiIndex: multiIndex,
indexId: indexId,
namespace: namespace,
attributeName: attributeName,
id: id,
searchState: searchState
};
var hasRefinementsValue = hasRefinements(args);
if (hasRefinementsValue) {
return getRefinements(args);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return defaultValue;
}
function cleanUpValue(searchState, context, id) {
var indexId = getIndexId(context);
var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri2.namespace,
attributeName = _getNamespaceAndAttri2.attributeName;
if (hasMultipleIndices(context) && Boolean(searchState.indices)) {
return cleanUpValueWithMultiIndex({
attribute: attributeName,
searchState: searchState,
indexId: indexId,
id: id,
namespace: namespace
});
}
return cleanUpValueWithSingleIndex({
attribute: attributeName,
searchState: searchState,
id: id,
namespace: namespace
});
}
function cleanUpValueWithSingleIndex(_ref3) {
var searchState = _ref3.searchState,
id = _ref3.id,
namespace = _ref3.namespace,
attribute = _ref3.attribute;
if (namespace) {
return _objectSpread({}, searchState, _defineProperty({}, namespace, omit(searchState[namespace], [attribute])));
}
return omit(searchState, [id]);
}
function cleanUpValueWithMultiIndex(_ref4) {
var searchState = _ref4.searchState,
indexId = _ref4.indexId,
id = _ref4.id,
namespace = _ref4.namespace,
attribute = _ref4.attribute;
var indexSearchState = searchState.indices[indexId];
if (namespace && indexSearchState) {
return _objectSpread({}, searchState, {
indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, indexSearchState, _defineProperty({}, namespace, omit(indexSearchState[namespace], [attribute])))))
});
}
if (indexSearchState) {
return _objectSpread({}, searchState, {
indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, omit(indexSearchState, [id])))
});
}
return searchState;
}
function getId() {
return 'configure';
}
var connectConfigure = createConnectorWithContext({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var children = props.children,
contextValue = props.contextValue,
indexContextValue = props.indexContextValue,
items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]);
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
var children = props.children,
contextValue = props.contextValue,
indexContextValue = props.indexContextValue,
items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]);
var propKeys = Object.keys(props);
var nonPresentKeys = this._props ? Object.keys(this._props).filter(function (prop) {
return propKeys.indexOf(prop) === -1;
}) : [];
this._props = props;
var nextValue = _defineProperty({}, id, _objectSpread({}, omit(nextSearchState[id], nonPresentKeys), items));
return refineValue(nextSearchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
var id = getId();
var indexId = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var subState = hasMultipleIndices({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) && searchState.indices ? searchState.indices[indexId] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = _defineProperty({}, id, configureState);
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
/**
* 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 algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, Configure, Hits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <Configure hitsPerPage={5} />
* <Hits />
* </InstantSearch>
* );
*/
var Configure = connectConfigure(function Configure() {
return null;
});
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
if (typeof global$1.setTimeout === 'function') ;
if (typeof global$1.clearTimeout === 'function') ;
// 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() };
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function clone(value) {
if (typeof value === 'object' && value !== null) {
return _merge(Array.isArray(value) ? [] : {}, value);
}
return value;
}
function isObjectOrArrayOrFunction(value) {
return (
typeof value === 'function' ||
Array.isArray(value) ||
Object.prototype.toString.call(value) === '[object Object]'
);
}
function _merge(target, source) {
if (target === source) {
return target;
}
for (var key in source) {
if (!Object.prototype.hasOwnProperty.call(source, key)) {
continue;
}
var sourceVal = source[key];
var targetVal = target[key];
if (typeof targetVal !== 'undefined' && typeof sourceVal === 'undefined') {
continue;
}
if (isObjectOrArrayOrFunction(targetVal) && isObjectOrArrayOrFunction(sourceVal)) {
target[key] = _merge(targetVal, sourceVal);
} else {
target[key] = clone(sourceVal);
}
}
return target;
}
/**
* This method is like Object.assign, but recursively merges own and inherited
* enumerable keyed properties of source objects into the destination object.
*
* NOTE: this behaves like lodash/merge, but:
* - does mutate functions if they are a source
* - treats non-plain objects as plain
* - does not work for circular objects
* - treats sparse arrays as sparse
* - does not convert Array-like objects (Arguments, NodeLists, etc.) to arrays
*
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
*/
function merge(target) {
if (!isObjectOrArrayOrFunction(target)) {
target = {};
}
for (var i = 1, l = arguments.length; i < l; i++) {
var source = arguments[i];
if (isObjectOrArrayOrFunction(source)) {
_merge(target, source);
}
}
return target;
}
var merge_1 = merge;
// NOTE: this behaves like lodash/defaults, but doesn't mutate the target
var defaultsPure = function defaultsPure() {
var sources = Array.prototype.slice.call(arguments);
return sources.reduceRight(function(acc, source) {
Object.keys(Object(source)).forEach(function(key) {
if (source[key] !== undefined) {
acc[key] = source[key];
}
});
return acc;
}, {});
};
function intersection(arr1, arr2) {
return arr1.filter(function(value, index) {
return (
arr2.indexOf(value) > -1 &&
arr1.indexOf(value) === index /* skips duplicates */
);
});
}
var intersection_1 = intersection;
// @MAJOR can be replaced by native Array#find when we change support
var find$1 = function find(array, comparator) {
if (!Array.isArray(array)) {
return undefined;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return array[i];
}
}
};
function valToNumber(v) {
if (typeof v === 'number') {
return v;
} else if (typeof v === 'string') {
return parseFloat(v);
} else if (Array.isArray(v)) {
return v.map(valToNumber);
}
throw new Error('The value should be a number, a parsable string or an array of those.');
}
var valToNumber_1 = valToNumber;
// https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source === null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key;
var i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var omit$1 = _objectWithoutPropertiesLoose$1;
function objectHasKeys$1(obj) {
return obj && Object.keys(obj).length > 0;
}
var objectHasKeys_1 = objectHasKeys$1;
/**
* 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 defaultsPure({}, 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 (value === undefined) {
// we use the "filter" form of clearRefinement, since it leaves empty values as-is
// the form with a string will remove the attribute completely
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f;
});
}
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 (value === undefined) 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 (attribute === undefined) {
if (!objectHasKeys_1(refinementList)) {
return refinementList;
}
return {};
} else if (typeof attribute === 'string') {
return omit$1(refinementList, attribute);
} else if (typeof attribute === 'function') {
var hasChanged = false;
var newRefinementList = Object.keys(refinementList).reduce(function(memo, key) {
var values = refinementList[key] || [];
var facetList = values.filter(function(value) {
return !attribute(value, key, refinementType);
});
if (facetList.length !== values.length) {
hasChanged = true;
}
memo[key] = facetList;
return memo;
}, {});
if (hasChanged) return newRefinementList;
return refinementList;
}
},
/**
* 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 containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (refinementValue === undefined || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return refinementList[attribute].indexOf(refinementValueAsString) !== -1;
}
};
var RefinementList = lib;
/**
* isEqual, but only for numeric refinement values, possible values:
* - 5
* - [5]
* - [[5]]
* - [[5,5],[4]]
*/
function isEqualNumericRefinement(a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
return (
a.length === b.length &&
a.every(function(el, i) {
return isEqualNumericRefinement(b[i], el);
})
);
}
return a === b;
}
/**
* like _.find but using deep equality to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into (elements are base or array of base)
* @param {any} searchedValue the value we're looking for (base or array of base)
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find$1(array, function(currentValue) {
return isEqualNumericRefinement(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) : {};
/**
* 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 || {};
var self = this;
Object.keys(params).forEach(function(paramName) {
var isKeyKnown = SearchParameters.PARAMETERS.indexOf(paramName) !== -1;
var isValueDefined = params[paramName] !== undefined;
if (!isKeyKnown && isValueDefined) {
self[paramName] = params[paramName];
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = Object.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'
];
numberKeys.forEach(function(k) {
var value = partialState[k];
if (typeof value === 'string') {
var parsedValue = parseFloat(value);
// global isNaN is ok to use here, value is only number or NaN
numbers[k] = isNaN(parsedValue) ? value : parsedValue;
}
});
// there's two formats of insideBoundingBox, we need to parse
// the one which is an array of float geo rectangles
if (Array.isArray(partialState.insideBoundingBox)) {
numbers.insideBoundingBox = partialState.insideBoundingBox.map(function(geoRect) {
return geoRect.map(function(value) {
return parseFloat(value);
});
});
}
if (partialState.numericRefinements) {
var numericRefinements = {};
Object.keys(partialState.numericRefinements).forEach(function(attribute) {
var operators = partialState.numericRefinements[attribute] || {};
numericRefinements[attribute] = {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator];
var parsedValues = values.map(function(v) {
if (Array.isArray(v)) {
return v.map(function(vPrime) {
if (typeof vPrime === 'string') {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (typeof v === 'string') {
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);
var hierarchicalFacets = newParameters.hierarchicalFacets || [];
hierarchicalFacets.forEach(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 &&
objectHasKeys_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 (objectHasKeys_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 patch = {
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: RefinementList.clearRefinement(
this.facetsRefinements,
attribute,
'conjunctiveFacet'
),
facetsExcludes: RefinementList.clearRefinement(
this.facetsExcludes,
attribute,
'exclude'
),
disjunctiveFacetsRefinements: RefinementList.clearRefinement(
this.disjunctiveFacetsRefinements,
attribute,
'disjunctiveFacet'
),
hierarchicalFacetsRefinements: RefinementList.clearRefinement(
this.hierarchicalFacetsRefinements,
attribute,
'hierarchicalFacet'
)
};
if (
patch.numericRefinements === this.numericRefinements &&
patch.facetsRefinements === this.facetsRefinements &&
patch.facetsExcludes === this.facetsExcludes &&
patch.disjunctiveFacetsRefinements === this.disjunctiveFacetsRefinements &&
patch.hierarchicalFacetsRefinements === this.hierarchicalFacetsRefinements
) {
return this;
}
return this.setQueryParameters(patch);
},
/**
* 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)) {
return [];
}
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)) {
return [];
}
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)) {
return [];
}
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) {
if (!this.isNumericRefined(attribute, operator, paramValue)) {
return this;
}
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return (
key === attribute &&
value.op === operator &&
isEqualNumericRefinement(value.val, valToNumber_1(paramValue))
);
})
});
} 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 attribute in the record
* @param {string} operator operator applied on the refined values
* @return {Array.<number|number[]>} refined values
*/
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 (attribute === undefined) {
if (!objectHasKeys_1(this.numericRefinements)) {
return this.numericRefinements;
}
return {};
} else if (typeof attribute === 'string') {
if (!objectHasKeys_1(this.numericRefinements[attribute])) {
return this.numericRefinements;
}
return omit$1(this.numericRefinements, attribute);
} else if (typeof attribute === 'function') {
var hasChanged = false;
var numericRefinements = this.numericRefinements;
var newNumericRefinements = Object.keys(numericRefinements).reduce(function(memo, key) {
var operators = numericRefinements[key];
var operatorList = {};
operators = operators || {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator] || [];
var outValues = [];
values.forEach(function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (outValues.length !== values.length) {
hasChanged = true;
}
operatorList[operator] = outValues;
});
memo[key] = operatorList;
return memo;
}, {});
if (hasChanged) return newNumericRefinements;
return this.numericRefinements;
}
},
/**
* 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: this.facets.filter(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: this.disjunctiveFacets.filter(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: this.hierarchicalFacets.filter(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: this.tagRefinements.filter(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: defaultsPure({}, 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.');
}
if (!this.isHierarchicalFacet(facet)) {
throw new Error(facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaultsPure({}, 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)) {
return this;
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaultsPure({}, 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 this.disjunctiveFacets.indexOf(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 this.facets.indexOf(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)) {
return false;
}
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)) {
return false;
}
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)) {
return false;
}
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)) {
return false;
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return refinements.indexOf(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 (value === undefined && operator === undefined) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined =
this.numericRefinements[attribute] &&
this.numericRefinements[attribute][operator] !== undefined;
if (value === undefined || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber_1(value);
var isAttributeValueDefined =
findArray(this.numericRefinements[attribute][operator], parsedValue) !==
undefined;
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 this.tagRefinements.indexOf(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() {
var self = this;
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection_1(
Object.keys(this.numericRefinements).filter(function(facet) {
return Object.keys(self.numericRefinements[facet]).length > 0;
}),
this.disjunctiveFacets
);
return Object.keys(this.disjunctiveFacetsRefinements).filter(function(facet) {
return self.disjunctiveFacetsRefinements[facet].length > 0;
})
.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() {
var self = this;
return intersection_1(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
this.hierarchicalFacets.map(function(facet) { return facet.name; }),
Object.keys(this.hierarchicalFacetsRefinements).filter(function(facet) {
return self.hierarchicalFacetsRefinements[facet].length > 0;
})
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return this.disjunctiveFacets.filter(function(f) {
return refinedFacets.indexOf(f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
var self = this;
Object.keys(this).forEach(function(paramName) {
var paramValue = self[paramName];
if (managedParameters.indexOf(paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* 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 self = this;
var nextWithNumbers = SearchParameters._parseNumbers(params);
var previousPlainObject = Object.keys(this).reduce(function(acc, key) {
acc[key] = self[key];
return acc;
}, {});
var nextPlainObject = Object.keys(nextWithNumbers).reduce(
function(previous, key) {
var isPreviousValueDefined = previous[key] !== undefined;
var isNextValueDefined = nextWithNumbers[key] !== undefined;
if (isPreviousValueDefined && !isNextValueDefined) {
return omit$1(previous, [key]);
}
if (isNextValueDefined) {
previous[key] = nextWithNumbers[key];
}
return previous;
},
previousPlainObject
);
return new this.constructor(nextPlainObject);
},
/**
* Returns a new instance with the page reset. Two scenarios possible:
* the page is omitted -> return the given instance
* the page is set -> return a new instance with a page of 0
* @return {SearchParameters} a new updated instance
*/
resetPage: function() {
if (this.page === undefined) {
return this;
}
return this.setPage(0);
},
/**
* 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,
function(f) {
return f.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)) {
return [];
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return path.map(function(part) {
return part.trim();
});
},
toString: function() {
return JSON.stringify(this, null, 2);
}
};
/**
* 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;
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined;
var valIsNull = value === null;
var othIsDefined = other !== undefined;
var othIsNull = other === null;
if (
(!othIsNull && value > other) ||
(valIsNull && othIsDefined) ||
!valIsDefined
) {
return 1;
}
if (
(!valIsNull && value < other) ||
(othIsNull && valIsDefined) ||
!othIsDefined
) {
return -1;
}
}
return 0;
}
/**
* @param {Array<object>} collection object with keys in attributes
* @param {Array<string>} iteratees attributes
* @param {Array<string>} orders asc | desc
*/
function orderBy(collection, iteratees, orders) {
if (!Array.isArray(collection)) {
return [];
}
if (!Array.isArray(orders)) {
orders = [];
}
var result = collection.map(function(value, index) {
return {
criteria: iteratees.map(function(iteratee) {
return value[iteratee];
}),
index: index,
value: value
};
});
result.sort(function comparer(object, other) {
var index = -1;
while (++index < object.criteria.length) {
var res = compareAscending(object.criteria[index], other.criteria[index]);
if (res) {
if (index >= orders.length) {
return res;
}
if (orders[index] === 'desc') {
return -res;
}
return res;
}
}
// This 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;
});
return result.map(function(res) {
return res.value;
});
}
var orderBy_1 = orderBy;
var compact = function compact(array) {
if (!Array.isArray(array)) {
return [];
}
return array.filter(Boolean);
};
// @MAJOR can be replaced by native Array#findIndex when we change support
var findIndex = function find(array, comparator) {
if (!Array.isArray(array)) {
return -1;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return i;
}
}
return -1;
};
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @param {string[]} [defaults] array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
var formatSort = function formatSort(sortBy, defaults) {
var defaultInstructions = (defaults || []).map(function(sort) {
return sort.split(':');
});
return sortBy.reduce(
function preparePredicate(out, sort) {
var sortInstruction = sort.split(':');
var matchingDefault = find$1(defaultInstructions, function(
defaultInstruction
) {
return defaultInstruction[0] === sortInstruction[0];
});
if (sortInstruction.length > 1 || !matchingDefault) {
out[0].push(sortInstruction[0]);
out[1].push(sortInstruction[1]);
return out;
}
out[0].push(matchingDefault[0]);
out[1].push(matchingDefault[1]);
return out;
},
[[], []]
);
};
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 rootExhaustive = hierarchicalFacetResult.every(function(facetResult) {
return facetResult.exhaustive;
});
var generateTreeFn = generateHierarchicalTree(
sortBy,
hierarchicalSeparator,
hierarchicalRootPath,
hierarchicalShowParentLevel,
hierarchicalFacetRefinement
);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(
hierarchicalRootPath.split(hierarchicalSeparator).length
);
}
return results.reduce(generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
exhaustive: rootExhaustive,
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) {
/**
* @type {object[]]} hierarchical data
*/
var data = parent && Array.isArray(parent.data) ? parent.data : [];
parent = find$1(data, function(subtree) {
return subtree.isRefined;
});
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 picked = Object.keys(hierarchicalFacetResult.data)
.map(function(facetValue) {
return [facetValue, hierarchicalFacetResult.data[facetValue]];
})
.filter(function(tuple) {
var facetValue = tuple[0];
return onlyMatchingTree(
facetValue,
parent.path || hierarchicalRootPath,
currentRefinement,
hierarchicalSeparator,
hierarchicalRootPath,
hierarchicalShowParentLevel
);
});
parent.data = orderBy_1(
picked.map(function(tuple) {
var facetValue = tuple[0];
var facetCount = tuple[1];
return format(
facetCount,
facetValue,
hierarchicalSeparator,
currentRefinement,
hierarchicalFacetResult.exhaustive
);
}),
sortBy[0],
sortBy[1]
);
}
return hierarchicalTree;
};
}
function onlyMatchingTree(
facetValue,
parentPath,
currentRefinement,
hierarchicalSeparator,
hierarchicalRootPath,
hierarchicalShowParentLevel
) {
// 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 format(
facetCount,
facetValue,
hierarchicalSeparator,
currentRefinement,
exhaustive
) {
var parts = facetValue.split(hierarchicalSeparator);
return {
name: parts[parts.length - 1].trim(),
path: facetValue,
count: facetCount,
isRefined:
currentRefinement === facetValue ||
currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
exhaustive: exhaustive,
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
*/
/**
* @param {string[]} attributes
*/
function getIndices(attributes) {
var indices = {};
attributes.forEach(function(val, idx) {
indices[val] = idx;
});
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
/**
* @typedef {Object} HierarchicalFacet
* @property {string} name
* @property {string[]} attributes
*/
/**
* @param {HierarchicalFacet[]} hierarchicalFacets
* @param {string} hierarchicalAttributeName
*/
function findMatchingHierarchicalFacetFromAttributeName(
hierarchicalFacets,
hierarchicalAttributeName
) {
return find$1(hierarchicalFacets, function facetKeyMatchesAttribute(
hierarchicalFacet
) {
var facetNames = hierarchicalFacet.attributes || [];
return facetNames.indexOf(hierarchicalAttributeName) > -1;
});
}
/*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 = results.reduce(function(sum, result) {
return result.processingTimeMS === undefined
? sum
: sum + result.processingTimeMS;
}, 0);
/**
* 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.
*
* getRankingInfo needs to be set to `true` for this to be returned
*
* @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;
/**
* queryID is the unique identifier of the query used to generate the current search results.
* This value is only available if the `clickAnalytics` search parameter is set to `true`.
* @member {string}
*/
this.queryID = mainSubResponse.queryID;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = state.hierarchicalFacets.map(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 information from the first, general, response.
var mainFacets = mainSubResponse.facets || {};
Object.keys(mainFacets).forEach(function(facetKey) {
var facetValueObject = mainFacets[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, function(f) {
return f.name === hierarchicalFacet.name;
});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = state.disjunctiveFacets.indexOf(facetKey) !== -1;
var isFacetConjunctive = state.facets.indexOf(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
disjunctiveFacets.forEach(function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var facets = result && result.facets ? result.facets : {};
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
Object.keys(facets).forEach(function(dfacet) {
var facetResults = facets[dfacet];
var position;
if (hierarchicalFacet) {
position = findIndex(state.hierarchicalFacets, function(f) {
return f.name === hierarchicalFacet.name;
});
var attributeIndex = findIndex(self.hierarchicalFacets[position], function(f) {
return f.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: defaultsPure({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
state.disjunctiveFacetsRefinements[dfacet].forEach(function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
state.disjunctiveFacetsRefinements[dfacet].indexOf(refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
state.getRefinedHierarchicalFacets().forEach(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];
var facets = result && result.facets
? result.facets
: {};
Object.keys(facets).forEach(function(dfacet) {
var facetResults = facets[dfacet];
var position = findIndex(state.hierarchicalFacets, function(f) {
return f.name === hierarchicalFacet.name;
});
var attributeIndex = findIndex(self.hierarchicalFacets[position], function(f) {
return f.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 = defaultsPure(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
Object.keys(state.facetsExcludes).forEach(function(facetName) {
var excludes = state.facetsExcludes[facetName];
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
excludes.forEach(function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
/**
* @type {Array}
*/
this.hierarchicalFacets = this.hierarchicalFacets.map(generateHierarchicalTree_1(state));
/**
* @type {Array}
*/
this.facets = compact(this.facets);
/**
* @type {Array}
*/
this.disjunctiveFacets = compact(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the faceted attribute
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
function predicate(facet) {
return facet.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) {
function predicate(facet) {
return facet.name === attribute;
}
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find$1(results.facets, predicate);
if (!facet) return [];
return Object.keys(facet.data).map(function(name) {
return {
name: name,
count: facet.data[name],
isRefined: results._state.isFacetRefined(attribute, name),
isExcluded: results._state.isExcludeRefined(attribute, name)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find$1(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return Object.keys(disjunctiveFacet.data).map(function(name) {
return {
name: name,
count: disjunctiveFacet.data[name],
isRefined: results._state.isDisjunctiveFacetRefined(attribute, name)
};
});
} 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 = node.data.map(function(childNode) {
return recSort(sortFn, childNode);
});
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|undefined} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('result', function(event){
* //get values ordered only by name ascending using the string predicate
* event.results.getFacetValues('city', {sortBy: ['name:asc']});
* //get values ordered only by count ascending using a function
* event.results.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) {
return undefined;
}
var options = defaultsPure({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (Array.isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (Array.isArray(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(function(hierarchicalFacetValues) {
return orderBy_1(hierarchicalFacetValues, order[0], order[1]);
}, facetValues);
} else if (typeof options.sortBy === 'function') {
if (Array.isArray(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(function(data) {
return vanillaSortFn(options.sortBy, data);
}, 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);
}
return undefined;
};
/**
* @typedef {Object} FacetListItem
* @property {string} name
*/
/**
* @param {FacetListItem[]} facetList (has more items, but enough for here)
* @param {string} facetName
*/
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find$1(facetList, function(facet) {
return facet.name === facetName;
});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhaustiveness for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* Note that for a numeric refinement, results are grouped per operator, this
* means that it will return responses for operators which are empty.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
Object.keys(state.facetsRefinements).forEach(function(attributeName) {
state.facetsRefinements[attributeName].forEach(function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
Object.keys(state.facetsExcludes).forEach(function(attributeName) {
state.facetsExcludes[attributeName].forEach(function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
Object.keys(state.disjunctiveFacetsRefinements).forEach(function(attributeName) {
state.disjunctiveFacetsRefinements[attributeName].forEach(function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
Object.keys(state.hierarchicalFacetsRefinements).forEach(function(attributeName) {
state.hierarchicalFacetsRefinements[attributeName].forEach(function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
Object.keys(state.numericRefinements).forEach(function(attributeName) {
var operators = state.numericRefinements[attributeName];
Object.keys(operators).forEach(function(operator) {
operators[operator].forEach(function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
state.tagRefinements.forEach(function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
/**
* @typedef {Object} Facet
* @property {string} name
* @property {Object} data
* @property {boolean} exhaustive
*/
/**
* @param {*} state
* @param {*} type
* @param {string} attributeName
* @param {*} name
* @param {Facet[]} resultsFacets
*/
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find$1(resultsFacets, function(f) {
return f.name === attributeName;
});
var count = facet && facet.data && facet.data[name] ? facet.data[name] : 0;
var exhaustive = (facet && facet.exhaustive) || false;
return {
type: type,
attributeName: attributeName,
name: name,
count: count,
exhaustive: exhaustive
};
}
/**
* @param {*} state
* @param {string} attributeName
* @param {*} name
* @param {Facet[]} resultsFacets
*/
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var separator = state._getHierarchicalFacetSeparator(facetDeclaration);
var split = name.split(separator);
var rootFacet = find$1(resultsFacets, function(facet) {
return facet.name === attributeName;
});
var facet = split.reduce(function(intermediateFacet, part) {
var newFacet =
intermediateFacet && find$1(intermediateFacet.data, function(f) {
return f.name === part;
});
return newFacet !== undefined ? newFacet : intermediateFacet;
}, rootFacet);
var count = (facet && facet.count) || 0;
var exhaustive = (facet && facet.exhaustive) || false;
var path = (facet && facet.path) || '';
return {
type: 'hierarchical',
attributeName: attributeName,
name: path,
count: count,
exhaustive: exhaustive
};
}
var SearchResults_1 = SearchResults;
// 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(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;
}
function inherits(ctor, superCtor) {
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
var inherits_1 = inherits;
/**
* 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;
}
inherits_1(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
state.getRefinedDisjunctiveFacets().forEach(function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
state.getRefinedHierarchicalFacets().forEach(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,
clickAnalytics: 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 = [];
Object.keys(state.numericRefinements).forEach(function(attribute) {
var operators = state.numericRefinements[attribute] || {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator] || [];
if (facetName !== attribute) {
values.forEach(function(value) {
if (Array.isArray(value)) {
var vs = value.map(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 = [];
var facetsRefinements = state.facetsRefinements || {};
Object.keys(facetsRefinements).forEach(function(facetName) {
var facetValues = facetsRefinements[facetName] || [];
facetValues.forEach(function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
var facetsExcludes = state.facetsExcludes || {};
Object.keys(facetsExcludes).forEach(function(facetName) {
var facetValues = facetsExcludes[facetName] || [];
facetValues.forEach(function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
var disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements || {};
Object.keys(disjunctiveFacetsRefinements).forEach(function(facetName) {
var facetValues = disjunctiveFacetsRefinements[facetName] || [];
if (facetName === facet || !facetValues || facetValues.length === 0) {
return;
}
var orFilters = [];
facetValues.forEach(function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
var hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements || {};
Object.keys(hierarchicalFacetsRefinements).forEach(function(facetName) {
var facetValues = hierarchicalFacetsRefinements[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 state.hierarchicalFacets.reduce(
// 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;
}
return merge_1(
{},
requestBuilder._getHitsSearchParams(stateForSearchForFacetValues),
searchForFacetSearchParameters
);
}
};
var requestBuilder_1 = requestBuilder;
var version$1 = '3.1.0';
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {object} event
* @property {SearchParameters} event.state the current parameters with the latest changes applied
* @property {SearchResults} event.results the previous results received from Algolia. `null` before the first request
* @example
* helper.on('change', function(event) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search
* @property {SearchResults} event.results the results from the previous search. `null` if it is the first search.
* @example
* helper.on('search', function(event) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @property {string} event.facet the facet searched into
* @property {string} event.query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(event) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @example
* helper.on('searchOnce', function(event) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {object} event
* @property {SearchResults} event.results the results received from Algolia
* @property {SearchParameters} event.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(event) {
* 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 {object} event
* @property {Error} event.error the error returned by the Algolia.
* @example
* helper.on('error', function(event) {
* 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 (typeof client.addAlgoliaAgent === 'function') {
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;
}
inherits_1(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({onlyWithDerivedHelpers: false});
return this;
};
AlgoliaSearchHelper.prototype.searchOnlyWithDerivedHelpers = function() {
this._search({onlyWithDerivedHelpers: true});
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', {
state: tempState
});
if (cb) {
this.client
.search(queries)
.then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) {
self.emit('searchQueueEmpty');
}
cb(null, new SearchResults_1(tempState, content.results), tempState);
})
.catch(function(err) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) {
self.emit('searchQueueEmpty');
}
cb(err, null, tempState);
});
return undefined;
}
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
* @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes
* it in the generated query.
* @return {promise.<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits, userState) {
var clientHasSFFV = typeof this.client.searchForFacetValues === 'function';
if (
!clientHasSFFV &&
typeof this.client.initIndex !== 'function'
) {
throw new Error(
'search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues'
);
}
var state = this.state.setQueryParameters(userState || {});
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, state);
this._currentNbQueries++;
var self = this;
this.emit('searchForFacetValues', {
state: state,
facet: facet,
query: query
});
var searchForFacetValuesPromise = clientHasSFFV
? this.client.searchForFacetValues([{indexName: state.index, params: algoliaQuery}])
: this.client.initIndex(state.index).searchForFacetValues(algoliaQuery);
return searchForFacetValuesPromise.then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
content = Array.isArray(content) ? content[0] : content;
content.facetHits.forEach(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._change({
state: this.state.resetPage().setQuery(q),
isPageReset: true
});
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._change({
state: this.state.resetPage().clearRefinements(name),
isPageReset: true
});
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._change({
state: this.state.resetPage().clearTags(),
isPageReset: true
});
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._change({
state: this.state.resetPage().addDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().addHierarchicalFacetRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().addNumericRefinement(attribute, operator, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().addFacetRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().addExcludeRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().addTagRefinement(tag),
isPageReset: true
});
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._change({
state: this.state.resetPage().removeNumericRefinement(attribute, operator, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().removeDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().removeHierarchicalFacetRefinement(facet),
isPageReset: true
});
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._change({
state: this.state.resetPage().removeFacetRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().removeExcludeRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().removeTagRefinement(tag),
isPageReset: true
});
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._change({
state: this.state.resetPage().toggleExcludeFacetRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().toggleFacetRefinement(facet, value),
isPageReset: true
});
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._change({
state: this.state.resetPage().toggleTagRefinement(tag),
isPageReset: true
});
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() {
var page = this.state.page || 0;
return this.setPage(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() {
var page = this.state.page || 0;
return this.setPage(page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this._change({
state: this.state.setPage(page),
isPageReset: false
});
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._change({
state: this.state.resetPage().setIndex(name),
isPageReset: true
});
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) {
this._change({
state: this.state.resetPage().setQueryParameter(parameter, value),
isPageReset: true
});
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._change({
state: SearchParameters_1.make(newState),
isPageReset: false
});
return this;
};
/**
* 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;
};
/**
* 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 (objectHasKeys_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 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);
conjRefinements.forEach(function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
excludeRefinements.forEach(function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
disjRefinements.forEach(function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
Object.keys(numericRefinements).forEach(function(operator) {
var value = numericRefinements[operator];
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute attribute in the record
* @param {string} operator operator applied on the refined values
* @return {Array.<number|number[]>} refined values
*/
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(options) {
var state = this.state;
var states = [];
var mainQueries = [];
if (!options.onlyWithDerivedHelpers) {
mainQueries = requestBuilder_1._getQueries(state.index, state);
states.push({
state: state,
queriesCount: mainQueries.length,
helper: this
});
this.emit('search', {
state: state,
results: this.lastResults
});
}
var derivedQueries = this.derivedHelpers.map(function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var derivedStateQueries = requestBuilder_1._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: derivedStateQueries.length,
helper: derivedHelper
});
derivedHelper.emit('search', {
state: derivedState,
results: derivedHelper.lastResults
});
return derivedStateQueries;
});
var queries = Array.prototype.concat.apply(mainQueries, derivedQueries);
var queryId = this._queryId++;
this._currentNbQueries++;
try {
this.client.search(queries)
.then(this._dispatchAlgoliaResponse.bind(this, states, queryId))
.catch(this._dispatchAlgoliaError.bind(this, queryId));
} catch (error) {
// If we reach this part, we're in an internal error state
this.emit('error', {
error: error
});
}
};
/**
* 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 {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, 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 (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results.slice();
states.forEach(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', {
results: formattedResponse,
state: state
});
});
};
AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function(queryId, error) {
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= queryId - this._lastQueryIdReceived;
this._lastQueryIdReceived = queryId;
this.emit('error', {
error: error
});
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
};
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(event) {
var state = event.state;
var isPageReset = event.isPageReset;
if (state !== this.state) {
this.state = state;
this.emit('change', {
state: this.state,
results: this.lastResults,
isPageReset: isPageReset
});
}
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache && 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 (typeof newClient.addAlgoliaAgent === 'function') {
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'
*/
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(event) {
* console.log(event.results);
* });
* helper
* .toggleFacetRefinement('category', 'Movies & TV Shows')
* .toggleFacetRefinement('shipping', '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;
var algoliasearchHelper_1 = algoliasearchHelper;
function createOptionalFilter(_ref) {
var attributeName = _ref.attributeName,
attributeValue = _ref.attributeValue,
attributeScore = _ref.attributeScore;
return "".concat(attributeName, ":").concat(attributeValue, "<score=").concat(attributeScore || 1, ">");
}
var defaultProps = {
transformSearchParameters: function transformSearchParameters(x) {
return _objectSpread({}, x);
}
};
function getId$1() {
// We store the search state of this widget in `configure`.
return 'configure';
}
function getSearchParametersFromProps(props) {
var optionalFilters = Object.keys(props.matchingPatterns).reduce(function (acc, attributeName) {
var attributePattern = props.matchingPatterns[attributeName];
var attributeValue = getPropertyByPath(props.hit, attributeName);
var attributeScore = attributePattern.score;
if (Array.isArray(attributeValue)) {
return [].concat(_toConsumableArray(acc), [attributeValue.map(function (attributeSubValue) {
return createOptionalFilter({
attributeName: attributeName,
attributeValue: attributeSubValue,
attributeScore: attributeScore
});
})]);
}
if (typeof attributeValue === 'string') {
return [].concat(_toConsumableArray(acc), [createOptionalFilter({
attributeName: attributeName,
attributeValue: attributeValue,
attributeScore: attributeScore
})]);
}
return acc;
}, []);
return props.transformSearchParameters(new algoliasearchHelper_1.SearchParameters({
// @ts-ignore @TODO algoliasearch-helper@3.0.1 will contain the type
// `sumOrFiltersScores`.
// See https://github.com/algolia/algoliasearch-helper-js/pull/753
sumOrFiltersScores: true,
facetFilters: ["objectID:-".concat(props.hit.objectID)],
optionalFilters: optionalFilters
}));
}
var connectConfigureRelatedItems = createConnectorWithContext({
displayName: 'AlgoliaConfigureRelatedItems',
defaultProps: defaultProps,
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
return searchParameters.setQueryParameters(getSearchParametersFromProps(props));
},
transitionState: function transitionState(props, _prevSearchState, nextSearchState) {
var id = getId$1(); // We need to transform the exhaustive search parameters back to clean
// search parameters without the empty default keys so we don't pollute the
// `configure` search state.
var searchParameters = removeEmptyArraysFromObject(removeEmptyKey(getSearchParametersFromProps(props)));
var searchParametersKeys = Object.keys(searchParameters);
var nonPresentKeys = this._searchParameters ? Object.keys(this._searchParameters).filter(function (prop) {
return searchParametersKeys.indexOf(prop) === -1;
}) : [];
this._searchParameters = searchParameters;
var nextValue = _defineProperty({}, id, _objectSpread({}, omit(nextSearchState[id], nonPresentKeys), searchParameters));
return refineValue(nextSearchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
var _this = this;
var id = getId$1();
var indexId = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var subState = hasMultipleIndices({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) && searchState.indices ? searchState.indices[indexId] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!_this._searchParameters[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = _defineProperty({}, id, configureState);
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = 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.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;
function emptyFunction() {}
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret_1) {
// It is still safe when called from React.
return;
}
var err = new Error(
'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'
);
err.name = 'Invariant Violation';
throw err;
} 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;
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();
}
});
function ConfigureRelatedItems() {
return null;
}
ConfigureRelatedItems.propTypes = {
hit: propTypes.object.isRequired,
matchingPatterns: propTypes.object.isRequired,
transformSearchParameters: propTypes.func
};
var ConfigureRelatedItems$1 = connectConfigureRelatedItems(ConfigureRelatedItems);
function getIndexContext(props) {
return {
targetedIndex: props.indexId
};
}
/**
* 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.
*
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, Index, SearchBox, Hits, Configure } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <Configure hitsPerPage={5} />
* <SearchBox />
* <Index indexName="instant_search">
* <Hits />
* </Index>
* <Index indexName="bestbuy">
* <Hits />
* </Index>
* </InstantSearch>
* );
*/
var Index =
/*#__PURE__*/
function (_Component) {
_inherits(Index, _Component);
_createClass(Index, null, [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(props) {
return {
indexContext: getIndexContext(props)
};
}
}]);
function Index(props) {
var _this;
_classCallCheck(this, Index);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Index).call(this, props));
_defineProperty(_assertThisInitialized(_this), "state", {
indexContext: getIndexContext(_this.props)
});
_defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0);
_this.props.contextValue.onSearchParameters(_this.getSearchParameters.bind(_assertThisInitialized(_this)), {
ais: _this.props.contextValue,
multiIndexContext: _this.state.indexContext
}, _this.props, undefined);
return _this;
}
_createClass(Index, [{
key: "componentDidMount",
value: function componentDidMount() {
this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (this.props.indexName !== prevProps.indexName) {
this.props.contextValue.widgetsManager.update();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (typeof this.unregisterWidget === 'function') {
this.unregisterWidget();
}
}
}, {
key: "getSearchParameters",
value: function getSearchParameters(searchParameters, props) {
return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName);
}
}, {
key: "render",
value: function render() {
var childrenCount = React.Children.count(this.props.children);
if (childrenCount === 0) {
return null;
}
return React__default.createElement(IndexProvider, {
value: this.state.indexContext
}, this.props.children);
}
}]);
return Index;
}(React.Component);
_defineProperty(Index, "propTypes", {
indexName: propTypes.string.isRequired,
indexId: propTypes.string.isRequired,
children: propTypes.node
});
var IndexWrapper = function IndexWrapper(props) {
var inferredIndexId = props.indexName;
return React__default.createElement(InstantSearchConsumer, null, function (contextValue) {
return React__default.createElement(Index, _extends({
contextValue: contextValue,
indexId: inferredIndexId
}, props));
});
};
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;
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;
}
};
}
function createStore(initialState) {
var state = initialState;
var listeners = [];
return {
getState: function getState() {
return state;
},
setState: function setState(nextState) {
state = nextState;
listeners.forEach(function (listener) {
return listener();
});
},
subscribe: function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
listeners.splice(listeners.indexOf(listener), 1);
};
}
};
}
function addAlgoliaAgents(searchClient) {
if (typeof searchClient.addAlgoliaAgent === 'function') {
searchClient.addAlgoliaAgent("react (".concat(React.version, ")"));
searchClient.addAlgoliaAgent("react-instantsearch (".concat(version, ")"));
}
}
var isMultiIndexContext = function isMultiIndexContext(widget) {
return hasMultipleIndices({
ais: widget.props.contextValue,
multiIndexContext: widget.props.indexContextValue
});
};
var isTargetedIndexEqualIndex = function isTargetedIndexEqualIndex(widget, indexId) {
return widget.props.indexContextValue.targetedIndex === indexId;
}; // Relying on the `indexId` is a bit brittle to detect the `Index` widget.
// Since it's a class we could rely on `instanceof` or similar. We never
// had an issue though. Works for now.
var isIndexWidget = function isIndexWidget(widget) {
return Boolean(widget.props.indexId);
};
var isIndexWidgetEqualIndex = function isIndexWidgetEqualIndex(widget, indexId) {
return widget.props.indexId === indexId;
};
var sortIndexWidgetsFirst = function sortIndexWidgetsFirst(firstWidget, secondWidget) {
var isFirstWidgetIndex = isIndexWidget(firstWidget);
var isSecondWidgetIndex = isIndexWidget(secondWidget);
if (isFirstWidgetIndex && !isSecondWidgetIndex) {
return -1;
}
if (!isFirstWidgetIndex && isSecondWidgetIndex) {
return 1;
}
return 0;
}; // This function is copied from the algoliasearch v4 API Client. If modified,
// consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
function serializeQueryParameters(parameters) {
var isObjectOrArray = function isObjectOrArray(value) {
return Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]';
};
var encode = function encode(format) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var i = 0;
return format.replace(/%s/g, function () {
return encodeURIComponent(args[i++]);
});
};
return Object.keys(parameters).map(function (key) {
return encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]);
}).join('&');
}
/**
* 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
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/
function createInstantSearchManager(_ref) {
var indexName = _ref.indexName,
_ref$initialState = _ref.initialState,
initialState = _ref$initialState === void 0 ? {} : _ref$initialState,
searchClient = _ref.searchClient,
resultsState = _ref.resultsState,
stalledSearchDelay = _ref.stalledSearchDelay;
var helper = algoliasearchHelper_1(searchClient, indexName, _objectSpread({}, HIGHLIGHT_TAGS));
addAlgoliaAgents(searchClient);
helper.on('search', handleNewSearch).on('result', handleSearchSuccess({
indexId: indexName
})).on('error', handleSearchError);
var skip = false;
var stalledSearchTimer = null;
var initialSearchParameters = helper.state;
var widgetsManager = createWidgetsManager(onWidgetsUpdate);
hydrateSearchClient(searchClient, resultsState);
var store = createStore({
widgets: initialState,
metadata: hydrateMetadata(resultsState),
results: hydrateResultsState(resultsState),
error: null,
searching: false,
isSearchStalled: true,
searchingForFacetValues: false
});
function skipSearch() {
skip = true;
}
function updateClient(client) {
addAlgoliaAgents(client);
helper.setClient(client);
search();
}
function clearCache() {
helper.clearCache();
search();
}
function getMetadata(state) {
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getMetadata);
}).map(function (widget) {
return widget.getMetadata(state);
});
}
function getSearchParameters() {
var sharedParameters = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return !isMultiIndexContext(widget) && !isIndexWidget(widget);
}).reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, initialSearchParameters);
var mainParameters = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
var targetedIndexEqualMainIndex = isMultiIndexContext(widget) && isTargetedIndexEqualIndex(widget, indexName);
var subIndexEqualMainIndex = isIndexWidget(widget) && isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexEqualMainIndex || subIndexEqualMainIndex;
}) // We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst).reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters);
var derivedIndices = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
var targetedIndexNotEqualMainIndex = isMultiIndexContext(widget) && !isTargetedIndexEqualIndex(widget, indexName);
var subIndexNotEqualMainIndex = isIndexWidget(widget) && !isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex;
}) // We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst).reduce(function (indices, widget) {
var indexId = isMultiIndexContext(widget) ? widget.props.indexContextValue.targetedIndex : widget.props.indexId;
var widgets = indices[indexId] || [];
return _objectSpread({}, indices, _defineProperty({}, indexId, widgets.concat(widget)));
}, {});
var derivedParameters = Object.keys(derivedIndices).map(function (indexId) {
return {
parameters: derivedIndices[indexId].reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters),
indexId: indexId
};
});
return {
mainParameters: mainParameters,
derivedParameters: derivedParameters
};
}
function search() {
if (!skip) {
var _getSearchParameters = getSearchParameters(),
mainParameters = _getSearchParameters.mainParameters,
derivedParameters = _getSearchParameters.derivedParameters; // We have to call `slice` because the method `detach` on the derived
// helpers mutates the value `derivedHelpers`. The `forEach` loop does
// not iterate on each value and we're not able to correctly clear the
// previous derived helpers (memory leak + useless requests).
helper.derivedHelpers.slice().forEach(function (derivedHelper) {
// Since we detach the derived helpers on **every** new search they
// won't receive intermediate results in case of a stalled search.
// Only the last result is dispatched by the derived helper because
// they are not detached yet:
//
// - a -> main helper receives results
// - ap -> main helper receives results
// - app -> main helper + derived helpers receive results
//
// The quick fix is to avoid to detach them on search but only once they
// received the results. But it means that in case of a stalled search
// all the derived helpers not detached yet register a new search inside
// the helper. The number grows fast in case of a bad network and it's
// not deterministic.
derivedHelper.detach();
});
derivedParameters.forEach(function (_ref2) {
var indexId = _ref2.indexId,
parameters = _ref2.parameters;
var derivedHelper = helper.derive(function () {
return parameters;
});
derivedHelper.on('result', handleSearchSuccess({
indexId: indexId
})).on('error', handleSearchError);
});
helper.setState(mainParameters);
helper.search();
}
}
function handleSearchSuccess(_ref3) {
var indexId = _ref3.indexId;
return function (event) {
var state = store.getState();
var isDerivedHelpersEmpty = !helper.derivedHelpers.length;
var results = state.results ? state.results : {}; // Switching from mono index to multi index and vice versa must reset the
// results to an empty object, otherwise we keep reference of stalled and
// unused results.
results = !isDerivedHelpersEmpty && results.getFacetByName ? {} : results;
if (!isDerivedHelpersEmpty) {
results = _objectSpread({}, results, _defineProperty({}, indexId, event.results));
} else {
results = event.results;
}
var currentState = store.getState();
var nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
stalledSearchTimer = null;
nextIsSearchStalled = false;
}
var resultsFacetValues = currentState.resultsFacetValues,
partialState = _objectWithoutProperties(currentState, ["resultsFacetValues"]);
store.setState(_objectSpread({}, partialState, {
results: results,
isSearchStalled: nextIsSearchStalled,
searching: false,
error: null
}));
};
}
function handleSearchError(_ref4) {
var error = _ref4.error;
var currentState = store.getState();
var nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
nextIsSearchStalled = false;
}
var resultsFacetValues = currentState.resultsFacetValues,
partialState = _objectWithoutProperties(currentState, ["resultsFacetValues"]);
store.setState(_objectSpread({}, partialState, {
isSearchStalled: nextIsSearchStalled,
error: error,
searching: false
}));
}
function handleNewSearch() {
if (!stalledSearchTimer) {
stalledSearchTimer = setTimeout(function () {
var _store$getState = store.getState(),
resultsFacetValues = _store$getState.resultsFacetValues,
partialState = _objectWithoutProperties(_store$getState, ["resultsFacetValues"]);
store.setState(_objectSpread({}, partialState, {
isSearchStalled: true
}));
}, stalledSearchDelay);
}
}
function hydrateSearchClient(client, results) {
if (!results) {
return;
} // Disable cache hydration on:
// - Algoliasearch API Client < v4 with cache disabled
// - Third party clients (detected by the `addAlgoliaAgent` function missing)
if ((!client.transporter || client._cacheHydrated) && (!client._useCache || typeof client.addAlgoliaAgent !== 'function')) {
return;
} // Algoliasearch API Client >= v4
// To hydrate the client we need to populate the cache with the data from
// the server (done in `hydrateSearchClientWithMultiIndexRequest` or
// `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
// for us to compute the key the same way as `algoliasearch-client` we need
// to populate it on a custom key and override the `search` method to
// search on it first.
if (client.transporter && !client._cacheHydrated) {
client._cacheHydrated = true;
var baseMethod = client.search;
client.search = function (requests) {
for (var _len2 = arguments.length, methodArgs = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
methodArgs[_key2 - 1] = arguments[_key2];
}
var requestsWithSerializedParams = requests.map(function (request) {
return _objectSpread({}, request, {
params: serializeQueryParameters(request.params)
});
});
return client.transporter.responsesCache.get({
method: 'search',
args: [requestsWithSerializedParams].concat(methodArgs)
}, function () {
return baseMethod.apply(void 0, [requests].concat(methodArgs));
});
};
}
if (Array.isArray(results.results)) {
hydrateSearchClientWithMultiIndexRequest(client, results.results);
return;
}
hydrateSearchClientWithSingleIndexRequest(client, results);
}
function hydrateSearchClientWithMultiIndexRequest(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set({
method: 'search',
args: [results.reduce(function (acc, result) {
return acc.concat(result.rawResults.map(function (request) {
return {
indexName: request.index,
params: request.params
};
}));
}, [])]
}, {
results: results.reduce(function (acc, result) {
return acc.concat(result.rawResults);
}, [])
});
return;
} // Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
var key = "/1/indexes/*/queries_body_".concat(JSON.stringify({
requests: results.reduce(function (acc, result) {
return acc.concat(result.rawResults.map(function (request) {
return {
indexName: request.index,
params: request.params
};
}));
}, [])
}));
client.cache = _objectSpread({}, client.cache, _defineProperty({}, key, JSON.stringify({
results: results.reduce(function (acc, result) {
return acc.concat(result.rawResults);
}, [])
})));
}
function hydrateSearchClientWithSingleIndexRequest(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set({
method: 'search',
args: [results.rawResults.map(function (request) {
return {
indexName: request.index,
params: request.params
};
})]
}, {
results: results.rawResults
});
return;
} // Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
var key = "/1/indexes/*/queries_body_".concat(JSON.stringify({
requests: results.rawResults.map(function (request) {
return {
indexName: request.index,
params: request.params
};
})
}));
client.cache = _objectSpread({}, client.cache, _defineProperty({}, key, JSON.stringify({
results: results.rawResults
})));
}
function hydrateResultsState(results) {
if (!results) {
return null;
}
if (Array.isArray(results.results)) {
return results.results.reduce(function (acc, result) {
return _objectSpread({}, acc, _defineProperty({}, result._internalIndexId, new algoliasearchHelper_1.SearchResults(new algoliasearchHelper_1.SearchParameters(result.state), result.rawResults)));
}, {});
}
return new algoliasearchHelper_1.SearchResults(new algoliasearchHelper_1.SearchParameters(results.state), results.rawResults);
} // Called whenever a widget has been rendered with new props.
function onWidgetsUpdate() {
var metadata = getMetadata(store.getState().widgets);
store.setState(_objectSpread({}, 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(_objectSpread({}, store.getState(), {
widgets: nextSearchState,
metadata: metadata,
searching: true
}));
search();
}
function onSearchForFacetValues(_ref5) {
var facetName = _ref5.facetName,
query = _ref5.query,
_ref5$maxFacetHits = _ref5.maxFacetHits,
maxFacetHits = _ref5$maxFacetHits === void 0 ? 10 : _ref5$maxFacetHits; // The values 1, 100 are the min / max values that the engine accepts.
// see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits
var maxFacetHitsWithinRange = Math.max(1, Math.min(maxFacetHits, 100));
store.setState(_objectSpread({}, store.getState(), {
searchingForFacetValues: true
}));
helper.searchForFacetValues(facetName, query, maxFacetHitsWithinRange).then(function (content) {
var _objectSpread7;
store.setState(_objectSpread({}, store.getState(), {
error: null,
searchingForFacetValues: false,
resultsFacetValues: _objectSpread({}, store.getState().resultsFacetValues, (_objectSpread7 = {}, _defineProperty(_objectSpread7, facetName, content.facetHits), _defineProperty(_objectSpread7, "query", query), _objectSpread7))
}));
}, function (error) {
store.setState(_objectSpread({}, store.getState(), {
searchingForFacetValues: false,
error: error
}));
}).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); // No need to trigger a new search here as the widgets will also update and trigger it if needed.
}
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,
getSearchParameters: getSearchParameters,
onSearchForFacetValues: onSearchForFacetValues,
onExternalStateUpdate: onExternalStateUpdate,
transitionState: transitionState,
updateClient: updateClient,
updateIndex: updateIndex,
clearCache: clearCache,
skipSearch: skipSearch
};
}
function hydrateMetadata(resultsState) {
if (!resultsState) {
return [];
} // add a value noop, which gets replaced once the widgets are mounted
return resultsState.metadata.map(function (datum) {
return _objectSpread({
value: function value() {}
}, datum, {
items: datum.items && datum.items.map(function (item) {
return _objectSpread({
value: function value() {}
}, item, {
items: item.items && item.items.map(function (nestedItem) {
return _objectSpread({
value: function value() {}
}, nestedItem);
})
});
})
});
});
}
function isControlled(props) {
return Boolean(props.searchState);
}
/**
* @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
* @name <InstantSearch>
* @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} indexName - Main index in which to search.
* @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index.
* @propType {object} [searchClient] - Provide a custom search client.
* @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).
* @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html).
* @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds.
* @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }`
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox />
* <Hits />
* </InstantSearch>
* );
*/
var InstantSearch =
/*#__PURE__*/
function (_Component) {
_inherits(InstantSearch, _Component);
_createClass(InstantSearch, null, [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, prevState) {
var nextIsControlled = isControlled(nextProps);
var previousSearchState = prevState.instantSearchManager.store.getState().widgets;
var nextSearchState = nextProps.searchState;
if (nextIsControlled && !reactFastCompare(previousSearchState, nextSearchState)) {
prevState.instantSearchManager.onExternalStateUpdate(nextProps.searchState);
}
return {
isControlled: nextIsControlled,
contextValue: _objectSpread({}, prevState.contextValue, {
mainTargetedIndex: nextProps.indexName
})
};
}
}]);
function InstantSearch(props) {
var _this;
_classCallCheck(this, InstantSearch);
_this = _possibleConstructorReturn(this, _getPrototypeOf(InstantSearch).call(this, props));
_defineProperty(_assertThisInitialized(_this), "isUnmounting", false);
var instantSearchManager = createInstantSearchManager({
indexName: _this.props.indexName,
searchClient: _this.props.searchClient,
initialState: _this.props.searchState || {},
resultsState: _this.props.resultsState,
stalledSearchDelay: _this.props.stalledSearchDelay
});
var contextValue = {
store: instantSearchManager.store,
widgetsManager: instantSearchManager.widgetsManager,
mainTargetedIndex: _this.props.indexName,
onInternalStateUpdate: _this.onWidgetsInternalStateUpdate.bind(_assertThisInitialized(_this)),
createHrefForState: _this.createHrefForState.bind(_assertThisInitialized(_this)),
onSearchForFacetValues: _this.onSearchForFacetValues.bind(_assertThisInitialized(_this)),
onSearchStateChange: _this.onSearchStateChange.bind(_assertThisInitialized(_this)),
onSearchParameters: _this.onSearchParameters.bind(_assertThisInitialized(_this))
};
_this.state = {
isControlled: isControlled(_this.props),
instantSearchManager: instantSearchManager,
contextValue: contextValue
};
return _this;
}
_createClass(InstantSearch, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
var prevIsControlled = isControlled(prevProps);
if (prevIsControlled && !this.state.isControlled) {
throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled");
}
if (!prevIsControlled && this.state.isControlled) {
throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled");
}
if (this.props.refresh !== prevProps.refresh && this.props.refresh) {
this.state.instantSearchManager.clearCache();
}
if (prevProps.indexName !== this.props.indexName) {
this.state.instantSearchManager.updateIndex(this.props.indexName);
}
if (prevProps.searchClient !== this.props.searchClient) {
this.state.instantSearchManager.updateClient(this.props.searchClient);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.isUnmounting = true;
this.state.instantSearchManager.skipSearch();
}
}, {
key: "createHrefForState",
value: function createHrefForState(searchState) {
searchState = this.state.instantSearchManager.transitionState(searchState);
return this.state.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#';
}
}, {
key: "onWidgetsInternalStateUpdate",
value: function onWidgetsInternalStateUpdate(searchState) {
searchState = this.state.instantSearchManager.transitionState(searchState);
this.onSearchStateChange(searchState);
if (!this.state.isControlled) {
this.state.instantSearchManager.onExternalStateUpdate(searchState);
}
}
}, {
key: "onSearchStateChange",
value: function onSearchStateChange(searchState) {
if (this.props.onSearchStateChange && !this.isUnmounting) {
this.props.onSearchStateChange(searchState);
}
}
}, {
key: "onSearchParameters",
value: function onSearchParameters(getSearchParameters, context, props, getMetadata) {
if (this.props.onSearchParameters) {
var _searchState = this.props.searchState ? this.props.searchState : {};
this.props.onSearchParameters(getSearchParameters, context, props, _searchState);
}
if (this.props.widgetsCollector) {
var _searchState2 = this.props.searchState ? this.props.searchState : {};
this.props.widgetsCollector({
getSearchParameters: getSearchParameters,
getMetadata: getMetadata,
context: context,
props: props,
searchState: _searchState2
});
}
}
}, {
key: "onSearchForFacetValues",
value: function onSearchForFacetValues(searchState) {
this.state.instantSearchManager.onSearchForFacetValues(searchState);
}
}, {
key: "getKnownKeys",
value: function getKnownKeys() {
return this.state.instantSearchManager.getWidgetsIds();
}
}, {
key: "render",
value: function render() {
if (React.Children.count(this.props.children) === 0) {
return null;
}
return React__default.createElement(InstantSearchProvider, {
value: this.state.contextValue
}, this.props.children);
}
}]);
return InstantSearch;
}(React.Component);
_defineProperty(InstantSearch, "defaultProps", {
stalledSearchDelay: 200,
refresh: false
});
_defineProperty(InstantSearch, "propTypes", {
// @TODO: These props are currently constant.
indexName: propTypes.string.isRequired,
searchClient: propTypes.shape({
search: propTypes.func.isRequired,
searchForFacetValues: propTypes.func,
addAlgoliaAgent: propTypes.func,
clearCache: propTypes.func
}).isRequired,
createURL: propTypes.func,
refresh: propTypes.bool,
searchState: propTypes.object,
onSearchStateChange: propTypes.func,
onSearchParameters: propTypes.func,
widgetsCollector: propTypes.func,
resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]),
children: propTypes.node,
stalledSearchDelay: propTypes.number
});
var getId$2 = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function _refine(props, searchState, nextRefinement, context) {
var id = getId$2(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace);
}
function transformValue(values) {
return values.reduce(function (acc, item) {
if (item.isRefined) {
acc.push({
label: item.name,
// If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label
// If dealing with the first level, "value" is equal to the current label
value: item.path
}); // Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one
if (item.data) {
acc = acc.concat(transformValue(item.data));
}
}
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 {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @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 = createConnectorWithContext({
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 ".concat(propName, " supplied to ").concat(componentName, ". Expected an Array of Strings"));
}
return undefined;
},
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var id = getId$2(props);
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
canRefine: false
};
}
var values = results.getFacetValues(id);
var items = values.data ? transformValue(values.data) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
canRefine: transformedItems.length > 0,
items: transformedItems
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
/**
* 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, attribute: 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. `attribute` and `currentRefinement` are metadata containing row values.
* @providedPropType {string} query - the search query
*/
var connectCurrentRefinements = createConnectorWithContext({
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.map(function (item) {
return _objectSpread({}, item, {
id: meta.id,
index: meta.index
});
}));
}
}
return res;
}, []);
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems,
canRefine: transformedItems.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);
}
});
var getId$3 = function getId(props) {
return props.attributes[0];
};
var namespace$1 = 'hierarchicalMenu';
function getCurrentRefinement(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$1, ".").concat(getId$3(props)), null);
if (currentRefinement === '') {
return null;
}
return currentRefinement;
}
function getValue(path, props, searchState, context) {
var id = props.id,
attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement(props, searchState, context);
var nextRefinement;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new algoliasearchHelper_1.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$1(value, props, searchState, context) {
return value.map(function (v) {
return {
label: v.name,
value: getValue(v.path, props, searchState, context),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue$1(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) ? _objectSpread({}, item, {
items: truncate(item.items, limit)
}) : item;
});
};
function _refine$1(props, searchState, nextRefinement, context) {
var id = getId$3(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$1);
}
function _cleanUp(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$1, ".").concat(getId$3(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 {array.<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 limit and showMoreLimit.
* @propType {number} [limit=10] - The maximum number of items displayed.
* @propType {number} [showMoreLimit=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 path to use if the first level is not the root level.
* @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 = createConnectorWithContext({
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 ".concat(propName, " supplied to ").concat(componentName, ". Expected an Array of Strings"));
}
return undefined;
},
separator: propTypes.string,
rootPath: propTypes.string,
showParentLevel: propTypes.bool,
defaultRefinement: propTypes.string,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func
},
defaultProps: {
showMore: false,
limit: 10,
showMoreLimit: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore,
limit = props.limit,
showMoreLimit = props.showMoreLimit;
var id = getId$3(props);
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: false
};
}
var itemsLimit = showMore ? showMoreLimit : limit;
var value = results.getFacetValues(id, {
sortBy: sortBy
});
var items = value.data ? transformValue$1(value.data, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: truncate(transformedItems, itemsLimit),
currentRefinement: getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$1(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel,
showMore = props.showMore,
limit = props.limit,
showMoreLimit = props.showMoreLimit,
contextValue = props.contextValue;
var id = getId$3(props);
var itemsLimit = showMore ? showMoreLimit : limit;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, itemsLimit)
});
var currentRefinement = getCurrentRefinement(props, searchState, {
ais: contextValue,
multiIndexContext: props.indexContextValue
});
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var rootAttribute = props.attributes[0];
var id = getId$3(props);
var currentRefinement = getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = !currentRefinement ? [] : [{
label: "".concat(rootAttribute, ": ").concat(currentRefinement),
attribute: rootAttribute,
value: function value(nextState) {
return _refine$1(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}];
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: items
};
}
});
var highlight = function highlight(_ref) {
var attribute = _ref.attribute,
hit = _ref.hit,
highlightProperty = _ref.highlightProperty,
_ref$preTag = _ref.preTag,
preTag = _ref$preTag === void 0 ? HIGHLIGHT_TAGS.highlightPreTag : _ref$preTag,
_ref$postTag = _ref.postTag,
postTag = _ref$postTag === void 0 ? HIGHLIGHT_TAGS.highlightPostTag : _ref$postTag;
return parseAlgoliaHit({
attribute: attribute,
highlightProperty: highlightProperty,
hit: hit,
preTag: preTag,
postTag: postTag
});
};
/**
* 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 - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attribute` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}`. If the element that corresponds to the attribute is an array of strings, it will return a nested array of objects.
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const CustomHighlight = connectHighlight(
* ({ highlight, attribute, hit, highlightProperty }) => {
* const highlights = highlight({
* highlightProperty: '_highlightResult',
* attribute,
* hit
* });
*
* return highlights.map(part => part.isHighlighted ? (
* <mark>{part.value}</mark>
* ) : (
* <span>{part.value}</span>
* ));
* }
* );
*
* const Hit = ({ hit }) => (
* <p>
* <CustomHighlight attribute="name" hit={hit} />
* </p>
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox defaultRefinement="pho" />
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
*/
var connectHighlight = createConnectorWithContext({
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 algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
* const CustomHits = connectHits(({ hits }) => (
* <div>
* {hits.map(hit =>
* <p key={hit.objectID}>
* <Highlight attribute="name" hit={hit} />
* </p>
* )}
* </div>
* ));
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <CustomHits />
* </InstantSearch>
* );
*/
var connectHits = createConnectorWithContext({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return {
hits: []
};
}
var hitsWithPositions = addAbsolutePositions(results.hits, results.hitsPerPage, results.page);
var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID);
return {
hits: hitsWithPositionsAndQueryID
};
},
/**
* Hits needs to be considered as a widget to trigger a search,
* even if no other widgets are used.
*
* To be considered as a widget you need either:
* - getSearchParameters
* - getMetadata
* - transitionState
*
* See: createConnector.tsx
*/
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
function getId$4() {
return 'hitsPerPage';
}
function getCurrentRefinement$1(props, searchState, context) {
var id = getId$4();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null);
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 = createConnectorWithContext({
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$1(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _objectSpread({}, item, {
isRefined: true
}) : _objectSpread({}, item, {
isRefined: false
});
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId$4();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$4());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement$1(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}));
},
getMetadata: function getMetadata() {
return {
id: getId$4()
};
}
});
function getId$5() {
return 'page';
}
function getCurrentRefinement$2(props, searchState, context) {
var id = getId$5();
var page = 1;
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page);
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
}
function getStateWithoutPage(state) {
var _ref = state || {},
page = _ref.page,
rest = _objectWithoutProperties(_ref, ["page"]);
return rest;
}
function getInMemoryCache() {
var cachedHits = undefined;
var cachedState = undefined;
return {
read: function read(_ref2) {
var state = _ref2.state;
return reactFastCompare(cachedState, getStateWithoutPage(state)) ? cachedHits : null;
},
write: function write(_ref3) {
var state = _ref3.state,
hits = _ref3.hits;
cachedState = getStateWithoutPage(state);
cachedHits = hits;
}
};
}
function extractHitsFromCachedHits(cachedHits) {
return Object.keys(cachedHits).map(Number).sort(function (a, b) {
return a - b;
}).reduce(function (acc, page) {
return acc.concat(cachedHits[page]);
}, []);
}
/**
* 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 = createConnectorWithContext({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var _this = this;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
this._prevState = this._prevState || {};
var cache = props.cache || getInMemoryCache();
if (this._cachedHits === undefined) {
this._cachedHits = cache.read({
state: searchState
}) || {};
}
if (!results) {
return {
hits: extractHitsFromCachedHits(this._cachedHits),
hasPrevious: false,
hasMore: false,
refine: function refine() {},
refinePrevious: function refinePrevious() {},
refineNext: function refineNext() {}
};
}
var page = results.page,
hits = results.hits,
hitsPerPage = results.hitsPerPage,
nbPages = results.nbPages,
_results$_state = results._state;
_results$_state = _results$_state === void 0 ? {} : _results$_state;
var p = _results$_state.page,
currentState = _objectWithoutProperties(_results$_state, ["page"]);
var hitsWithPositions = addAbsolutePositions(hits, hitsPerPage, page);
var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID);
if (!reactFastCompare(currentState, this._prevState)) {
this._cachedHits = cache.read({
state: searchState
}) || {};
}
if (this._cachedHits[page] === undefined) {
this._cachedHits[page] = hitsWithPositionsAndQueryID;
cache.write({
state: searchState,
hits: this._cachedHits
});
}
this._prevState = currentState;
/*
Math.min() and Math.max() returns Infinity or -Infinity when no argument is given.
But there is always something in this point because of `this._cachedHits[page]`.
*/
var firstReceivedPage = Math.min.apply(Math, _toConsumableArray(Object.keys(this._cachedHits).map(Number)));
var lastReceivedPage = Math.max.apply(Math, _toConsumableArray(Object.keys(this._cachedHits).map(Number)));
var hasPrevious = firstReceivedPage > 0;
var lastPageIndex = nbPages - 1;
var hasMore = lastReceivedPage < lastPageIndex;
var refinePrevious = function refinePrevious(event) {
return _this.refine(event, firstReceivedPage - 1);
};
var refineNext = function refineNext(event) {
return _this.refine(event, lastReceivedPage + 1);
};
return {
hits: extractHitsFromCachedHits(this._cachedHits),
hasPrevious: hasPrevious,
hasMore: hasMore,
refinePrevious: refinePrevious,
refineNext: refineNext
};
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQueryParameters({
page: getCurrentRefinement$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) - 1
});
},
refine: function refine(props, searchState, event, index) {
var pages = Object.keys(this._cachedHits || {}).map(Number);
var lastReceivedPage = pages.length === 0 ? undefined : Math.max.apply(Math, _toConsumableArray(pages)); // If there is no key in `this._cachedHits`,
// then `lastReceivedPage` should be `undefined`.
if (index === undefined && lastReceivedPage !== undefined) {
index = lastReceivedPage + 1;
} else if (index === undefined) {
index = getCurrentRefinement$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
var id = getId$5();
var nextValue = _defineProperty({}, id, index + 1);
var resetPage = false;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
}
});
var namespace$2 = 'menu';
function getId$6(props) {
return props.attribute;
}
function getCurrentRefinement$3(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$2, ".").concat(getId$6(props)), null);
if (currentRefinement === '') {
return null;
}
return currentRefinement;
}
function getValue$1(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$3(props, searchState, context);
return name === currentRefinement ? '' : name;
}
function getLimit(_ref) {
var showMore = _ref.showMore,
limit = _ref.limit,
showMoreLimit = _ref.showMoreLimit;
return showMore ? showMoreLimit : limit;
}
function _refine$2(props, searchState, nextRefinement, context) {
var id = getId$6(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$2);
}
function _cleanUp$1(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$2, ".").concat(getId$6(props)));
}
var defaultSortBy = ['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 `attribute` 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} attribute - 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} [limit=10] - the minimum number of diplayed items
* @propType {number} [showMoreLimit=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} [searchable=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 = createConnectorWithContext({
displayName: 'AlgoliaMenu',
propTypes: {
attribute: propTypes.string.isRequired,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
defaultRefinement: propTypes.string,
transformItems: propTypes.func,
searchable: propTypes.bool
},
defaultProps: {
showMore: false,
limit: 10,
showMoreLimit: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var attribute = props.attribute,
searchable = props.searchable,
indexContextValue = props.indexContextValue;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search)
if (searchable && indexContextValue) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: canRefine
};
}
var items;
if (isFromSearch) {
items = searchForFacetValuesResults[attribute].map(function (v) {
return {
label: v.value,
value: getValue$1(v.value, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
_highlightResult: {
label: {
value: v.highlighted
}
},
count: v.count,
isRefined: v.isRefined
};
});
} else {
items = results.getFacetValues(attribute, {
sortBy: searchable ? undefined : defaultSortBy
}).map(function (v) {
return {
label: v.name,
value: getValue$1(v.name, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
count: v.count,
isRefined: v.isRefined
};
});
}
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, getLimit(props)),
currentRefinement: getCurrentRefinement$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$2(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return {
facetName: props.attribute,
query: nextRefinement,
maxFacetHits: getLimit(props)
};
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$1(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute;
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props))
});
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
var currentRefinement = getCurrentRefinement$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (currentRefinement !== null) {
searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$6(props);
var currentRefinement = getCurrentRefinement$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: currentRefinement === null ? [] : [{
label: "".concat(props.attribute, ": ").concat(currentRefinement),
attribute: props.attribute,
value: function value(nextState) {
return _refine$2(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}]
};
}
});
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(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"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
var start = typeof item.start !== 'undefined' ? item.start : '';
var end = typeof item.end !== 'undefined' ? item.end : '';
return "".concat(start, ":").concat(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$3 = 'multiRange';
function getId$7(props) {
return props.attribute;
}
function getCurrentRefinement$4(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$3, ".").concat(getId$7(props)), '');
}
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(attribute, results, value) {
var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : 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({}, getId$7(props), nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$3);
}
function _cleanUp$2(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$3, ".").concat(getId$7(props)));
}
/**
* connectNumericMenu 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 connectNumericMenu
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @kind connector
* @propType {string} attribute - 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 NumericMenu can display.
*/
var connectNumericMenu = createConnectorWithContext({
displayName: 'AlgoliaNumericMenu',
propTypes: {
id: propTypes.string,
attribute: 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 attribute = props.attribute;
var currentRefinement = getCurrentRefinement$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: results ? itemHasRefinement(getId$7(props), results, value) : false
};
});
var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null;
var refinedItem = find(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: refinedItem === undefined,
noRefinement: !stats,
label: 'All'
});
}
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems,
currentRefinement: currentRefinement,
canRefine: transformedItems.length > 0 && transformedItems.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$3(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute;
var _parseItem = parseItem(getCurrentRefinement$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})),
start = _parseItem.start,
end = _parseItem.end;
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
if (typeof start === 'number') {
searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start);
}
if (typeof end === 'number') {
searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$7(props);
var value = getCurrentRefinement$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = [];
var index = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (value !== '') {
var _find = find(props.items, function (item) {
return stringifyItem(item) === value;
}),
label = _find.label;
items.push({
label: "".concat(props.attribute, ": ").concat(label),
attribute: props.attribute,
currentRefinement: label,
value: function value(nextState) {
return _refine$3(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
}
return {
id: id,
index: index,
items: items
};
}
});
function getId$8() {
return 'page';
}
function getCurrentRefinement$5(props, searchState, context) {
var id = getId$8();
var page = 1;
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page);
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
}
function _refine$4(props, searchState, nextPage, context) {
var id = getId$8();
var nextValue = _defineProperty({}, 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} [padding=3] - How many page links to display around the current page.
* @propType {number} [totalPages=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 = createConnectorWithContext({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return null;
}
var nbPages = results.nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
return _refine$4(props, searchState, nextPage, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$8());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) - 1);
},
getMetadata: function getMetadata() {
return {
id: getId$8()
};
}
});
/**
* 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 = createConnectorWithContext({
displayName: 'AlgoliaPoweredBy',
getProvidedProps: function getProvidedProps() {
var hostname = typeof window === 'undefined' ? '' : window.location.hostname;
var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + "utm_content=".concat(hostname, "&") + 'utm_campaign=poweredby';
return {
url: url
};
}
});
/**
* 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 `attribute` 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.
* The values inside the attribute must be JavaScript numbers (not strings).
* @propType {string} attribute - 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=0] - 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
* @providedPropType {number} min - the minimum value available.
* @providedPropType {number} max - the maximum value available.
* @providedPropType {number} precision - Number of digits after decimal point to use.
*/
function getId$9(props) {
return props.attribute;
}
var namespace$4 = 'range';
function getCurrentRange(boundaries, stats, precision) {
var pow = Math.pow(10, precision);
var min;
if (typeof boundaries.min === 'number' && isFinite(boundaries.min)) {
min = boundaries.min;
} else if (typeof stats.min === 'number' && isFinite(stats.min)) {
min = stats.min;
} else {
min = undefined;
}
var max;
if (typeof boundaries.max === 'number' && isFinite(boundaries.max)) {
max = boundaries.max;
} else if (typeof stats.max === 'number' && 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$6(props, searchState, currentRange, context) {
var _getCurrentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$4, ".").concat(getId$9(props)), {}),
min = _getCurrentRefinement.min,
max = _getCurrentRefinement.max;
var isFloatPrecision = Boolean(props.precision);
var nextMin = min;
if (typeof nextMin === 'string') {
nextMin = isFloatPrecision ? parseFloat(nextMin) : parseInt(nextMin, 10);
}
var nextMax = max;
if (typeof nextMax === 'string') {
nextMax = isFloatPrecision ? parseFloat(nextMax) : parseInt(nextMax, 10);
}
var refinement = {
min: nextMin,
max: nextMax
};
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 getCurrentRefinementWithRange(refinement, range) {
return {
min: refinement.min !== undefined ? refinement.min : range.min,
max: refinement.max !== undefined ? refinement.max : range.max
};
}
function nextValueForRefinement(hasBound, isReset, range, value) {
var next;
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$9(props);
var resetPage = true;
var nextValue = _defineProperty({}, id, {
min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber),
max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber)
});
return refineValue(searchState, nextValue, context, resetPage, namespace$4);
}
function _cleanUp$3(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$4, ".").concat(getId$9(props)));
}
var connectRange = createConnectorWithContext({
displayName: 'AlgoliaRange',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
defaultRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
min: propTypes.number,
max: propTypes.number,
precision: propTypes.number,
header: propTypes.node,
footer: propTypes.node
},
defaultProps: {
precision: 0
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute,
precision = props.precision,
minBound = props.min,
maxBound = props.max;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var hasFacet = results && results.getFacetByName(attribute);
var stats = hasFacet ? results.getFacetStats(attribute) || {} : {};
var facetValues = hasFacet ? results.getFacetValues(attribute) : [];
var count = facetValues.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 behavior 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 currentRefinement = getCurrentRefinement$6(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
min: rangeMin,
max: rangeMax,
canRefine: count.length > 0,
currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange),
count: count,
precision: precision
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$5(props, searchState, nextRefinement, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attribute = props.attribute;
var _getCurrentRefinement2 = getCurrentRefinement$6(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
min = _getCurrentRefinement2.min,
max = _getCurrentRefinement2.max;
params = params.addDisjunctiveFacet(attribute);
if (min !== undefined) {
params = params.addNumericRefinement(attribute, '>=', min);
}
if (max !== undefined) {
params = params.addNumericRefinement(attribute, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var _this$_currentRange = this._currentRange,
minRange = _this$_currentRange.min,
maxRange = _this$_currentRange.max;
var _getCurrentRefinement3 = getCurrentRefinement$6(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
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 ? "".concat(minValue, " <= ") : '', props.attribute, hasMax ? " <= ".concat(maxValue) : ''];
items.push({
label: fragments.join(''),
attribute: props.attribute,
value: function value(nextState) {
return _refine$5(props, nextState, {}, _this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: getCurrentRefinementWithRange({
min: minValue,
max: maxValue
}, {
min: minRange,
max: maxRange
})
});
}
return {
id: getId$9(props),
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: items
};
}
});
var namespace$5 = 'refinementList';
function getId$a(props) {
return props.attribute;
}
function getCurrentRefinement$7(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$5, ".").concat(getId$a(props)), []);
if (typeof currentRefinement !== 'string') {
return currentRefinement;
}
if (currentRefinement) {
return [currentRefinement];
}
return [];
}
function getValue$2(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$7(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 getLimit$1(_ref) {
var showMore = _ref.showMore,
limit = _ref.limit,
showMoreLimit = _ref.showMoreLimit;
return showMore ? showMoreLimit : limit;
}
function _refine$6(props, searchState, nextRefinement, context) {
var id = getId$a(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 refineValue(searchState, nextValue, context, resetPage, namespace$5);
}
function _cleanUp$4(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$5, ".").concat(getId$a(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 `attribute` 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} attribute - the name of the attribute in the record
* @propType {boolean} [searchable=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} [limit=10] - the minimum number of displayed items
* @propType {number} [showMoreLimit=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.
* @providedPropType {boolean} canRefine - a boolean that says whether you can refine
*/
var sortBy$1 = ['isRefined', 'count:desc', 'name:asc'];
var connectRefinementList = createConnectorWithContext({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
operator: propTypes.oneOf(['and', 'or']),
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])),
searchable: propTypes.bool,
transformItems: propTypes.func
},
defaultProps: {
operator: 'or',
showMore: false,
limit: 10,
showMoreLimit: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var attribute = props.attribute,
searchable = props.searchable,
indexContextValue = props.indexContextValue;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search)
if (searchable && indexContextValue) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: canRefine,
isFromSearch: isFromSearch,
searchable: searchable
};
}
var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) {
return {
label: v.value,
value: getValue$2(v.value, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
_highlightResult: {
label: {
value: v.highlighted
}
},
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attribute, {
sortBy: sortBy$1
}).map(function (v) {
return {
label: v.name,
value: getValue$2(v.name, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, getLimit$1(props)),
currentRefinement: getCurrentRefinement$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$6(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return {
facetName: props.attribute,
query: nextRefinement,
maxFacetHits: getLimit$1(props)
};
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute,
operator = props.operator;
var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet';
var addRefinementKey = "".concat(addKey, "Refinement");
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props))
});
searchParameters = searchParameters[addKey](attribute);
return getCurrentRefinement$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}).reduce(function (res, val) {
return res[addRefinementKey](attribute, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$a(props);
var context = {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
};
return {
id: id,
index: getIndexId(context),
items: getCurrentRefinement$7(props, searchState, context).length > 0 ? [{
attribute: props.attribute,
label: "".concat(props.attribute, ": "),
currentRefinement: getCurrentRefinement$7(props, searchState, context),
value: function value(nextState) {
return _refine$6(props, nextState, [], context);
},
items: getCurrentRefinement$7(props, searchState, context).map(function (item) {
return {
label: "".concat(item),
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement$7(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 = createConnectorWithContext({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: propTypes.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var id = props.scrollOn;
var value = getCurrentRefinementValue(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, id, null);
if (!this._prevSearchState) {
this._prevSearchState = {};
} // Get the subpart of the state that interest us
if (hasMultipleIndices({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})) {
searchState = searchState.indices ? searchState.indices[getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})] : {};
} // 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 comparison 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(searchState, ['configure', id]);
var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState);
this._prevSearchState = cleanedSearchState;
return {
value: value,
hasNotChanged: hasNotChanged
};
}
});
function getId$b() {
return 'query';
}
function getCurrentRefinement$8(props, searchState, context) {
var id = getId$b();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, '');
if (currentRefinement) {
return currentRefinement;
}
return '';
}
function _refine$7(props, searchState, nextRefinement, context) {
var id = getId$b();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage);
}
function _cleanUp$5(props, searchState, context) {
return cleanUpValue(searchState, context, getId$b());
}
/**
* connectSearchBox connector provides the logic to build a widget that will
* let the user search for a query
* @name connectSearchBox
* @kind connector
* @propType {string} [defaultRefinement] - Provide a default value for the query
* @providedPropType {function} refine - a function to change the current query
* @providedPropType {string} currentRefinement - the current query used
* @providedPropType {boolean} isSearchStalled - a flag that indicates if InstantSearch has detected that searches are stalled
*/
var connectSearchBox = createConnectorWithContext({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: propTypes.string
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
return {
currentRefinement: getCurrentRefinement$8(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isSearchStalled: searchResults.isSearchStalled
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$7(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement$8(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}));
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$b();
var currentRefinement = getCurrentRefinement$8(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: currentRefinement === null ? [] : [{
label: "".concat(id, ": ").concat(currentRefinement),
value: function value(nextState) {
return _refine$7(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}]
};
}
});
function getId$c() {
return 'sortBy';
}
function getCurrentRefinement$9(props, searchState, context) {
var id = getId$c();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null);
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 = createConnectorWithContext({
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$9(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _objectSpread({}, item, {
isRefined: true
}) : _objectSpread({}, item, {
isRefined: false
});
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId$c();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$c());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement$9(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return {
id: getId$c()
};
}
});
/**
* 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 = createConnectorWithContext({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return null;
}
return {
nbHits: results.nbHits,
processingTimeMS: results.processingTimeMS
};
}
});
function getId$d(props) {
return props.attribute;
}
var namespace$6 = 'toggle';
var falsyStrings = ['0', 'false', 'null', 'undefined'];
function getCurrentRefinement$a(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$6, ".").concat(getId$d(props)), false);
if (falsyStrings.indexOf(currentRefinement) !== -1) {
return false;
}
return Boolean(currentRefinement);
}
function _refine$8(props, searchState, nextRefinement, context) {
var id = getId$d(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$6);
}
function _cleanUp$6(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$6, ".").concat(getId$d(props)));
}
/**
* connectToggleRefinement connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value.
* @name connectToggleRefinement
* @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} attribute - 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 `attribute`.
* @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise
* @providedPropType {object} count - an object that contains the count for `checked` and `unchecked` state
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
*/
var connectToggleRefinement = createConnectorWithContext({
displayName: 'AlgoliaToggle',
propTypes: {
label: propTypes.string.isRequired,
attribute: propTypes.string.isRequired,
value: propTypes.any.isRequired,
filter: propTypes.func,
defaultRefinement: propTypes.bool
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute,
value = props.value;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var currentRefinement = getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var allFacetValues = results && results.getFacetByName(attribute) ? results.getFacetValues(attribute) : null;
var facetValue = // Use null to always be consistent with type of the value
// count: number | null
allFacetValues && allFacetValues.length ? find(allFacetValues, function (item) {
return item.name === value.toString();
}) : null;
var facetValueCount = facetValue && facetValue.count;
var allFacetValuesCount = // Use null to always be consistent with type of the value
// count: number | null
allFacetValues && allFacetValues.length ? allFacetValues.reduce(function (acc, item) {
return acc + item.count;
}, 0) : null;
var canRefine = currentRefinement ? allFacetValuesCount !== null && allFacetValuesCount > 0 : facetValueCount !== null && facetValueCount > 0;
var count = {
checked: allFacetValuesCount,
unchecked: facetValueCount
};
return {
currentRefinement: currentRefinement,
canRefine: canRefine,
count: count
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$8(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute,
value = props.value,
filter = props.filter;
var checked = getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var nextSearchParameters = searchParameters.addDisjunctiveFacet(attribute);
if (checked) {
nextSearchParameters = nextSearchParameters.addDisjunctiveFacetRefinement(attribute, value);
if (filter) {
nextSearchParameters = filter(nextSearchParameters);
}
}
return nextSearchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$d(props);
var checked = getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = [];
var index = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (checked) {
items.push({
label: props.label,
currentRefinement: checked,
attribute: props.attribute,
value: function value(nextState) {
return _refine$8(props, nextState, false, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
}
return {
id: id,
index: index,
items: items
};
}
});
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
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 ( module.exports) {
module.exports = classNames;
} else {
window.classNames = classNames;
}
}());
});
var createClassNames = function createClassNames(block) {
var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'ais';
return function () {
for (var _len = arguments.length, elements = new Array(_len), _key = 0; _key < _len; _key++) {
elements[_key] = arguments[_key];
}
var suitElements = elements.filter(function (element) {
return element || element === '';
}).map(function (element) {
var baseClassName = "".concat(prefix, "-").concat(block);
return element ? "".concat(baseClassName, "-").concat(element) : baseClassName;
});
return classnames(suitElements);
};
};
var isSpecialClick = function isSpecialClick(event) {
var isMiddleClick = event.button === 1;
return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
};
var capitalize = function capitalize(key) {
return key.length === 0 ? '' : "".concat(key[0].toUpperCase()).concat(key.slice(1));
}; // taken from InstantSearch.js/utils
function range(_ref) {
var _ref$start = _ref.start,
start = _ref$start === void 0 ? 0 : _ref$start,
end = _ref.end,
_ref$step = _ref.step,
step = _ref$step === void 0 ? 1 : _ref$step; // We can't divide by 0 so we re-assign the step to 1 if it happens.
var limitStep = step === 0 ? 1 : step; // In some cases the array to create has a decimal length.
// We therefore need to round the value.
// Example:
// { start: 1, end: 5000, step: 500 }
// => Array length = (5000 - 1) / 500 = 9.998
var arrayLength = Math.round((end - start) / limitStep);
return _toConsumableArray(Array(arrayLength)).map(function (_, current) {
return (start + current) * limitStep;
});
}
function find$2(array, comparator) {
if (!Array.isArray(array)) {
return undefined;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return array[i];
}
}
return undefined;
}
var cx = createClassNames('Panel');
var _createContext$1 = React.createContext(function setCanRefine() {}),
PanelConsumer = _createContext$1.Consumer,
PanelProvider = _createContext$1.Provider;
var Panel =
/*#__PURE__*/
function (_Component) {
_inherits(Panel, _Component);
function Panel() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, Panel);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Panel)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "state", {
canRefine: true
});
_defineProperty(_assertThisInitialized(_this), "setCanRefine", function (nextCanRefine) {
_this.setState({
canRefine: nextCanRefine
});
});
return _this;
}
_createClass(Panel, [{
key: "render",
value: function render() {
var _this$props = this.props,
children = _this$props.children,
className = _this$props.className,
header = _this$props.header,
footer = _this$props.footer;
var canRefine = this.state.canRefine;
return React__default.createElement("div", {
className: classnames(cx('', !canRefine && '-noRefinement'), className)
}, header && React__default.createElement("div", {
className: cx('header')
}, header), React__default.createElement("div", {
className: cx('body')
}, React__default.createElement(PanelProvider, {
value: this.setCanRefine
}, children)), footer && React__default.createElement("div", {
className: cx('footer')
}, footer));
}
}]);
return Panel;
}(React.Component);
_defineProperty(Panel, "propTypes", {
children: propTypes.node.isRequired,
className: propTypes.string,
header: propTypes.node,
footer: propTypes.node
});
_defineProperty(Panel, "defaultProps", {
className: '',
header: null,
footer: null
});
var PanelCallbackHandler =
/*#__PURE__*/
function (_Component) {
_inherits(PanelCallbackHandler, _Component);
function PanelCallbackHandler() {
_classCallCheck(this, PanelCallbackHandler);
return _possibleConstructorReturn(this, _getPrototypeOf(PanelCallbackHandler).apply(this, arguments));
}
_createClass(PanelCallbackHandler, [{
key: "componentDidMount",
value: function componentDidMount() {
this.props.setCanRefine(this.props.canRefine);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.canRefine !== this.props.canRefine) {
this.props.setCanRefine(this.props.canRefine);
}
}
}, {
key: "render",
value: function render() {
return this.props.children;
}
}]);
return PanelCallbackHandler;
}(React.Component);
_defineProperty(PanelCallbackHandler, "propTypes", {
children: propTypes.node.isRequired,
canRefine: propTypes.bool.isRequired,
setCanRefine: propTypes.func.isRequired
});
var PanelWrapper = function PanelWrapper(_ref) {
var canRefine = _ref.canRefine,
children = _ref.children;
return React__default.createElement(PanelConsumer, null, function (setCanRefine) {
return React__default.createElement(PanelCallbackHandler, {
setCanRefine: setCanRefine,
canRefine: canRefine
}, children);
});
};
var Link =
/*#__PURE__*/
function (_Component) {
_inherits(Link, _Component);
function Link() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, Link);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Link)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "onClick", function (e) {
if (isSpecialClick(e)) {
return;
}
_this.props.onClick();
e.preventDefault();
});
return _this;
}
_createClass(Link, [{
key: "render",
value: function render() {
return React__default.createElement("a", _extends({}, this.props, {
onClick: this.onClick
}));
}
}]);
return Link;
}(React.Component);
_defineProperty(Link, "propTypes", {
onClick: propTypes.func.isRequired
});
var cx$1 = createClassNames('Breadcrumb');
var itemsPropType = propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired
}));
var Breadcrumb =
/*#__PURE__*/
function (_Component) {
_inherits(Breadcrumb, _Component);
function Breadcrumb() {
_classCallCheck(this, Breadcrumb);
return _possibleConstructorReturn(this, _getPrototypeOf(Breadcrumb).apply(this, arguments));
}
_createClass(Breadcrumb, [{
key: "render",
value: function render() {
var _this$props = this.props,
canRefine = _this$props.canRefine,
createURL = _this$props.createURL,
items = _this$props.items,
refine = _this$props.refine,
rootURL = _this$props.rootURL,
separator = _this$props.separator,
translate = _this$props.translate,
className = _this$props.className;
var rootPath = canRefine ? React__default.createElement("li", {
className: cx$1('item')
}, React__default.createElement(Link, {
className: cx$1('link'),
onClick: function onClick() {
return !rootURL ? refine() : null;
},
href: rootURL ? rootURL : createURL()
}, translate('rootLabel'))) : null;
var breadcrumb = items.map(function (item, idx) {
var isLast = idx === items.length - 1;
return React__default.createElement("li", {
className: cx$1('item', isLast && 'item--selected'),
key: idx
}, React__default.createElement("span", {
className: cx$1('separator')
}, separator), !isLast ? React__default.createElement(Link, {
className: cx$1('link'),
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
}, item.label) : item.label);
});
return React__default.createElement("div", {
className: classnames(cx$1('', !canRefine && '-noRefinement'), className)
}, React__default.createElement("ul", {
className: cx$1('list')
}, rootPath, breadcrumb));
}
}]);
return Breadcrumb;
}(React.Component);
_defineProperty(Breadcrumb, "propTypes", {
canRefine: propTypes.bool.isRequired,
createURL: propTypes.func.isRequired,
items: itemsPropType,
refine: propTypes.func.isRequired,
rootURL: propTypes.string,
separator: propTypes.node,
translate: propTypes.func.isRequired,
className: propTypes.string
});
_defineProperty(Breadcrumb, "defaultProps", {
rootURL: null,
separator: ' > ',
className: ''
});
var Breadcrumb$1 = translatable({
rootLabel: 'Home'
})(Breadcrumb);
/**
* A breadcrumb is a secondary navigation scheme that allows the user to see where the current page
* is in relation to the website or web application’s hierarchy.
* In terms of usability, using a breadcrumb reduces the number of actions a visitor needs to take in
* order to get to a higher-level page.
*
* If you want to select a specific refinement for your Breadcrumb component, you will need to
* use a [Virtual Hierarchical Menu](https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html)
* and set its defaultRefinement that will be then used by the Breadcrumb.
*
* @name Breadcrumb
* @kind widget
* @requirements Breadcrumbs are used for websites with a large amount of content organised in a hierarchical manner.
* The typical example is an e-commerce website which has a large variety of products grouped into logical categories
* (with categories, subcategories which also have subcategories).To use this widget, your attributes must be formatted in a specific way.
*
* Keep in mind that breadcrumbs shouldn’t replace effective primary navigation menus:
* it is only an alternative way to navigate around the website.
*
* If, for instance, you would like 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.
*
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow
* @propType {node} [separator='>'] - Symbol used for separating hyperlinks
* @propType {string} [rootURL=null] - The originating page (homepage)
* @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-Breadcrumb - the root div of the widget
* @themeKey ais-Breadcrumb--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-Breadcrumb-list - the list of all breadcrumb items
* @themeKey ais-Breadcrumb-item - the breadcrumb navigation item
* @themeKey ais-Breadcrumb-item--selected - the selected breadcrumb item
* @themeKey ais-Breadcrumb-separator - the separator of each breadcrumb item
* @themeKey ais-Breadcrumb-link - the clickable breadcrumb element
* @translationKey rootLabel - The root's label. Accepts a string
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { Breadcrumb, InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <Breadcrumb
* attributes={[
* 'hierarchicalCategories.lvl0',
* 'hierarchicalCategories.lvl1',
* 'hierarchicalCategories.lvl2',
* ]}
* />
* <HierarchicalMenu
* defaultRefinement="Cameras & Camcorders"
* attributes={[
* 'hierarchicalCategories.lvl0',
* 'hierarchicalCategories.lvl1',
* 'hierarchicalCategories.lvl2',
* ]}
* />
* </InstantSearch>
* );
*/
var BreadcrumbWidget = function BreadcrumbWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(Breadcrumb$1, props));
};
var Breadcrumb$2 = connectBreadcrumb(BreadcrumbWidget);
var cx$2 = createClassNames('ClearRefinements');
var ClearRefinements =
/*#__PURE__*/
function (_Component) {
_inherits(ClearRefinements, _Component);
function ClearRefinements() {
_classCallCheck(this, ClearRefinements);
return _possibleConstructorReturn(this, _getPrototypeOf(ClearRefinements).apply(this, arguments));
}
_createClass(ClearRefinements, [{
key: "render",
value: function render() {
var _this$props = this.props,
items = _this$props.items,
canRefine = _this$props.canRefine,
refine = _this$props.refine,
translate = _this$props.translate,
className = _this$props.className;
return React__default.createElement("div", {
className: classnames(cx$2(''), className)
}, React__default.createElement("button", {
className: cx$2('button', !canRefine && 'button--disabled'),
onClick: function onClick() {
return refine(items);
},
disabled: !canRefine
}, translate('reset')));
}
}]);
return ClearRefinements;
}(React.Component);
_defineProperty(ClearRefinements, "propTypes", {
items: propTypes.arrayOf(propTypes.object).isRequired,
canRefine: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
});
_defineProperty(ClearRefinements, "defaultProps", {
className: ''
});
var ClearRefinements$1 = translatable({
reset: 'Clear all filters'
})(ClearRefinements);
/**
* The ClearRefinements widget displays a button that lets the user clean every refinement applied
* to the search.
* @name ClearRefinements
* @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-ClearRefinements - the root div of the widget
* @themeKey ais-ClearRefinements-button - the clickable button
* @themeKey ais-ClearRefinements-button--disabled - the disabled clickable button
* @translationKey reset - the clear all button value
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, ClearRefinements, RefinementList } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <ClearRefinements />
* <RefinementList
* attribute="brand"
* defaultRefinement={['Apple']}
* />
* </InstantSearch>
* );
*/
var ClearRefinementsWidget = function ClearRefinementsWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(ClearRefinements$1, props));
};
var ClearRefinements$2 = connectCurrentRefinements(ClearRefinementsWidget);
var cx$3 = createClassNames('CurrentRefinements');
var CurrentRefinements = function CurrentRefinements(_ref) {
var items = _ref.items,
canRefine = _ref.canRefine,
refine = _ref.refine,
translate = _ref.translate,
className = _ref.className;
return React__default.createElement("div", {
className: classnames(cx$3('', !canRefine && '-noRefinement'), className)
}, React__default.createElement("ul", {
className: cx$3('list', !canRefine && 'list--noRefinement')
}, items.map(function (item) {
return React__default.createElement("li", {
key: item.label,
className: cx$3('item')
}, React__default.createElement("span", {
className: cx$3('label')
}, item.label), item.items ? item.items.map(function (nest) {
return React__default.createElement("span", {
key: nest.label,
className: cx$3('category')
}, React__default.createElement("span", {
className: cx$3('categoryLabel')
}, nest.label), React__default.createElement("button", {
className: cx$3('delete'),
onClick: function onClick() {
return refine(nest.value);
}
}, translate('clearFilter', nest)));
}) : React__default.createElement("span", {
className: cx$3('category')
}, React__default.createElement("button", {
className: cx$3('delete'),
onClick: function onClick() {
return refine(item.value);
}
}, translate('clearFilter', item))));
})));
};
var itemPropTypes = propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.func.isRequired,
items: function items() {
return itemPropTypes.apply(void 0, arguments);
}
}));
CurrentRefinements.defaultProps = {
className: ''
};
var CurrentRefinements$1 = translatable({
clearFilter: '✕'
})(CurrentRefinements);
/**
* 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 - the root div of the widget
* @themeKey ais-CurrentRefinements--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-CurrentRefinements-list - the list of all refined items
* @themeKey ais-CurrentRefinements-list--noRefinement - the list of all refined items when there is no refinement
* @themeKey ais-CurrentRefinements-item - the refined list item
* @themeKey ais-CurrentRefinements-button - the button of each refined list item
* @themeKey ais-CurrentRefinements-label - the refined list label
* @themeKey ais-CurrentRefinements-category - the category of each item
* @themeKey ais-CurrentRefinements-categoryLabel - the label of each catgory
* @themeKey ais-CurrentRefinements-delete - the delete button of each label
* @translationKey clearFilter - the remove filter button label
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, CurrentRefinements, RefinementList } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <CurrentRefinements />
* <RefinementList
* attribute="brand"
* defaultRefinement={['Colors']}
* />
* </InstantSearch>
* );
*/
var CurrentRefinementsWidget = function CurrentRefinementsWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(CurrentRefinements$1, props));
};
var CurrentRefinements$2 = connectCurrentRefinements(CurrentRefinementsWidget);
var cx$4 = createClassNames('SearchBox');
var defaultLoadingIndicator = React__default.createElement("svg", {
width: "18",
height: "18",
viewBox: "0 0 38 38",
xmlns: "http://www.w3.org/2000/svg",
stroke: "#444",
className: cx$4('loadingIcon')
}, React__default.createElement("g", {
fill: "none",
fillRule: "evenodd"
}, React__default.createElement("g", {
transform: "translate(1 1)",
strokeWidth: "2"
}, React__default.createElement("circle", {
strokeOpacity: ".5",
cx: "18",
cy: "18",
r: "18"
}), React__default.createElement("path", {
d: "M36 18c0-9.94-8.06-18-18-18"
}, React__default.createElement("animateTransform", {
attributeName: "transform",
type: "rotate",
from: "0 18 18",
to: "360 18 18",
dur: "1s",
repeatCount: "indefinite"
})))));
var defaultReset = React__default.createElement("svg", {
className: cx$4('resetIcon'),
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 20 20",
width: "10",
height: "10"
}, React__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"
}));
var defaultSubmit = React__default.createElement("svg", {
className: cx$4('submitIcon'),
xmlns: "http://www.w3.org/2000/svg",
width: "10",
height: "10",
viewBox: "0 0 40 40"
}, React__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"
}));
var SearchBox =
/*#__PURE__*/
function (_Component) {
_inherits(SearchBox, _Component);
function SearchBox(props) {
var _this;
_classCallCheck(this, SearchBox);
_this = _possibleConstructorReturn(this, _getPrototypeOf(SearchBox).call(this));
_defineProperty(_assertThisInitialized(_this), "getQuery", function () {
return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query;
});
_defineProperty(_assertThisInitialized(_this), "onInputMount", function (input) {
_this.input = input;
if (!_this.props.inputRef) return;
if (typeof _this.props.inputRef === 'function') {
_this.props.inputRef(input);
} else {
_this.props.inputRef.current = input;
}
});
_defineProperty(_assertThisInitialized(_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();
});
_defineProperty(_assertThisInitialized(_this), "onSubmit", function (e) {
e.preventDefault();
e.stopPropagation();
_this.input.blur();
var _this$props = _this.props,
refine = _this$props.refine,
searchAsYouType = _this$props.searchAsYouType;
if (!searchAsYouType) {
refine(_this.getQuery());
}
return false;
});
_defineProperty(_assertThisInitialized(_this), "onChange", function (event) {
var _this$props2 = _this.props,
searchAsYouType = _this$props2.searchAsYouType,
refine = _this$props2.refine,
onChange = _this$props2.onChange;
var value = event.target.value;
if (searchAsYouType) {
refine(value);
} else {
_this.setState({
query: value
});
}
if (onChange) {
onChange(event);
}
});
_defineProperty(_assertThisInitialized(_this), "onReset", function (event) {
var _this$props3 = _this.props,
searchAsYouType = _this$props3.searchAsYouType,
refine = _this$props3.refine,
onReset = _this$props3.onReset;
refine('');
_this.input.focus();
if (!searchAsYouType) {
_this.setState({
query: ''
});
}
if (onReset) {
onReset(event);
}
});
_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: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (!this.props.searchAsYouType && prevProps.currentRefinement !== this.props.currentRefinement) {
this.setState({
query: this.props.currentRefinement
});
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$props4 = this.props,
className = _this$props4.className,
translate = _this$props4.translate,
autoFocus = _this$props4.autoFocus,
loadingIndicator = _this$props4.loadingIndicator,
submit = _this$props4.submit,
reset = _this$props4.reset;
var query = this.getQuery();
var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) {
if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) {
return _objectSpread({}, props, _defineProperty({}, prop, _this2.props[prop]));
}
return props;
}, {});
var isSearchStalled = this.props.showLoadingIndicator && this.props.isSearchStalled;
/* eslint-disable max-len */
return React__default.createElement("div", {
className: classnames(cx$4(''), className)
}, React__default.createElement("form", {
noValidate: true,
onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit,
onReset: this.onReset,
className: cx$4('form', isSearchStalled && 'form--stalledSearch'),
action: "",
role: "search"
}, React__default.createElement("input", _extends({
ref: this.onInputMount,
type: "search",
placeholder: translate('placeholder'),
autoFocus: autoFocus,
autoComplete: "off",
autoCorrect: "off",
autoCapitalize: "off",
spellCheck: "false",
required: true,
maxLength: "512",
value: query,
onChange: this.onChange
}, searchInputEvents, {
className: cx$4('input')
})), React__default.createElement("button", {
type: "submit",
title: translate('submitTitle'),
className: cx$4('submit')
}, submit), React__default.createElement("button", {
type: "reset",
title: translate('resetTitle'),
className: cx$4('reset'),
hidden: !query || isSearchStalled
}, reset), this.props.showLoadingIndicator && React__default.createElement("span", {
hidden: !isSearchStalled,
className: cx$4('loadingIndicator')
}, loadingIndicator)));
/* eslint-enable */
}
}]);
return SearchBox;
}(React.Component);
_defineProperty(SearchBox, "propTypes", {
currentRefinement: propTypes.string,
className: propTypes.string,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
loadingIndicator: propTypes.node,
reset: propTypes.node,
submit: propTypes.node,
focusShortcuts: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])),
autoFocus: propTypes.bool,
searchAsYouType: propTypes.bool,
onSubmit: propTypes.func,
onReset: propTypes.func,
onChange: propTypes.func,
isSearchStalled: propTypes.bool,
showLoadingIndicator: propTypes.bool,
inputRef: propTypes.oneOfType([propTypes.func, propTypes.exact({
current: propTypes.object
})])
});
_defineProperty(SearchBox, "defaultProps", {
currentRefinement: '',
className: '',
focusShortcuts: ['s', '/'],
autoFocus: false,
searchAsYouType: true,
showLoadingIndicator: false,
isSearchStalled: false,
loadingIndicator: defaultLoadingIndicator,
reset: defaultReset,
submit: defaultSubmit
});
var SearchBox$1 = translatable({
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(SearchBox);
var itemsPropType$1 = propTypes.arrayOf(propTypes.shape({
value: propTypes.any,
label: propTypes.node.isRequired,
items: function items() {
return itemsPropType$1.apply(void 0, arguments);
}
}));
var List =
/*#__PURE__*/
function (_Component) {
_inherits(List, _Component);
function List() {
var _this;
_classCallCheck(this, List);
_this = _possibleConstructorReturn(this, _getPrototypeOf(List).call(this));
_defineProperty(_assertThisInitialized(_this), "onShowMoreClick", function () {
_this.setState(function (state) {
return {
extended: !state.extended
};
});
});
_defineProperty(_assertThisInitialized(_this), "getLimit", function () {
var _this$props = _this.props,
limit = _this$props.limit,
showMoreLimit = _this$props.showMoreLimit;
var extended = _this.state.extended;
return extended ? showMoreLimit : limit;
});
_defineProperty(_assertThisInitialized(_this), "resetQuery", function () {
_this.setState({
query: ''
});
});
_defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) {
var itemHasChildren = item.items && Boolean(item.items.length);
return React__default.createElement("li", {
key: item.key || item.label,
className: _this.props.cx('item', item.isRefined && 'item--selected', item.noRefinement && 'item--noRefinement', itemHasChildren && 'item--parent')
}, _this.props.renderItem(item, resetQuery), itemHasChildren && React__default.createElement("ul", {
className: _this.props.cx('list', 'list--child')
}, item.items.slice(0, _this.getLimit()).map(function (child) {
return _this.renderItem(child, item);
})));
});
_this.state = {
extended: false,
query: ''
};
return _this;
}
_createClass(List, [{
key: "renderShowMore",
value: function renderShowMore() {
var _this$props2 = this.props,
showMore = _this$props2.showMore,
translate = _this$props2.translate,
cx = _this$props2.cx;
var extended = this.state.extended;
var disabled = this.props.limit >= this.props.items.length;
if (!showMore) {
return null;
}
return React__default.createElement("button", {
disabled: disabled,
className: cx('showMore', disabled && 'showMore--disabled'),
onClick: this.onShowMoreClick
}, translate('showMore', extended));
}
}, {
key: "renderSearchBox",
value: function renderSearchBox() {
var _this2 = this;
var _this$props3 = this.props,
cx = _this$props3.cx,
searchForItems = _this$props3.searchForItems,
isFromSearch = _this$props3.isFromSearch,
translate = _this$props3.translate,
items = _this$props3.items,
selectItem = _this$props3.selectItem;
var noResults = items.length === 0 && this.state.query !== '' ? React__default.createElement("div", {
className: cx('noResults')
}, translate('noResults')) : null;
return React__default.createElement("div", {
className: cx('searchBox')
}, React__default.createElement(SearchBox$1, {
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 _this$props4 = this.props,
cx = _this$props4.cx,
items = _this$props4.items,
className = _this$props4.className,
searchable = _this$props4.searchable,
canRefine = _this$props4.canRefine;
var searchBox = searchable ? this.renderSearchBox() : null;
var rootClassName = classnames(cx('', !canRefine && '-noRefinement'), className);
if (items.length === 0) {
return React__default.createElement("div", {
className: rootClassName
}, 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.
return React__default.createElement("div", {
className: rootClassName
}, searchBox, React__default.createElement("ul", {
className: cx('list', !canRefine && 'list--noRefinement')
}, items.slice(0, this.getLimit()).map(function (item) {
return _this3.renderItem(item, _this3.resetQuery);
})), this.renderShowMore());
}
}]);
return List;
}(React.Component);
_defineProperty(List, "propTypes", {
cx: propTypes.func.isRequired,
// Only required with showMore.
translate: propTypes.func,
items: itemsPropType$1,
renderItem: propTypes.func.isRequired,
selectItem: propTypes.func,
className: propTypes.string,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
show: propTypes.func,
searchForItems: propTypes.func,
searchable: propTypes.bool,
isFromSearch: propTypes.bool,
canRefine: propTypes.bool
});
_defineProperty(List, "defaultProps", {
className: '',
isFromSearch: false
});
var cx$5 = createClassNames('HierarchicalMenu');
var itemsPropType$2 = propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string,
count: propTypes.number.isRequired,
items: function items() {
return itemsPropType$2.apply(void 0, arguments);
}
}));
var HierarchicalMenu =
/*#__PURE__*/
function (_Component) {
_inherits(HierarchicalMenu, _Component);
function HierarchicalMenu() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, HierarchicalMenu);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(HierarchicalMenu)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "renderItem", function (item) {
var _this$props = _this.props,
createURL = _this$props.createURL,
refine = _this$props.refine;
return React__default.createElement(Link, {
className: cx$5('link'),
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
}, React__default.createElement("span", {
className: cx$5('label')
}, item.label), ' ', React__default.createElement("span", {
className: cx$5('count')
}, item.count));
});
return _this;
}
_createClass(HierarchicalMenu, [{
key: "render",
value: function render() {
var _this$props2 = this.props,
translate = _this$props2.translate,
items = _this$props2.items,
showMore = _this$props2.showMore,
limit = _this$props2.limit,
showMoreLimit = _this$props2.showMoreLimit,
canRefine = _this$props2.canRefine,
className = _this$props2.className;
return React__default.createElement(List, {
renderItem: this.renderItem,
cx: cx$5,
translate: translate,
items: items,
showMore: showMore,
limit: limit,
showMoreLimit: showMoreLimit,
canRefine: canRefine,
className: className
});
}
}]);
return HierarchicalMenu;
}(React.Component);
_defineProperty(HierarchicalMenu, "propTypes", {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired,
items: itemsPropType$2,
showMore: propTypes.bool,
className: propTypes.string,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func
});
_defineProperty(HierarchicalMenu, "defaultProps", {
className: ''
});
var HierarchicalMenu$1 = translatable({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
}
})(HierarchicalMenu);
/**
* 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
* [{
* "objectID": "321432",
* "name": "lemon",
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* },
* {
* "objectID": "8976987",
* "name": "orange",
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* }]
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "objectID": "321432",
* "name": "lemon",
* "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 {array.<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 limit and showMoreLimit.
* @propType {number} [limit=10] - The maximum number of items displayed.
* @propType {number} [showMoreLimit=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 path to use if the first level is not the root level.
* @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 - the root div of the widget
* @themeKey ais-HierarchicalMenu-noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-HierarchicalMenu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @themeKey ais-HierarchicalMenu-list - the list of menu items
* @themeKey ais-HierarchicalMenu-list--child - the child list of menu items
* @themeKey ais-HierarchicalMenu-item - the menu list item
* @themeKey ais-HierarchicalMenu-item--selected - the selected menu list item
* @themeKey ais-HierarchicalMenu-item--parent - the menu list item containing children
* @themeKey ais-HierarchicalMenu-link - the clickable menu element
* @themeKey ais-HierarchicalMenu-label - the label of each item
* @themeKey ais-HierarchicalMenu-count - the count of values for each item
* @themeKey ais-HierarchicalMenu-showMore - the button used to display more categories
* @themeKey ais-HierarchicalMenu-showMore--disabled - the disabled button used to display more categories
* @translationKey showMore - The label of the show more button. Accepts one parameter, a boolean that is true if the values are expanded
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <HierarchicalMenu
* attributes={[
* 'hierarchicalCategories.lvl0',
* 'hierarchicalCategories.lvl1',
* 'hierarchicalCategories.lvl2',
* ]}
* />
* </InstantSearch>
* );
*/
var HierarchicalMenuWidget = function HierarchicalMenuWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(HierarchicalMenu$1, props));
};
var HierarchicalMenu$2 = connectHierarchicalMenu(HierarchicalMenuWidget);
var Highlight = function Highlight(_ref) {
var cx = _ref.cx,
value = _ref.value,
highlightedTagName = _ref.highlightedTagName,
isHighlighted = _ref.isHighlighted,
nonHighlightedTagName = _ref.nonHighlightedTagName;
var TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName;
var className = isHighlighted ? 'highlighted' : 'nonHighlighted';
return React__default.createElement(TagName, {
className: cx(className)
}, value);
};
var Highlighter = function Highlighter(_ref2) {
var cx = _ref2.cx,
hit = _ref2.hit,
attribute = _ref2.attribute,
highlight = _ref2.highlight,
highlightProperty = _ref2.highlightProperty,
tagName = _ref2.tagName,
nonHighlightedTagName = _ref2.nonHighlightedTagName,
separator = _ref2.separator,
className = _ref2.className;
var parsedHighlightedValue = highlight({
hit: hit,
attribute: attribute,
highlightProperty: highlightProperty
});
return React__default.createElement("span", {
className: classnames(cx(''), className)
}, parsedHighlightedValue.map(function (item, i) {
if (Array.isArray(item)) {
var isLast = i === parsedHighlightedValue.length - 1;
return React__default.createElement("span", {
key: i
}, item.map(function (element, index) {
return React__default.createElement(Highlight, {
cx: cx,
key: index,
value: element.value,
highlightedTagName: tagName,
nonHighlightedTagName: nonHighlightedTagName,
isHighlighted: element.isHighlighted
});
}), !isLast && React__default.createElement("span", {
className: cx('separator')
}, separator));
}
return React__default.createElement(Highlight, {
cx: cx,
key: i,
value: item.value,
highlightedTagName: tagName,
nonHighlightedTagName: nonHighlightedTagName,
isHighlighted: item.isHighlighted
});
}));
};
Highlighter.defaultProps = {
tagName: 'em',
nonHighlightedTagName: 'span',
className: '',
separator: ', '
};
var cx$6 = createClassNames('Highlight');
var Highlight$1 = function Highlight(props) {
return React__default.createElement(Highlighter, _extends({}, props, {
highlightProperty: "_highlightResult",
cx: cx$6
}));
};
/**
* Renders any attribute from a 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} attribute - location of the highlighted attribute in the hit (the corresponding element can be either a string or an array of strings)
* @propType {object} hit - hit object containing the highlighted attribute
* @propType {string} [tagName='em'] - tag to be used for highlighted parts of the hit
* @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted
* @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings.
* @themeKey ais-Highlight - root of the component
* @themeKey ais-Highlight-highlighted - part of the text which is highlighted
* @themeKey ais-Highlight-nonHighlighted - part of the text that is not highlighted
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch-dom';
*
* const Hit = ({ hit }) => (
* <div>
* <Highlight attribute="name" hit={hit} />
* </div>
* );
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox defaultRefinement="Pho" />
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
*/
var Highlight$2 = connectHighlight(Highlight$1);
var cx$7 = createClassNames('Hits');
var DefaultHitComponent = function DefaultHitComponent(props) {
return React__default.createElement("div", {
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px',
wordBreak: 'break-all'
}
}, JSON.stringify(props).slice(0, 100), "...");
};
var Hits = function Hits(_ref) {
var hits = _ref.hits,
_ref$className = _ref.className,
className = _ref$className === void 0 ? '' : _ref$className,
_ref$hitComponent = _ref.hitComponent,
HitComponent = _ref$hitComponent === void 0 ? DefaultHitComponent : _ref$hitComponent;
return React__default.createElement("div", {
className: classnames(cx$7(''), className)
}, React__default.createElement("ul", {
className: cx$7('list')
}, hits.map(function (hit) {
return React__default.createElement("li", {
className: cx$7('item'),
key: hit.objectID
}, React__default.createElement(HitComponent, {
hit: hit
}));
})));
};
var HitPropTypes = propTypes.shape({
objectID: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired
});
/**
* 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 - the root div of the widget
* @themeKey ais-Hits-list - the list of results
* @themeKey ais-Hits-item - the hit list item
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, Hits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <Hits />
* </InstantSearch>
* );
*/
var Hits$1 = connectHits(Hits);
var Select =
/*#__PURE__*/
function (_Component) {
_inherits(Select, _Component);
function Select() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, Select);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Select)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "onChange", function (e) {
_this.props.onSelect(e.target.value);
});
return _this;
}
_createClass(Select, [{
key: "render",
value: function render() {
var _this$props = this.props,
cx = _this$props.cx,
items = _this$props.items,
selectedItem = _this$props.selectedItem;
return React__default.createElement("select", {
className: cx('select'),
value: selectedItem,
onChange: this.onChange
}, items.map(function (item) {
return React__default.createElement("option", {
className: cx('option'),
key: item.key === undefined ? item.value : item.key,
disabled: item.disabled,
value: item.value
}, item.label === undefined ? item.value : item.label);
}));
}
}]);
return Select;
}(React.Component);
_defineProperty(Select, "propTypes", {
cx: propTypes.func.isRequired,
onSelect: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
value: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired,
key: propTypes.oneOfType([propTypes.string, propTypes.number]),
label: propTypes.string,
disabled: propTypes.bool
})).isRequired,
selectedItem: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired
});
var cx$8 = createClassNames('HitsPerPage');
var HitsPerPage =
/*#__PURE__*/
function (_Component) {
_inherits(HitsPerPage, _Component);
function HitsPerPage() {
_classCallCheck(this, HitsPerPage);
return _possibleConstructorReturn(this, _getPrototypeOf(HitsPerPage).apply(this, arguments));
}
_createClass(HitsPerPage, [{
key: "render",
value: function render() {
var _this$props = this.props,
items = _this$props.items,
currentRefinement = _this$props.currentRefinement,
refine = _this$props.refine,
className = _this$props.className;
return React__default.createElement("div", {
className: classnames(cx$8(''), className)
}, React__default.createElement(Select, {
onSelect: refine,
selectedItem: currentRefinement,
items: items,
cx: cx$8
}));
}
}]);
return HitsPerPage;
}(React.Component);
_defineProperty(HitsPerPage, "propTypes", {
items: propTypes.arrayOf(propTypes.shape({
value: propTypes.number.isRequired,
label: propTypes.string
})).isRequired,
currentRefinement: propTypes.number.isRequired,
refine: propTypes.func.isRequired,
className: propTypes.string
});
_defineProperty(HitsPerPage, "defaultProps", {
className: ''
});
/**
* 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 - the root div of the widget
* @themeKey ais-HitsPerPage-select - the select
* @themeKey ais-HitsPerPage-option - the select option
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, HitsPerPage, Hits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <HitsPerPage
* defaultRefinement={5}
* items={[
* { value: 5, label: 'Show 5 hits' },
* { value: 10, label: 'Show 10 hits' },
* ]}
* />
* <Hits />
* </InstantSearch>
* );
*/
var HitsPerPage$1 = connectHitsPerPage(HitsPerPage);
var cx$9 = createClassNames('InfiniteHits');
var InfiniteHits =
/*#__PURE__*/
function (_Component) {
_inherits(InfiniteHits, _Component);
function InfiniteHits() {
_classCallCheck(this, InfiniteHits);
return _possibleConstructorReturn(this, _getPrototypeOf(InfiniteHits).apply(this, arguments));
}
_createClass(InfiniteHits, [{
key: "render",
value: function render() {
var _this$props = this.props,
HitComponent = _this$props.hitComponent,
hits = _this$props.hits,
showPrevious = _this$props.showPrevious,
hasPrevious = _this$props.hasPrevious,
hasMore = _this$props.hasMore,
refinePrevious = _this$props.refinePrevious,
refineNext = _this$props.refineNext,
translate = _this$props.translate,
className = _this$props.className;
return React__default.createElement("div", {
className: classnames(cx$9(''), className)
}, showPrevious && React__default.createElement("button", {
className: cx$9('loadPrevious', !hasPrevious && 'loadPrevious--disabled'),
onClick: function onClick() {
return refinePrevious();
},
disabled: !hasPrevious
}, translate('loadPrevious')), React__default.createElement("ul", {
className: cx$9('list')
}, hits.map(function (hit) {
return React__default.createElement("li", {
key: hit.objectID,
className: cx$9('item')
}, React__default.createElement(HitComponent, {
hit: hit
}));
})), React__default.createElement("button", {
className: cx$9('loadMore', !hasMore && 'loadMore--disabled'),
onClick: function onClick() {
return refineNext();
},
disabled: !hasMore
}, translate('loadMore')));
}
}]);
return InfiniteHits;
}(React.Component);
InfiniteHits.defaultProps = {
className: '',
showPrevious: false,
hitComponent: function hitComponent(hit) {
return React__default.createElement("div", {
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px',
wordBreak: 'break-all'
}
}, JSON.stringify(hit).slice(0, 100), "...");
}
};
var InfiniteHits$1 = translatable({
loadPrevious: 'Load previous',
loadMore: 'Load more'
})(InfiniteHits);
/**
* 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 ais-InfiniteHits - the root div of the widget
* @themeKey ais-InfiniteHits-list - the list of hits
* @themeKey ais-InfiniteHits-item - the hit list item
* @themeKey ais-InfiniteHits-loadMore - the button used to display more results
* @themeKey ais-InfiniteHits-loadMore--disabled - the disabled button used to display more results
* @translationKey loadMore - the label of load more button
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, InfiniteHits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <InfiniteHits />
* </InstantSearch>
* );
*/
var InfiniteHits$2 = connectInfiniteHits(InfiniteHits$1);
var cx$a = createClassNames('Menu');
var Menu =
/*#__PURE__*/
function (_Component) {
_inherits(Menu, _Component);
function Menu() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, Menu);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Menu)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) {
var createURL = _this.props.createURL;
var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, {
attribute: "label",
hit: item
}) : item.label;
return React__default.createElement(Link, {
className: cx$a('link'),
onClick: function onClick() {
return _this.selectItem(item, resetQuery);
},
href: createURL(item.value)
}, React__default.createElement("span", {
className: cx$a('label')
}, label), ' ', React__default.createElement("span", {
className: cx$a('count')
}, item.count));
});
_defineProperty(_assertThisInitialized(_this), "selectItem", function (item, resetQuery) {
resetQuery();
_this.props.refine(item.value);
});
return _this;
}
_createClass(Menu, [{
key: "render",
value: function render() {
var _this$props = this.props,
translate = _this$props.translate,
items = _this$props.items,
showMore = _this$props.showMore,
limit = _this$props.limit,
showMoreLimit = _this$props.showMoreLimit,
isFromSearch = _this$props.isFromSearch,
searchForItems = _this$props.searchForItems,
searchable = _this$props.searchable,
canRefine = _this$props.canRefine,
className = _this$props.className;
return React__default.createElement(List, {
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx$a,
translate: translate,
items: items,
showMore: showMore,
limit: limit,
showMoreLimit: showMoreLimit,
isFromSearch: isFromSearch,
searchForItems: searchForItems,
searchable: searchable,
canRefine: canRefine,
className: className
});
}
}]);
return Menu;
}(React.Component);
_defineProperty(Menu, "propTypes", {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
searchForItems: propTypes.func.isRequired,
searchable: propTypes.bool,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired,
count: propTypes.number.isRequired,
isRefined: propTypes.bool.isRequired
})),
isFromSearch: propTypes.bool.isRequired,
canRefine: propTypes.bool.isRequired,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func,
className: propTypes.string
});
_defineProperty(Menu, "defaultProps", {
className: ''
});
var Menu$1 = translatable({
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);
/**
* 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 `attribute` 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.
*
* If you are using the `searchable` prop, you'll also need to make the attribute searchable using
* the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values).
* @propType {string} attribute - 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} [limit=10] - the minimum number of diplayed items
* @propType {number} [showMoreLimit=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} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/).
* @themeKey ais-Menu - the root div of the widget
* @themeKey ais-Menu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @themeKey ais-Menu-list - the list of all menu items
* @themeKey ais-Menu-item - the menu list item
* @themeKey ais-Menu-item--selected - the selected menu list item
* @themeKey ais-Menu-link - the clickable menu element
* @themeKey ais-Menu-label - the label of each item
* @themeKey ais-Menu-count - the count of values for each item
* @themeKey ais-Menu-noResults - the div displayed when there are no results
* @themeKey ais-Menu-showMore - the button used to display more categories
* @themeKey ais-Menu-showMore--disabled - the disabled button used to display more categories
* @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 algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, Menu } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <Menu attribute="categories" />
* </InstantSearch>
* );
*/
var MenuWidget = function MenuWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(Menu$1, props));
};
var Menu$2 = connectMenu(MenuWidget);
var cx$b = createClassNames('MenuSelect');
var MenuSelect =
/*#__PURE__*/
function (_Component) {
_inherits(MenuSelect, _Component);
function MenuSelect() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, MenuSelect);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(MenuSelect)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "handleSelectChange", function (_ref) {
var value = _ref.target.value;
_this.props.refine(value === 'ais__see__all__option' ? '' : value);
});
return _this;
}
_createClass(MenuSelect, [{
key: "render",
value: function render() {
var _this$props = this.props,
items = _this$props.items,
canRefine = _this$props.canRefine,
translate = _this$props.translate,
className = _this$props.className;
return React__default.createElement("div", {
className: classnames(cx$b('', !canRefine && '-noRefinement'), className)
}, React__default.createElement("select", {
value: this.selectedValue,
onChange: this.handleSelectChange,
className: cx$b('select')
}, React__default.createElement("option", {
value: "ais__see__all__option",
className: cx$b('option')
}, translate('seeAllOption')), items.map(function (item) {
return React__default.createElement("option", {
key: item.value,
value: item.value,
className: cx$b('option')
}, item.label, " (", item.count, ")");
})));
}
}, {
key: "selectedValue",
get: function get() {
var _ref2 = find$2(this.props.items, function (item) {
return item.isRefined === true;
}) || {
value: 'ais__see__all__option'
},
value = _ref2.value;
return value;
}
}]);
return MenuSelect;
}(React.Component);
_defineProperty(MenuSelect, "propTypes", {
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired,
count: propTypes.oneOfType([propTypes.number.isRequired, propTypes.string.isRequired]),
isRefined: propTypes.bool.isRequired
})).isRequired,
canRefine: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
});
_defineProperty(MenuSelect, "defaultProps", {
className: ''
});
var MenuSelect$1 = translatable({
seeAllOption: 'See all'
})(MenuSelect);
/**
* The MenuSelect component displays a select that lets the user choose a single value for a specific attribute.
* @name MenuSelect
* @kind widget
* @requirements The attribute passed to the `attribute` 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} attribute - the name of the attribute in the record
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {number} [limit=10] - the minimum number of diplayed items
* @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-MenuSelect - the root div of the widget
* @themeKey ais-MenuSelect-noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-MenuSelect-select - the `<select>`
* @themeKey ais-MenuSelect-option - the select `<option>`
* @translationkey seeAllOption - The label of the option to select to remove the refinement
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, MenuSelect } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <MenuSelect attribute="categories" />
* </InstantSearch>
* );
*/
var MenuSelectWidget = function MenuSelectWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(MenuSelect$1, props));
};
var MenuSelect$2 = connectMenu(MenuSelectWidget);
var cx$c = createClassNames('NumericMenu');
var NumericMenu =
/*#__PURE__*/
function (_Component) {
_inherits(NumericMenu, _Component);
function NumericMenu() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, NumericMenu);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(NumericMenu)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "renderItem", function (item) {
var _this$props = _this.props,
refine = _this$props.refine,
translate = _this$props.translate;
return React__default.createElement("label", {
className: cx$c('label')
}, React__default.createElement("input", {
className: cx$c('radio'),
type: "radio",
checked: item.isRefined,
disabled: item.noRefinement,
onChange: function onChange() {
return refine(item.value);
}
}), React__default.createElement("span", {
className: cx$c('labelText')
}, item.value === '' ? translate('all') : item.label));
});
return _this;
}
_createClass(NumericMenu, [{
key: "render",
value: function render() {
var _this$props2 = this.props,
items = _this$props2.items,
canRefine = _this$props2.canRefine,
className = _this$props2.className;
return React__default.createElement(List, {
renderItem: this.renderItem,
showMore: false,
canRefine: canRefine,
cx: cx$c,
items: items.map(function (item) {
return _objectSpread({}, item, {
key: item.value
});
}),
className: className
});
}
}]);
return NumericMenu;
}(React.Component);
_defineProperty(NumericMenu, "propTypes", {
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.node.isRequired,
value: propTypes.string.isRequired,
isRefined: propTypes.bool.isRequired,
noRefinement: propTypes.bool.isRequired
})).isRequired,
canRefine: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
});
_defineProperty(NumericMenu, "defaultProps", {
className: ''
});
var NumericMenu$1 = translatable({
all: 'All'
})(NumericMenu);
/**
* NumericMenu is a widget used for selecting the range value of a numeric attribute.
* @name NumericMenu
* @kind widget
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @propType {string} attribute - 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-NumericMenu - the root div of the widget
* @themeKey ais-NumericMenu--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-NumericMenu-list - the list of all refinement items
* @themeKey ais-NumericMenu-item - the refinement list item
* @themeKey ais-NumericMenu-item--selected - the selected refinement list item
* @themeKey ais-NumericMenu-label - the label of each refinement item
* @themeKey ais-NumericMenu-radio - the radio input of each refinement item
* @themeKey ais-NumericMenu-labelText - the label text of each refinement item
* @translationkey all - The label of the largest range added automatically by react instantsearch
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, NumericMenu } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient
* indexName="instant_search"
* >
* <NumericMenu
* attribute="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>
* );
*/
var NumericMenuWidget = function NumericMenuWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(NumericMenu$1, props));
};
var NumericMenu$2 = connectNumericMenu(NumericMenuWidget);
var LinkList =
/*#__PURE__*/
function (_Component) {
_inherits(LinkList, _Component);
function LinkList() {
_classCallCheck(this, LinkList);
return _possibleConstructorReturn(this, _getPrototypeOf(LinkList).apply(this, arguments));
}
_createClass(LinkList, [{
key: "render",
value: function render() {
var _this$props = this.props,
cx = _this$props.cx,
createURL = _this$props.createURL,
items = _this$props.items,
onSelect = _this$props.onSelect,
canRefine = _this$props.canRefine;
return React__default.createElement("ul", {
className: cx('list', !canRefine && 'list--noRefinement')
}, items.map(function (item) {
return React__default.createElement("li", {
key: item.key === undefined ? item.value : item.key,
className: cx('item', item.selected && !item.disabled && 'item--selected', item.disabled && 'item--disabled', item.modifier)
}, item.disabled ? React__default.createElement("span", {
className: cx('link')
}, item.label === undefined ? item.value : item.label) : React__default.createElement(Link, {
className: cx('link', item.selected && 'link--selected'),
"aria-label": item.ariaLabel,
href: createURL(item.value),
onClick: function onClick() {
return onSelect(item.value);
}
}, item.label === undefined ? item.value : item.label));
}));
}
}]);
return LinkList;
}(React.Component);
_defineProperty(LinkList, "propTypes", {
cx: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
value: propTypes.oneOfType([propTypes.string, propTypes.number, propTypes.object]).isRequired,
key: propTypes.oneOfType([propTypes.string, propTypes.number]),
label: propTypes.node,
modifier: propTypes.string,
ariaLabel: propTypes.string,
disabled: propTypes.bool
})),
onSelect: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired
});
var cx$d = createClassNames('Pagination'); // Determines the size of the widget (the number of pages displayed - that the user can directly click on)
function calculateSize(padding, maxPages) {
return Math.min(2 * padding + 1, maxPages);
}
function calculatePaddingLeft(currentPage, padding, maxPages, size) {
if (currentPage <= padding) {
return currentPage;
}
if (currentPage >= maxPages - padding) {
return size - (maxPages - currentPage);
}
return padding + 1;
} // Retrieve the correct page range to populate the widget
function getPages(currentPage, maxPages, padding) {
var size = calculateSize(padding, maxPages); // If the widget size is equal to the max number of pages, return the entire page range
if (size === maxPages) return range({
start: 1,
end: maxPages + 1
});
var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size);
var paddingRight = size - paddingLeft;
var first = currentPage - paddingLeft;
var last = currentPage + paddingRight;
return range({
start: first + 1,
end: last + 1
});
}
var Pagination =
/*#__PURE__*/
function (_Component) {
_inherits(Pagination, _Component);
function Pagination() {
_classCallCheck(this, Pagination);
return _possibleConstructorReturn(this, _getPrototypeOf(Pagination).apply(this, arguments));
}
_createClass(Pagination, [{
key: "getItem",
value: function getItem(modifier, translationKey, value) {
var _this$props = this.props,
nbPages = _this$props.nbPages,
totalPages = _this$props.totalPages,
translate = _this$props.translate;
return {
key: "".concat(modifier, ".").concat(value),
modifier: modifier,
disabled: value < 1 || value >= Math.min(totalPages, nbPages),
label: translate(translationKey, value),
value: value,
ariaLabel: translate("aria".concat(capitalize(translationKey)), value)
};
}
}, {
key: "render",
value: function render() {
var _this$props2 = this.props,
ListComponent = _this$props2.listComponent,
nbPages = _this$props2.nbPages,
totalPages = _this$props2.totalPages,
currentRefinement = _this$props2.currentRefinement,
padding = _this$props2.padding,
showFirst = _this$props2.showFirst,
showPrevious = _this$props2.showPrevious,
showNext = _this$props2.showNext,
showLast = _this$props2.showLast,
refine = _this$props2.refine,
createURL = _this$props2.createURL,
canRefine = _this$props2.canRefine,
translate = _this$props2.translate,
className = _this$props2.className,
otherProps = _objectWithoutProperties(_this$props2, ["listComponent", "nbPages", "totalPages", "currentRefinement", "padding", "showFirst", "showPrevious", "showNext", "showLast", "refine", "createURL", "canRefine", "translate", "className"]);
var maxPages = Math.min(nbPages, totalPages);
var lastPage = maxPages;
var items = [];
if (showFirst) {
items.push({
key: 'first',
modifier: 'item--firstPage',
disabled: currentRefinement === 1,
label: translate('first'),
value: 1,
ariaLabel: translate('ariaFirst')
});
}
if (showPrevious) {
items.push({
key: 'previous',
modifier: 'item--previousPage',
disabled: currentRefinement === 1,
label: translate('previous'),
value: currentRefinement - 1,
ariaLabel: translate('ariaPrevious')
});
}
items = items.concat(getPages(currentRefinement, maxPages, padding).map(function (value) {
return {
key: value,
modifier: 'item--page',
label: translate('page', value),
value: value,
selected: value === currentRefinement,
ariaLabel: translate('ariaPage', value)
};
}));
if (showNext) {
items.push({
key: 'next',
modifier: 'item--nextPage',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('next'),
value: currentRefinement + 1,
ariaLabel: translate('ariaNext')
});
}
if (showLast) {
items.push({
key: 'last',
modifier: 'item--lastPage',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('last'),
value: lastPage,
ariaLabel: translate('ariaLast')
});
}
return React__default.createElement("div", {
className: classnames(cx$d('', !canRefine && '-noRefinement'), className)
}, React__default.createElement(ListComponent, _extends({}, otherProps, {
cx: cx$d,
items: items,
onSelect: refine,
createURL: createURL,
canRefine: canRefine
})));
}
}]);
return Pagination;
}(React.Component);
_defineProperty(Pagination, "propTypes", {
nbPages: propTypes.number.isRequired,
currentRefinement: propTypes.number.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired,
translate: propTypes.func.isRequired,
listComponent: propTypes.func,
showFirst: propTypes.bool,
showPrevious: propTypes.bool,
showNext: propTypes.bool,
showLast: propTypes.bool,
padding: propTypes.number,
totalPages: propTypes.number,
className: propTypes.string
});
_defineProperty(Pagination, "defaultProps", {
listComponent: LinkList,
showFirst: true,
showPrevious: true,
showNext: true,
showLast: false,
padding: 3,
totalPages: Infinity,
className: ''
});
var Pagination$1 = translatable({
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 ".concat(currentRefinement.toString());
}
})(Pagination);
/**
* 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} [padding=3] - How many page links to display around the current page.
* @propType {number} [totalPages=Infinity] - Maximum number of pages to display.
* @themeKey ais-Pagination - the root div of the widget
* @themeKey ais-Pagination--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-Pagination-list - the list of all pagination items
* @themeKey ais-Pagination-list--noRefinement - the list of all pagination items when there is no refinement
* @themeKey ais-Pagination-item - the pagination list item
* @themeKey ais-Pagination-item--firstPage - the "first" pagination list item
* @themeKey ais-Pagination-item--lastPage - the "last" pagination list item
* @themeKey ais-Pagination-item--previousPage - the "previous" pagination list item
* @themeKey ais-Pagination-item--nextPage - the "next" pagination list item
* @themeKey ais-Pagination-item--page - the "page" pagination list item
* @themeKey ais-Pagination-item--selected - the selected pagination list item
* @themeKey ais-Pagination-item--disabled - the disabled pagination list item
* @themeKey ais-Pagination-link - the pagination clickable element
* @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 algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, Pagination } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <Pagination />
* </InstantSearch>
* );
*/
var PaginationWidget = function PaginationWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(Pagination$1, props));
};
var Pagination$2 = connectPagination(PaginationWidget);
var cx$e = createClassNames('PoweredBy');
/* eslint-disable max-len */
var AlgoliaLogo = function AlgoliaLogo() {
return React__default.createElement("svg", {
xmlns: "http://www.w3.org/2000/svg",
baseProfile: "basic",
viewBox: "0 0 1366 362",
width: "100",
height: "27",
className: cx$e('logo')
}, React__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)"
}, React__default.createElement("stop", {
offset: "0",
stopColor: "#00AEFF"
}), React__default.createElement("stop", {
offset: "1",
stopColor: "#3369E7"
})), React__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)"
}), React__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"
}), React__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 =
/*#__PURE__*/
function (_Component) {
_inherits(PoweredBy, _Component);
function PoweredBy() {
_classCallCheck(this, PoweredBy);
return _possibleConstructorReturn(this, _getPrototypeOf(PoweredBy).apply(this, arguments));
}
_createClass(PoweredBy, [{
key: "render",
value: function render() {
var _this$props = this.props,
url = _this$props.url,
translate = _this$props.translate,
className = _this$props.className;
return React__default.createElement("div", {
className: classnames(cx$e(''), className)
}, React__default.createElement("span", {
className: cx$e('text')
}, translate('searchBy')), ' ', React__default.createElement("a", {
href: url,
target: "_blank",
className: cx$e('link'),
"aria-label": "Algolia",
rel: "noopener noreferrer"
}, React__default.createElement(AlgoliaLogo, null)));
}
}]);
return PoweredBy;
}(React.Component);
_defineProperty(PoweredBy, "propTypes", {
url: propTypes.string.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
});
var PoweredBy$1 = translatable({
searchBy: 'Search by'
})(PoweredBy);
/**
* 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 - the root div of the widget
* @themeKey ais-PoweredBy-text - the text of the widget
* @themeKey ais-PoweredBy-link - the link of the logo
* @themeKey ais-PoweredBy-logo - the logo of the widget
* @translationKey searchBy - Label value for the powered by
* @example
* import React from 'react';
* import { InstantSearch, PoweredBy } from 'react-instantsearch-dom';
* import algoliasearch from 'algoliasearch/lite';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <PoweredBy />
* </InstantSearch>
* );
*/
var PoweredBy$2 = connectPoweredBy(PoweredBy$1);
var cx$f = createClassNames('RangeInput');
var RawRangeInput =
/*#__PURE__*/
function (_Component) {
_inherits(RawRangeInput, _Component);
function RawRangeInput(props) {
var _this;
_classCallCheck(this, RawRangeInput);
_this = _possibleConstructorReturn(this, _getPrototypeOf(RawRangeInput).call(this, props));
_defineProperty(_assertThisInitialized(_this), "onSubmit", function (e) {
e.preventDefault();
_this.props.refine({
min: _this.state.from,
max: _this.state.to
});
});
_this.state = _this.normalizeStateForRendering(props);
return _this;
}
_createClass(RawRangeInput, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (this.props.canRefine && (prevProps.currentRefinement.min !== this.props.currentRefinement.min || prevProps.currentRefinement.max !== this.props.currentRefinement.max)) {
this.setState(this.normalizeStateForRendering(this.props));
}
}
}, {
key: "normalizeStateForRendering",
value: function normalizeStateForRendering(props) {
var canRefine = props.canRefine,
rangeMin = props.min,
rangeMax = props.max;
var _props$currentRefinem = props.currentRefinement,
valueMin = _props$currentRefinem.min,
valueMax = _props$currentRefinem.max;
return {
from: canRefine && valueMin !== undefined && valueMin !== rangeMin ? valueMin : '',
to: canRefine && valueMax !== undefined && valueMax !== rangeMax ? valueMax : ''
};
}
}, {
key: "normalizeRangeForRendering",
value: function normalizeRangeForRendering(_ref) {
var canRefine = _ref.canRefine,
min = _ref.min,
max = _ref.max;
var hasMin = min !== undefined;
var hasMax = max !== undefined;
return {
min: canRefine && hasMin && hasMax ? min : '',
max: canRefine && hasMin && hasMax ? max : ''
};
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$state = this.state,
from = _this$state.from,
to = _this$state.to;
var _this$props = this.props,
precision = _this$props.precision,
translate = _this$props.translate,
canRefine = _this$props.canRefine,
className = _this$props.className;
var _this$normalizeRangeF = this.normalizeRangeForRendering(this.props),
min = _this$normalizeRangeF.min,
max = _this$normalizeRangeF.max;
var step = 1 / Math.pow(10, precision);
return React__default.createElement("div", {
className: classnames(cx$f('', !canRefine && '-noRefinement'), className)
}, React__default.createElement("form", {
className: cx$f('form'),
onSubmit: this.onSubmit
}, React__default.createElement("input", {
className: cx$f('input', 'input--min'),
type: "number",
min: min,
max: max,
value: from,
step: step,
placeholder: min,
disabled: !canRefine,
onChange: function onChange(e) {
return _this2.setState({
from: e.currentTarget.value
});
}
}), React__default.createElement("span", {
className: cx$f('separator')
}, translate('separator')), React__default.createElement("input", {
className: cx$f('input', 'input--max'),
type: "number",
min: min,
max: max,
value: to,
step: step,
placeholder: max,
disabled: !canRefine,
onChange: function onChange(e) {
return _this2.setState({
to: e.currentTarget.value
});
}
}), React__default.createElement("button", {
className: cx$f('submit'),
type: "submit"
}, translate('submit'))));
}
}]);
return RawRangeInput;
}(React.Component);
_defineProperty(RawRangeInput, "propTypes", {
canRefine: propTypes.bool.isRequired,
precision: propTypes.number.isRequired,
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
min: propTypes.number,
max: propTypes.number,
currentRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
className: propTypes.string
});
_defineProperty(RawRangeInput, "defaultProps", {
currentRefinement: {},
className: ''
});
var RangeInput = translatable({
submit: 'ok',
separator: 'to'
})(RawRangeInput);
/**
* 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 `attribute` 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.
* The values inside the attribute must be JavaScript numbers (not strings).
* @propType {string} attribute - 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.
* @propType {number} [precision=0] - Number of digits after decimal point to use.
* @themeKey ais-RangeInput - the root div of the widget
* @themeKey ais-RangeInput-form - the wrapping form
* @themeKey ais-RangeInput-label - the label wrapping inputs
* @themeKey ais-RangeInput-input - the input (number)
* @themeKey ais-RangeInput-input--min - the minimum input
* @themeKey ais-RangeInput-input--max - the maximum input
* @themeKey ais-RangeInput-separator - the separator word used between the two inputs
* @themeKey ais-RangeInput-button - the submit button
* @translationKey submit - Label value for the submit button
* @translationKey separator - Label value for the input separator
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, RangeInput } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <RangeInput attribute="price" />
* </InstantSearch>
* );
*/
var RangeInputWidget = function RangeInputWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(RangeInput, props));
};
var RangeInput$1 = connectRange(RangeInputWidget);
/**
* 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. ⚠️ This example only works with the version 2.x of Rheostat.
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Rheostat from 'rheostat';
import { connectRange } from 'react-instantsearch-dom';
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 } };
componentDidUpdate(prevProps) {
if (
this.props.canRefine &&
(prevProps.currentRefinement.min !== this.props.currentRefinement.min ||
prevProps.currentRefinement.max !== this.props.currentRefinement.max)
) {
this.setState({
currentValues: {
min: this.props.currentRefinement.min,
max: this.props.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
className="ais-RangeSlider"
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);
*/
var RangeSlider = (function () {
return React__default.createElement("div", null, "We do not provide any Slider, see the documentation to learn how to connect one easily:", React__default.createElement("a", {
target: "_blank",
rel: "noopener noreferrer",
href: "https://www.algolia.com/doc/api-reference/widgets/range-slider/react/"
}, "https://www.algolia.com/doc/api-reference/widgets/range-slider/react/"));
});
var cx$g = createClassNames('RatingMenu');
var RatingMenu =
/*#__PURE__*/
function (_Component) {
_inherits(RatingMenu, _Component);
function RatingMenu() {
_classCallCheck(this, RatingMenu);
return _possibleConstructorReturn(this, _getPrototypeOf(RatingMenu).apply(this, arguments));
}
_createClass(RatingMenu, [{
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,
lowerBound = _ref.lowerBound,
count = _ref.count,
translate = _ref.translate,
createURL = _ref.createURL,
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 = [];
var rating = 0;
for (var icon = 0; icon < max; icon++) {
if (icon < lowerBound) {
rating++;
}
icons.push([React__default.createElement("svg", {
key: icon,
className: cx$g('starIcon', icon >= lowerBound ? 'starIcon--empty' : 'starIcon--full'),
"aria-hidden": "true",
width: "24",
height: "24"
}, React__default.createElement("use", {
xlinkHref: "#".concat(cx$g(icon >= lowerBound ? 'starEmptySymbol' : 'starSymbol'))
})), ' ']);
} // The last item of the list (the default item), should not
// be clickable if it is selected.
var isLastAndSelect = isLastSelectableItem && selected;
var onClickHandler = disabled || isLastAndSelect ? {} : {
href: createURL({
min: lowerBound,
max: max
}),
onClick: this.onClick.bind(this, lowerBound, max)
};
return React__default.createElement("li", {
key: lowerBound,
className: cx$g('item', selected && 'item--selected', disabled && 'item--disabled')
}, React__default.createElement("a", _extends({
className: cx$g('link'),
"aria-label": "".concat(rating).concat(translate('ratingLabel'))
}, onClickHandler), icons, React__default.createElement("span", {
className: cx$g('label'),
"aria-hidden": "true"
}, translate('ratingLabel')), ' ', React__default.createElement("span", {
className: cx$g('count')
}, count)));
}
}, {
key: "render",
value: function render() {
var _this = this;
var _this$props = this.props,
min = _this$props.min,
max = _this$props.max,
translate = _this$props.translate,
count = _this$props.count,
createURL = _this$props.createURL,
canRefine = _this$props.canRefine,
className = _this$props.className; // min & max are always set when there is a results, otherwise it means
// that we don't want to render anything since we don't have any values.
var limitMin = min !== undefined && min >= 0 ? min : 1;
var limitMax = max !== undefined && max >= 0 ? max : 0;
var inclusiveLength = limitMax - limitMin + 1;
var values = count.map(function (item) {
return _objectSpread({}, item, {
value: parseFloat(item.value)
});
}).filter(function (item) {
return item.value >= limitMin && item.value <= limitMax;
});
var items = range({
start: 0,
end: Math.max(inclusiveLength, 0)
}).map(function (index) {
var element = find$2(values, function (item) {
return item.value === limitMax - index;
});
var placeholder = {
value: limitMax - index,
count: 0,
total: 0
};
return element || placeholder;
}).reduce(function (acc, item, index) {
return acc.concat(_objectSpread({}, item, {
total: index === 0 ? item.count : acc[index - 1].total + item.count
}));
}, []).map(function (item, index, arr) {
return _this.buildItem({
lowerBound: item.value,
count: item.total,
isLastSelectableItem: arr.length - 1 === index,
max: limitMax,
translate: translate,
createURL: createURL
});
});
return React__default.createElement("div", {
className: classnames(cx$g('', !canRefine && '-noRefinement'), className)
}, React__default.createElement("svg", {
xmlns: "http://www.w3.org/2000/svg",
style: {
display: 'none'
}
}, React__default.createElement("symbol", {
id: cx$g('starSymbol'),
viewBox: "0 0 24 24"
}, React__default.createElement("path", {
d: "M12 .288l2.833 8.718h9.167l-7.417 5.389 2.833 8.718-7.416-5.388-7.417 5.388 2.833-8.718-7.416-5.389h9.167z"
})), React__default.createElement("symbol", {
id: cx$g('starEmptySymbol'),
viewBox: "0 0 24 24"
}, React__default.createElement("path", {
d: "M12 6.76l1.379 4.246h4.465l-3.612 2.625 1.379 4.246-3.611-2.625-3.612 2.625 1.379-4.246-3.612-2.625h4.465l1.38-4.246zm0-6.472l-2.833 8.718h-9.167l7.416 5.389-2.833 8.718 7.417-5.388 7.416 5.388-2.833-8.718 7.417-5.389h-9.167l-2.833-8.718z"
}))), React__default.createElement("ul", {
className: cx$g('list', !canRefine && 'list--noRefinement')
}, items));
}
}]);
return RatingMenu;
}(React.Component);
_defineProperty(RatingMenu, "propTypes", {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
min: propTypes.number,
max: propTypes.number,
currentRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
count: propTypes.arrayOf(propTypes.shape({
value: propTypes.string,
count: propTypes.number
})),
canRefine: propTypes.bool.isRequired,
className: propTypes.string
});
_defineProperty(RatingMenu, "defaultProps", {
className: ''
});
var RatingMenu$1 = translatable({
ratingLabel: ' & Up'
})(RatingMenu);
/**
* RatingMenu lets the user refine search results by clicking on stars.
*
* The stars are based on the selected `attribute`.
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @name RatingMenu
* @kind widget
* @requirements The attribute passed to the `attribute` 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.
* The values inside the attribute must be JavaScript numbers (not strings).
* @propType {string} attribute - 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-RatingMenu - the root div of the widget
* @themeKey ais-RatingMenu--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-RatingMenu-list - the list of ratings
* @themeKey ais-RatingMenu-list--noRefinement - the list of ratings when there is no refinement
* @themeKey ais-RatingMenu-item - the rating list item
* @themeKey ais-RatingMenu-item--selected - the selected rating list item
* @themeKey ais-RatingMenu-item--disabled - the disabled rating list item
* @themeKey ais-RatingMenu-link - the rating clickable item
* @themeKey ais-RatingMenu-starIcon - the star icon
* @themeKey ais-RatingMenu-starIcon--full - the filled star icon
* @themeKey ais-RatingMenu-starIcon--empty - the empty star icon
* @themeKey ais-RatingMenu-label - the label used after the stars
* @themeKey ais-RatingMenu-count - the count of ratings for a specific item
* @translationKey ratingLabel - Label value for the rating link
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, RatingMenu } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <RatingMenu attribute="rating" />
* </InstantSearch>
* );
*/
var RatingMenuWidget = function RatingMenuWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(RatingMenu$1, props));
};
var RatingMenu$2 = connectRange(RatingMenuWidget);
var cx$h = createClassNames('RefinementList');
var RefinementList$1 =
/*#__PURE__*/
function (_Component) {
_inherits(RefinementList, _Component);
function RefinementList() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, RefinementList);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(RefinementList)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "state", {
query: ''
});
_defineProperty(_assertThisInitialized(_this), "selectItem", function (item, resetQuery) {
resetQuery();
_this.props.refine(item.value);
});
_defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) {
var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, {
attribute: "label",
hit: item
}) : item.label;
return React__default.createElement("label", {
className: cx$h('label')
}, React__default.createElement("input", {
className: cx$h('checkbox'),
type: "checkbox",
checked: item.isRefined,
onChange: function onChange() {
return _this.selectItem(item, resetQuery);
}
}), React__default.createElement("span", {
className: cx$h('labelText')
}, label), ' ', React__default.createElement("span", {
className: cx$h('count')
}, item.count.toLocaleString()));
});
return _this;
}
_createClass(RefinementList, [{
key: "render",
value: function render() {
var _this$props = this.props,
translate = _this$props.translate,
items = _this$props.items,
showMore = _this$props.showMore,
limit = _this$props.limit,
showMoreLimit = _this$props.showMoreLimit,
isFromSearch = _this$props.isFromSearch,
searchForItems = _this$props.searchForItems,
searchable = _this$props.searchable,
canRefine = _this$props.canRefine,
className = _this$props.className;
return React__default.createElement(List, {
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx$h,
translate: translate,
items: items,
showMore: showMore,
limit: limit,
showMoreLimit: showMoreLimit,
isFromSearch: isFromSearch,
searchForItems: searchForItems,
searchable: searchable,
canRefine: canRefine,
className: className,
query: this.state.query
});
}
}]);
return RefinementList;
}(React.Component);
_defineProperty(RefinementList$1, "propTypes", {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
searchForItems: propTypes.func.isRequired,
searchable: propTypes.bool,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.arrayOf(propTypes.string).isRequired,
count: propTypes.number.isRequired,
isRefined: propTypes.bool.isRequired
})),
isFromSearch: propTypes.bool.isRequired,
canRefine: propTypes.bool.isRequired,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func,
className: propTypes.string
});
_defineProperty(RefinementList$1, "defaultProps", {
className: ''
});
var RefinementList$2 = translatable({
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$1);
/**
* The RefinementList component displays a list that let the end user choose multiple values for a specific facet.
* @name RefinementList
* @kind widget
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/).
* @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} [limit=10] - the minimum number of displayed items
* @propType {number} [showMoreLimit=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 - the root div of the widget
* @themeKey ais-RefinementList--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-RefinementList-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @themeKey ais-RefinementList-list - the list of refinement items
* @themeKey ais-RefinementList-item - the refinement list item
* @themeKey ais-RefinementList-item--selected - the refinement selected list item
* @themeKey ais-RefinementList-label - the label of each refinement item
* @themeKey ais-RefinementList-checkbox - the checkbox input of each refinement item
* @themeKey ais-RefinementList-labelText - the label text of each refinement item
* @themeKey ais-RefinementList-count - the count of values for each item
* @themeKey ais-RefinementList-noResults - the div displayed when there are no results
* @themeKey ais-RefinementList-showMore - the button used to display more categories
* @themeKey ais-RefinementList-showMore--disabled - the disabled button used to display more categories
* @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 `attribute` 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.
*
* If you are using the `searchable` prop, you'll also need to make the attribute searchable using
* the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values).
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, RefinementList } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <RefinementList attribute="brand" />
* </InstantSearch>
* );
*/
var RefinementListWidget = function RefinementListWidget(props) {
return React__default.createElement(PanelWrapper, props, React__default.createElement(RefinementList$2, props));
};
var RefinementList$3 = connectRefinementList(RefinementListWidget);
var cx$i = createClassNames('ScrollTo');
var ScrollTo =
/*#__PURE__*/
function (_Component) {
_inherits(ScrollTo, _Component);
function ScrollTo() {
_classCallCheck(this, ScrollTo);
return _possibleConstructorReturn(this, _getPrototypeOf(ScrollTo).apply(this, arguments));
}
_createClass(ScrollTo, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
var _this$props = this.props,
value = _this$props.value,
hasNotChanged = _this$props.hasNotChanged;
if (value !== prevProps.value && hasNotChanged) {
this.el.scrollIntoView();
}
}
}, {
key: "render",
value: function render() {
var _this = this;
return React__default.createElement("div", {
ref: function ref(_ref) {
return _this.el = _ref;
},
className: cx$i('')
}, this.props.children);
}
}]);
return ScrollTo;
}(React.Component);
_defineProperty(ScrollTo, "propTypes", {
value: propTypes.any,
children: propTypes.node,
hasNotChanged: propTypes.bool
});
/**
* The ScrollTo component will make 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.
* @themeKey ais-ScrollTo - the root div of the widget
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, ScrollTo, Hits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <ScrollTo>
* <Hits />
* </ScrollTo>
* </InstantSearch>
* );
*/
var ScrollTo$1 = connectScrollTo(ScrollTo);
/**
* 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 from the search input itself.
* @propType {node} [submit] - Change the apparence of the default submit button (magnifying glass).
* @propType {node} [reset] - Change the apparence of the default reset button (cross).
* @propType {node} [loadingIndicator] - Change the apparence of the default loading indicator (spinning circle).
* @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted.
* @propType {boolean} [showLoadingIndicator=false] - Display that the search is loading. This only happens after a certain amount of time to avoid a blinking effect. This timer can be configured with `stalledSearchDelay` props on <InstantSearch>. By default, the value is 200ms.
* @themeKey ais-SearchBox - the root div of the widget
* @themeKey ais-SearchBox-form - the wrapping form
* @themeKey ais-SearchBox-input - the search input
* @themeKey ais-SearchBox-submit - the submit button
* @themeKey ais-SearchBox-submitIcon - the default magnifier icon used with the search input
* @themeKey ais-SearchBox-reset - the reset button used to clear the content of the input
* @themeKey ais-SearchBox-resetIcon - the default reset icon used inside the reset button
* @themeKey ais-SearchBox-loadingIndicator - the loading indicator container
* @themeKey ais-SearchBox-loadingIcon - the default loading icon
* @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 algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox />
* </InstantSearch>
* );
*/
var SearchBox$2 = connectSearchBox(SearchBox$1);
var cx$j = createClassNames('Snippet');
var Snippet = function Snippet(props) {
return React__default.createElement(Highlighter, _extends({}, props, {
highlightProperty: "_snippetResult",
cx: cx$j
}));
};
/**
* 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
* @requirements To use this widget, the attribute name passed to the `attribute` prop must be
* present in "Attributes to snippet" on the Algolia dashboard or configured as `attributesToSnippet`
* via a set settings call to the Algolia API.
* @propType {string} attribute - location of the highlighted snippet attribute in the hit (the corresponding element can be either a string or an array of strings)
* @propType {object} hit - hit object containing the highlighted snippet attribute
* @propType {string} [tagName='em'] - tag to be used for highlighted parts of the attribute
* @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted
* @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings.
* @themeKey ais-Snippet - the root span of the widget
* @themeKey ais-Snippet-highlighted - the highlighted text
* @themeKey ais-Snippet-nonHighlighted - the normal text
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox, Hits, Snippet } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const Hit = ({ hit }) => (
* <div>
* <Snippet attribute="description" hit={hit} />
* </div>
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox defaultRefinement="adjustable" />
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
*/
var Snippet$1 = connectHighlight(Snippet);
var cx$k = createClassNames('SortBy');
var SortBy =
/*#__PURE__*/
function (_Component) {
_inherits(SortBy, _Component);
function SortBy() {
_classCallCheck(this, SortBy);
return _possibleConstructorReturn(this, _getPrototypeOf(SortBy).apply(this, arguments));
}
_createClass(SortBy, [{
key: "render",
value: function render() {
var _this$props = this.props,
items = _this$props.items,
currentRefinement = _this$props.currentRefinement,
refine = _this$props.refine,
className = _this$props.className;
return React__default.createElement("div", {
className: classnames(cx$k(''), className)
}, React__default.createElement(Select, {
cx: cx$k,
items: items,
selectedItem: currentRefinement,
onSelect: refine
}));
}
}]);
return SortBy;
}(React.Component);
_defineProperty(SortBy, "propTypes", {
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.string.isRequired
})).isRequired,
currentRefinement: propTypes.string.isRequired,
refine: propTypes.func.isRequired,
className: propTypes.string
});
_defineProperty(SortBy, "defaultProps", {
className: ''
});
/**
* 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 - the root div of the widget
* @themeKey ais-SortBy-select - the select
* @themeKey ais-SortBy-option - the select option
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SortBy } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SortBy
* defaultRefinement="instant_search"
* items={[
* { value: 'instant_search', label: 'Featured' },
* { value: 'instant_search_price_asc', label: 'Price asc.' },
* { value: 'instant_search_price_desc', label: 'Price desc.' },
* ]}
* />
* </InstantSearch>
* );
*/
var SortBy$1 = connectSortBy(SortBy);
var cx$l = createClassNames('Stats');
var Stats =
/*#__PURE__*/
function (_Component) {
_inherits(Stats, _Component);
function Stats() {
_classCallCheck(this, Stats);
return _possibleConstructorReturn(this, _getPrototypeOf(Stats).apply(this, arguments));
}
_createClass(Stats, [{
key: "render",
value: function render() {
var _this$props = this.props,
translate = _this$props.translate,
nbHits = _this$props.nbHits,
processingTimeMS = _this$props.processingTimeMS,
className = _this$props.className;
return React__default.createElement("div", {
className: classnames(cx$l(''), className)
}, React__default.createElement("span", {
className: cx$l('text')
}, translate('stats', nbHits, processingTimeMS)));
}
}]);
return Stats;
}(React.Component);
_defineProperty(Stats, "propTypes", {
translate: propTypes.func.isRequired,
nbHits: propTypes.number.isRequired,
processingTimeMS: propTypes.number.isRequired,
className: propTypes.string
});
_defineProperty(Stats, "defaultProps", {
className: ''
});
var Stats$1 = translatable({
stats: function stats(n, ms) {
return "".concat(n.toLocaleString(), " results found in ").concat(ms.toLocaleString(), "ms");
}
})(Stats);
/**
* 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 - the root div of the widget
* @themeKey ais-Stats-text - the text of the widget - the count of items for each item
* @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 { InstantSearch, Stats, Hits } from 'react-instantsearch-dom';
* import algoliasearch from 'algoliasearch/lite';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <Stats />
* <Hits />
* </InstantSearch>
* );
*/
var Stats$2 = connectStats(Stats$1);
var cx$m = createClassNames('ToggleRefinement');
var ToggleRefinement = function ToggleRefinement(_ref) {
var currentRefinement = _ref.currentRefinement,
label = _ref.label,
canRefine = _ref.canRefine,
refine = _ref.refine,
className = _ref.className;
return React__default.createElement("div", {
className: classnames(cx$m('', !canRefine && '-noRefinement'), className)
}, React__default.createElement("label", {
className: cx$m('label')
}, React__default.createElement("input", {
className: cx$m('checkbox'),
type: "checkbox",
checked: currentRefinement,
onChange: function onChange(event) {
return refine(event.target.checked);
}
}), React__default.createElement("span", {
className: cx$m('labelText')
}, label)));
};
ToggleRefinement.defaultProps = {
className: ''
};
/**
* The ToggleRefinement provides an on/off filtering feature based on an attribute value.
* @name ToggleRefinement
* @kind widget
* @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} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {any} value - Value of the refinement to apply on `attribute` when checked.
* @propType {boolean} [defaultRefinement=false] - Default state of the widget. Should the toggle be checked by default?
* @themeKey ais-ToggleRefinement - the root div of the widget
* @themeKey ais-ToggleRefinement-list - the list of toggles
* @themeKey ais-ToggleRefinement-item - the toggle list item
* @themeKey ais-ToggleRefinement-label - the label of each toggle item
* @themeKey ais-ToggleRefinement-checkbox - the checkbox input of each toggle item
* @themeKey ais-ToggleRefinement-labelText - the label text of each toggle item
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, ToggleRefinement } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <ToggleRefinement
* attribute="free_shipping"
* label="Free Shipping"
* value={true}
* />
* </InstantSearch>
* );
*/
var ToggleRefinement$1 = connectToggleRefinement(ToggleRefinement);
var ANONYMOUS_TOKEN_COOKIE_KEY = '_ALGOLIA';
function getCookie(name) {
var prefix = "".concat(name, "=");
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1);
}
if (cookie.indexOf(prefix) === 0) {
return cookie.substring(prefix.length, cookie.length);
}
}
return undefined;
}
function getInsightsAnonymousUserToken() {
return getCookie(ANONYMOUS_TOKEN_COOKIE_KEY);
}
exports.Breadcrumb = Breadcrumb$2;
exports.ClearRefinements = ClearRefinements$2;
exports.Configure = Configure;
exports.CurrentRefinements = CurrentRefinements$2;
exports.ExperimentalConfigureRelatedItems = ConfigureRelatedItems$1;
exports.HierarchicalMenu = HierarchicalMenu$2;
exports.Highlight = Highlight$2;
exports.Hits = Hits$1;
exports.HitsPerPage = HitsPerPage$1;
exports.Index = IndexWrapper;
exports.InfiniteHits = InfiniteHits$2;
exports.InstantSearch = InstantSearch;
exports.Menu = Menu$2;
exports.MenuSelect = MenuSelect$2;
exports.NumericMenu = NumericMenu$2;
exports.Pagination = Pagination$2;
exports.Panel = Panel;
exports.PoweredBy = PoweredBy$2;
exports.RangeInput = RangeInput$1;
exports.RangeSlider = RangeSlider;
exports.RatingMenu = RatingMenu$2;
exports.RefinementList = RefinementList$3;
exports.ScrollTo = ScrollTo$1;
exports.SearchBox = SearchBox$2;
exports.Snippet = Snippet$1;
exports.SortBy = SortBy$1;
exports.Stats = Stats$2;
exports.ToggleRefinement = ToggleRefinement$1;
exports.getInsightsAnonymousUserToken = getInsightsAnonymousUserToken;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=Dom.js.map
|
ajax/libs/primereact/6.5.0-rc.2/tabview/tabview.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, UniqueComponentId, classNames, ObjectUtils } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 propTypes = {exports: {}};
/**
* 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$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
/**
* 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 = ReactPropTypesSecret_1;
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'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'
);
err.name = 'Invariant Violation';
throw err;
} 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,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/**
* 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
propTypes.exports = factoryWithThrowingShims();
}
var PropTypes = propTypes.exports;
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var TabPanel = /*#__PURE__*/function (_Component) {
_inherits(TabPanel, _Component);
var _super = _createSuper(TabPanel);
function TabPanel() {
_classCallCheck(this, TabPanel);
return _super.apply(this, arguments);
}
return TabPanel;
}(Component);
_defineProperty(TabPanel, "defaultProps", {
header: null,
headerTemplate: null,
leftIcon: null,
rightIcon: null,
disabled: false,
headerStyle: null,
headerClassName: null,
contentStyle: null,
contentClassName: null
});
_defineProperty(TabPanel, "propTypes", {
header: PropTypes.any,
headerTemplate: PropTypes.any,
leftIcon: PropTypes.string,
rightIcon: PropTypes.string,
disabled: PropTypes.bool,
headerStyle: PropTypes.object,
headerClassName: PropTypes.string,
contentStyle: PropTypes.object,
contentClassName: PropTypes.string
});
var TabView = /*#__PURE__*/function (_Component2) {
_inherits(TabView, _Component2);
var _super2 = _createSuper(TabView);
function TabView(props) {
var _this;
_classCallCheck(this, TabView);
_this = _super2.call(this, props);
var state = {
id: props.id
};
if (!_this.props.onTabChange) {
state = _objectSpread(_objectSpread({}, state), {}, {
activeIndex: props.activeIndex
});
}
_this.state = state;
return _this;
}
_createClass(TabView, [{
key: "getActiveIndex",
value: function getActiveIndex() {
return this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex;
}
}, {
key: "isSelected",
value: function isSelected(index) {
return index === this.getActiveIndex();
}
}, {
key: "onTabHeaderClick",
value: function onTabHeaderClick(event, tab, index) {
if (!tab.props.disabled) {
if (this.props.onTabChange) {
this.props.onTabChange({
originalEvent: event,
index: index
});
} else {
this.setState({
activeIndex: index
});
}
}
event.preventDefault();
}
}, {
key: "updateInkBar",
value: function updateInkBar() {
var activeIndex = this.getActiveIndex();
var tabHeader = this["tab_".concat(activeIndex)];
this.inkbar.style.width = DomHandler.getWidth(tabHeader) + 'px';
this.inkbar.style.left = DomHandler.getOffset(tabHeader).left - DomHandler.getOffset(this.nav).left + 'px';
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (!this.state.id) {
this.setState({
id: UniqueComponentId()
});
}
this.updateInkBar();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
this.updateInkBar();
}
}, {
key: "renderTabHeader",
value: function renderTabHeader(tab, index) {
var _this2 = this;
var selected = this.isSelected(index);
var className = classNames('p-unselectable-text', {
'p-tabview-selected p-highlight': selected,
'p-disabled': tab.props.disabled
}, tab.props.headerClassName);
var id = this.state.id + '_header_' + index;
var ariaControls = this.state.id + '_content_' + index;
var tabIndex = tab.props.disabled ? null : 0;
var leftIconElement = tab.props.leftIcon && /*#__PURE__*/React.createElement("i", {
className: tab.props.leftIcon
});
var titleElement = /*#__PURE__*/React.createElement("span", {
className: "p-tabview-title"
}, tab.props.header);
var rightIconElement = tab.props.rightIcon && /*#__PURE__*/React.createElement("i", {
className: tab.props.rightIcon
});
var content =
/*#__PURE__*/
/* eslint-disable */
React.createElement("a", {
role: "tab",
className: "p-tabview-nav-link",
onClick: function onClick(event) {
return _this2.onTabHeaderClick(event, tab, index);
},
id: id,
"aria-controls": ariaControls,
"aria-selected": selected,
tabIndex: tabIndex
}, leftIconElement, titleElement, rightIconElement, /*#__PURE__*/React.createElement(Ripple, null))
/* eslint-enable */
;
if (tab.props.headerTemplate) {
var defaultContentOptions = {
className: 'p-tabview-nav-link',
titleClassName: 'p-tabview-title',
onClick: function onClick(event) {
return _this2.onTabHeaderClick(event, tab, index);
},
leftIconElement: leftIconElement,
titleElement: titleElement,
rightIconElement: rightIconElement,
element: content,
props: this.props,
index: index,
selected: selected,
ariaControls: ariaControls
};
content = ObjectUtils.getJSXElement(tab.props.headerTemplate, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
ref: function ref(el) {
return _this2["tab_".concat(index)] = el;
},
className: className,
style: tab.props.headerStyle,
role: "presentation"
}, content);
}
}, {
key: "renderTabHeaders",
value: function renderTabHeaders() {
var _this3 = this;
return React.Children.map(this.props.children, function (tab, index) {
return _this3.renderTabHeader(tab, index);
});
}
}, {
key: "renderNavigator",
value: function renderNavigator() {
var _this4 = this;
var headers = this.renderTabHeaders();
return /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this4.nav = el;
},
className: "p-tabview-nav",
role: "tablist"
}, headers, /*#__PURE__*/React.createElement("li", {
ref: function ref(el) {
return _this4.inkbar = el;
},
className: "p-tabview-ink-bar"
}));
}
}, {
key: "renderContent",
value: function renderContent() {
var _this5 = this;
var contents = React.Children.map(this.props.children, function (tab, index) {
if (!_this5.props.renderActiveOnly || _this5.isSelected(index)) {
return _this5.createContent(tab, index);
}
});
return /*#__PURE__*/React.createElement("div", {
className: "p-tabview-panels"
}, contents);
}
}, {
key: "createContent",
value: function createContent(tab, index) {
var selected = this.isSelected(index);
var className = classNames(tab.props.contentClassName, 'p-tabview-panel', {
'p-hidden': !selected
});
var id = this.state.id + '_content_' + index;
var ariaLabelledBy = this.state.id + '_header_' + index;
return /*#__PURE__*/React.createElement("div", {
id: id,
"aria-labelledby": ariaLabelledBy,
"aria-hidden": !selected,
className: className,
style: tab.props.contentStyle,
role: "tabpanel"
}, !this.props.renderActiveOnly ? tab.props.children : selected && tab.props.children);
}
}, {
key: "render",
value: function render() {
var className = classNames('p-tabview p-component', this.props.className);
var navigator = this.renderNavigator();
var content = this.renderContent();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: className,
style: this.props.style
}, navigator, content);
}
}]);
return TabView;
}(Component);
_defineProperty(TabView, "defaultProps", {
id: null,
activeIndex: 0,
style: null,
className: null,
renderActiveOnly: true,
onTabChange: null
});
_defineProperty(TabView, "propTypes", {
id: PropTypes.string,
activeIndex: PropTypes.number,
style: PropTypes.object,
className: PropTypes.string,
renderActiveOnly: PropTypes.bool,
onTabChange: PropTypes.func
});
export { TabPanel, TabView };
|
ajax/libs/primereact/6.5.0/tieredmenu/tieredmenu.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, classNames, Ripple, ObjectUtils, OverlayService, ZIndexUtils, ConnectedOverlayScrollHandler, CSSTransition, Portal } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var TieredMenuSub = /*#__PURE__*/function (_Component) {
_inherits(TieredMenuSub, _Component);
var _super = _createSuper$1(TieredMenuSub);
function TieredMenuSub(props) {
var _this;
_classCallCheck(this, TieredMenuSub);
_this = _super.call(this, props);
_this.state = {
activeItem: null
};
_this.onLeafClick = _this.onLeafClick.bind(_assertThisInitialized(_this));
_this.onChildItemKeyDown = _this.onChildItemKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(TieredMenuSub, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.parentActive && !this.props.parentActive) {
this.setState({
activeItem: null
});
}
if (this.props.parentActive && !this.props.root) {
this.position();
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this2.element && !_this2.element.contains(event.target)) {
_this2.setState({
activeItem: null
});
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "position",
value: function position() {
if (this.element) {
var parentItem = this.element.parentElement;
var containerOffset = DomHandler.getOffset(parentItem);
var viewport = DomHandler.getViewport();
var sublistWidth = this.element.offsetParent ? this.element.offsetWidth : DomHandler.getHiddenElementOuterWidth(this.element);
var itemOuterWidth = DomHandler.getOuterWidth(parentItem.children[0]);
if (parseInt(containerOffset.left, 10) + itemOuterWidth + sublistWidth > viewport.width - DomHandler.calculateScrollbarWidth()) {
DomHandler.addClass(this.element, 'p-submenu-list-flipped');
}
}
}
}, {
key: "onItemMouseEnter",
value: function onItemMouseEnter(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (this.props.root) {
if (this.state.activeItem || this.props.popup) {
this.setState({
activeItem: item
});
}
} else {
this.setState({
activeItem: item
});
}
}
}, {
key: "onItemClick",
value: function onItemClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
if (this.props.root) {
if (item.items) {
if (this.state.activeItem && item === this.state.activeItem) {
this.setState({
activeItem: null
});
} else {
this.setState({
activeItem: item
});
}
}
}
if (!item.items) {
this.onLeafClick();
}
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event, item) {
var listItem = event.currentTarget.parentElement;
switch (event.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.children[0].focus();
}
event.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.children[0].focus();
}
event.preventDefault();
break;
//right
case 39:
if (item.items) {
this.setState({
activeItem: item
});
setTimeout(function () {
listItem.children[1].children[0].children[0].focus();
}, 50);
}
event.preventDefault();
break;
}
if (this.props.onKeyDown) {
this.props.onKeyDown(event, listItem);
}
}
}, {
key: "onChildItemKeyDown",
value: function onChildItemKeyDown(event, childListItem) {
//left
if (event.which === 37) {
this.setState({
activeItem: null
});
childListItem.parentElement.previousElementSibling.focus();
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || !DomHandler.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || !DomHandler.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "onLeafClick",
value: function onLeafClick() {
this.setState({
activeItem: null
});
if (this.props.onLeafClick) {
this.props.onLeafClick();
}
}
}, {
key: "renderSeparator",
value: function renderSeparator(index) {
return /*#__PURE__*/React.createElement("li", {
key: 'separator_' + index,
className: "p-menu-separator",
role: "separator"
});
}
}, {
key: "renderSubmenu",
value: function renderSubmenu(item) {
if (item.items) {
return /*#__PURE__*/React.createElement(TieredMenuSub, {
model: item.items,
onLeafClick: this.onLeafClick,
popup: this.props.popup,
onKeyDown: this.onChildItemKeyDown,
parentActive: item === this.state.activeItem
});
}
return null;
}
}, {
key: "renderMenuitem",
value: function renderMenuitem(item, index) {
var _this3 = this;
var active = this.state.activeItem === item;
var className = classNames('p-menuitem', {
'p-menuitem-active': active
}, item.className);
var linkClassName = classNames('p-menuitem-link', {
'p-disabled': item.disabled
});
var iconClassName = classNames('p-menuitem-icon', item.icon);
var submenuIconClassName = 'p-submenu-icon pi pi-angle-right';
var icon = item.icon && /*#__PURE__*/React.createElement("span", {
className: iconClassName
});
var label = item.label && /*#__PURE__*/React.createElement("span", {
className: "p-menuitem-text"
}, item.label);
var submenuIcon = item.items && /*#__PURE__*/React.createElement("span", {
className: submenuIconClassName
});
var submenu = this.renderSubmenu(item);
var content = /*#__PURE__*/React.createElement("a", {
href: item.url || '#',
className: linkClassName,
target: item.target,
role: "menuitem",
"aria-haspopup": item.items != null,
onClick: function onClick(event) {
return _this3.onItemClick(event, item);
},
onKeyDown: function onKeyDown(event) {
return _this3.onItemKeyDown(event, item);
},
"aria-disabled": item.disabled
}, icon, label, submenuIcon, /*#__PURE__*/React.createElement(Ripple, null));
if (item.template) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this3.onItemClick(event, item);
},
onKeyDown: function onKeyDown(event) {
return _this3.onItemKeyDown(event, item);
},
className: linkClassName,
labelClassName: 'p-menuitem-text',
iconClassName: iconClassName,
submenuIconClassName: submenuIconClassName,
element: content,
props: this.props,
active: active
};
content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
key: item.label + '_' + index,
className: className,
style: item.style,
onMouseEnter: function onMouseEnter(event) {
return _this3.onItemMouseEnter(event, item);
},
role: "none"
}, content, submenu);
}
}, {
key: "renderItem",
value: function renderItem(item, index) {
if (item.separator) return this.renderSeparator(index);else return this.renderMenuitem(item, index);
}
}, {
key: "renderMenu",
value: function renderMenu() {
var _this4 = this;
if (this.props.model) {
return this.props.model.map(function (item, index) {
return _this4.renderItem(item, index);
});
}
return null;
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var className = classNames({
'p-submenu-list': !this.props.root
});
var submenu = this.renderMenu();
return /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this5.element = el;
},
className: className,
role: this.props.root ? 'menubar' : 'menu',
"aria-orientation": "horizontal"
}, submenu);
}
}]);
return TieredMenuSub;
}(Component);
_defineProperty(TieredMenuSub, "defaultProps", {
model: null,
root: false,
className: null,
popup: false,
onLeafClick: null,
onKeyDown: null,
parentActive: false
});
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var TieredMenu = /*#__PURE__*/function (_Component) {
_inherits(TieredMenu, _Component);
var _super = _createSuper(TieredMenu);
function TieredMenu(props) {
var _this;
_classCallCheck(this, TieredMenu);
_this = _super.call(this, props);
_this.state = {
visible: !props.popup
};
_this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this));
_this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this));
_this.onExit = _this.onExit.bind(_assertThisInitialized(_this));
_this.onExited = _this.onExited.bind(_assertThisInitialized(_this));
_this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this));
_this.menuRef = /*#__PURE__*/React.createRef();
return _this;
}
_createClass(TieredMenu, [{
key: "onPanelClick",
value: function onPanelClick(event) {
if (this.props.popup) {
OverlayService.emit('overlay-click', {
originalEvent: event,
target: this.target
});
}
}
}, {
key: "toggle",
value: function toggle(event) {
if (this.props.popup) {
if (this.state.visible) this.hide(event);else this.show(event);
}
}
}, {
key: "show",
value: function show(event) {
var _this2 = this;
this.target = event.currentTarget;
var currentEvent = event;
this.setState({
visible: true
}, function () {
if (_this2.props.onShow) {
_this2.props.onShow(currentEvent);
}
});
}
}, {
key: "hide",
value: function hide(event) {
var _this3 = this;
var currentEvent = event;
this.setState({
visible: false
}, function () {
if (_this3.props.onHide) {
_this3.props.onHide(currentEvent);
}
});
}
}, {
key: "onEnter",
value: function onEnter() {
if (this.props.autoZIndex) {
ZIndexUtils.set('menu', this.menuRef.current, this.props.baseZIndex);
}
DomHandler.absolutePosition(this.menuRef.current, this.target);
}
}, {
key: "onEntered",
value: function onEntered() {
this.bindDocumentListeners();
this.bindScrollListener();
}
}, {
key: "onExit",
value: function onExit() {
this.target = null;
this.unbindDocumentListeners();
this.unbindScrollListener();
}
}, {
key: "onExited",
value: function onExited() {
ZIndexUtils.clear(this.menuRef.current);
}
}, {
key: "bindDocumentListeners",
value: function bindDocumentListeners() {
this.bindDocumentClickListener();
this.bindDocumentResizeListener();
}
}, {
key: "unbindDocumentListeners",
value: function unbindDocumentListeners() {
this.unbindDocumentClickListener();
this.unbindDocumentResizeListener();
}
}, {
key: "bindDocumentClickListener",
value: function bindDocumentClickListener() {
var _this4 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this4.props.popup && _this4.state.visible && _this4.menuRef.current && !_this4.menuRef.current.contains(event.target)) {
_this4.hide(event);
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "unbindDocumentClickListener",
value: function unbindDocumentClickListener() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "bindDocumentResizeListener",
value: function bindDocumentResizeListener() {
var _this5 = this;
if (!this.documentResizeListener) {
this.documentResizeListener = function (event) {
if (_this5.state.visible && !DomHandler.isAndroid()) {
_this5.hide(event);
}
};
window.addEventListener('resize', this.documentResizeListener);
}
}
}, {
key: "unbindDocumentResizeListener",
value: function unbindDocumentResizeListener() {
if (this.documentResizeListener) {
window.removeEventListener('resize', this.documentResizeListener);
this.documentResizeListener = null;
}
}
}, {
key: "bindScrollListener",
value: function bindScrollListener() {
var _this6 = this;
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, function (event) {
if (_this6.state.visible) {
_this6.hide(event);
}
});
}
this.scrollHandler.bindScrollListener();
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindDocumentListeners();
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
ZIndexUtils.clear(this.menuRef.current);
}
}, {
key: "renderElement",
value: function renderElement() {
var className = classNames('p-tieredmenu p-component', {
'p-tieredmenu-overlay': this.props.popup
}, this.props.className);
return /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: this.menuRef,
classNames: "p-connected-overlay",
in: this.state.visible,
timeout: {
enter: 120,
exit: 100
},
options: this.props.transitionOptions,
unmountOnExit: true,
onEnter: this.onEnter,
onEntered: this.onEntered,
onExit: this.onExit,
onExited: this.onExited
}, /*#__PURE__*/React.createElement("div", {
ref: this.menuRef,
id: this.props.id,
className: className,
style: this.props.style,
onClick: this.onPanelClick
}, /*#__PURE__*/React.createElement(TieredMenuSub, {
model: this.props.model,
root: true,
popup: this.props.popup
})));
}
}, {
key: "render",
value: function render() {
var element = this.renderElement();
return this.props.popup ? /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo
}) : element;
}
}]);
return TieredMenu;
}(Component);
_defineProperty(TieredMenu, "defaultProps", {
id: null,
model: null,
popup: false,
style: null,
className: null,
autoZIndex: true,
baseZIndex: 0,
appendTo: null,
transitionOptions: null,
onShow: null,
onHide: null
});
export { TieredMenu };
|
ajax/libs/primereact/6.5.1/knob/knob.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Knob = /*#__PURE__*/function (_Component) {
_inherits(Knob, _Component);
var _super = _createSuper(Knob);
function Knob(props) {
var _this;
_classCallCheck(this, Knob);
_this = _super.call(this, props);
_this.state = {};
_this.radius = 40;
_this.midX = 50;
_this.midY = 50;
_this.minRadians = 4 * Math.PI / 3;
_this.maxRadians = -Math.PI / 3;
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this));
_this.onMouseUp = _this.onMouseUp.bind(_assertThisInitialized(_this));
_this.onTouchStart = _this.onTouchStart.bind(_assertThisInitialized(_this));
_this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this));
_this.onMouseMove = _this.onMouseMove.bind(_assertThisInitialized(_this));
_this.onTouchMove = _this.onTouchMove.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Knob, [{
key: "updateValue",
value: function updateValue(offsetX, offsetY) {
var dx = offsetX - this.props.size / 2;
var dy = this.props.size / 2 - offsetY;
var angle = Math.atan2(dy, dx);
var start = -Math.PI / 2 - Math.PI / 6;
this.updateModel(angle, start);
}
}, {
key: "updateModel",
value: function updateModel(angle, start) {
var mappedValue;
if (angle > this.maxRadians) mappedValue = this.mapRange(angle, this.minRadians, this.maxRadians, this.props.min, this.props.max);else if (angle < start) mappedValue = this.mapRange(angle + 2 * Math.PI, this.minRadians, this.maxRadians, this.props.min, this.props.max);else return;
if (this.props.onChange) {
var newValue = Math.round((mappedValue - this.props.min) / this.props.step) * this.props.step + this.props.min;
this.props.onChange({
value: newValue
});
}
}
}, {
key: "mapRange",
value: function mapRange(x, inMin, inMax, outMin, outMax) {
return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}
}, {
key: "onClick",
value: function onClick(event) {
if (!this.props.disabled && !this.props.readOnly) {
this.updateValue(event.nativeEvent.offsetX, event.nativeEvent.offsetY);
}
}
}, {
key: "onMouseDown",
value: function onMouseDown(event) {
if (!this.props.disabled && !this.props.readOnly) {
this.windowMouseMoveListener = this.onMouseMove;
this.windowMouseUpListener = this.onMouseUp;
window.addEventListener('mousemove', this.windowMouseMoveListener);
window.addEventListener('mouseup', this.windowMouseUpListener);
event.preventDefault();
}
}
}, {
key: "onMouseUp",
value: function onMouseUp(event) {
if (!this.props.disabled && !this.props.readOnly) {
window.removeEventListener('mousemove', this.windowMouseMoveListener);
window.removeEventListener('mouseup', this.windowMouseUpListener);
this.windowMouseMoveListener = null;
this.windowMouseUpListener = null;
event.preventDefault();
}
}
}, {
key: "onTouchStart",
value: function onTouchStart(event) {
if (!this.props.disabled && !this.props.readOnly) {
this.windowTouchMoveListener = this.onTouchMove;
this.windowTouchEndListener = this.onTouchEnd;
window.addEventListener('touchmove', this.windowTouchMoveListener, {
passive: false,
cancelable: false
});
window.addEventListener('touchend', this.windowTouchEndListener);
}
}
}, {
key: "onTouchEnd",
value: function onTouchEnd(event) {
if (!this.props.disabled && !this.props.readOnly) {
window.removeEventListener('touchmove', this.windowTouchMoveListener);
window.removeEventListener('touchend', this.windowTouchEndListener);
this.windowTouchMoveListener = null;
this.windowTouchEndListener = null;
}
}
}, {
key: "onMouseMove",
value: function onMouseMove(event) {
if (!this.props.disabled && !this.props.readOnly) {
this.updateValue(event.offsetX, event.offsetY);
event.preventDefault();
}
}
}, {
key: "onTouchMove",
value: function onTouchMove(event) {
if (!this.props.disabled && !this.props.readOnly && event.touches.length === 1) {
var rect = this.element.getBoundingClientRect();
var touch = event.targetTouches.item(0);
var offsetX = touch.clientX - rect.left;
var offsetY = touch.clientY - rect.top;
this.updateValue(offsetX, offsetY);
event.preventDefault();
}
}
}, {
key: "rangePath",
value: function rangePath() {
return "M ".concat(this.minX(), " ").concat(this.minY(), " A ").concat(this.radius, " ").concat(this.radius, " 0 1 1 ").concat(this.maxX(), " ").concat(this.maxY());
}
}, {
key: "valuePath",
value: function valuePath() {
return "M ".concat(this.zeroX(), " ").concat(this.zeroY(), " A ").concat(this.radius, " ").concat(this.radius, " 0 ").concat(this.largeArc(), " ").concat(this.sweep(), " ").concat(this.valueX(), " ").concat(this.valueY());
}
}, {
key: "zeroRadians",
value: function zeroRadians() {
if (this.props.min > 0 && this.props.max > 0) return this.mapRange(this.props.min, this.props.min, this.props.max, this.minRadians, this.maxRadians);else return this.mapRange(0, this.props.min, this.props.max, this.minRadians, this.maxRadians);
}
}, {
key: "valueRadians",
value: function valueRadians() {
return this.mapRange(this.props.value, this.props.min, this.props.max, this.minRadians, this.maxRadians);
}
}, {
key: "minX",
value: function minX() {
return this.midX + Math.cos(this.minRadians) * this.radius;
}
}, {
key: "minY",
value: function minY() {
return this.midY - Math.sin(this.minRadians) * this.radius;
}
}, {
key: "maxX",
value: function maxX() {
return this.midX + Math.cos(this.maxRadians) * this.radius;
}
}, {
key: "maxY",
value: function maxY() {
return this.midY - Math.sin(this.maxRadians) * this.radius;
}
}, {
key: "zeroX",
value: function zeroX() {
return this.midX + Math.cos(this.zeroRadians()) * this.radius;
}
}, {
key: "zeroY",
value: function zeroY() {
return this.midY - Math.sin(this.zeroRadians()) * this.radius;
}
}, {
key: "valueX",
value: function valueX() {
return this.midX + Math.cos(this.valueRadians()) * this.radius;
}
}, {
key: "valueY",
value: function valueY() {
return this.midY - Math.sin(this.valueRadians()) * this.radius;
}
}, {
key: "largeArc",
value: function largeArc() {
return Math.abs(this.zeroRadians() - this.valueRadians()) < Math.PI ? 0 : 1;
}
}, {
key: "sweep",
value: function sweep() {
return this.valueRadians() > this.zeroRadians() ? 0 : 1;
}
}, {
key: "valueToDisplay",
value: function valueToDisplay() {
return this.props.valueTemplate.replace("{value}", this.props.value.toString());
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var containerClassName = classNames('p-knob p-component', {
'p-disabled': this.props.disabled
}, this.props.className);
var text = this.props.showValue && /*#__PURE__*/React.createElement("text", {
x: 50,
y: 57,
textAnchor: 'middle',
fill: this.props.textColor,
className: 'p-knob-text',
name: this.props.name
}, this.valueToDisplay());
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: containerClassName,
style: this.props.style,
ref: function ref(el) {
return _this2.element = el;
}
}, /*#__PURE__*/React.createElement("svg", {
viewBox: "0 0 100 100",
width: this.props.size,
height: this.props.size,
onClick: this.onClick,
onMouseDown: this.onMouseDown,
onMouseUp: this.onMouseUp,
onTouchStart: this.onTouchStart,
onTouchEnd: this.onTouchEnd
}, /*#__PURE__*/React.createElement("path", {
d: this.rangePath(),
strokeWidth: this.props.strokeWidth,
stroke: this.props.rangeColor,
className: 'p-knob-range'
}), /*#__PURE__*/React.createElement("path", {
d: this.valuePath(),
strokeWidth: this.props.strokeWidth,
stroke: this.props.valueColor,
className: 'p-knob-value'
}), text));
}
}]);
return Knob;
}(Component);
_defineProperty(Knob, "defaultProps", {
id: null,
style: null,
className: null,
value: null,
size: 100,
disabled: false,
readOnly: false,
showValue: true,
step: 1,
min: 0,
max: 100,
strokeWidth: 14,
name: null,
valueColor: 'var(--primary-color, Black)',
rangeColor: 'var(--surface-d, LightGray)',
textColor: 'var(--text-color-secondary, Black)',
valueTemplate: '{value}',
onChange: null
});
export { Knob };
|
ajax/libs/primereact/6.5.0-rc.1/avatargroup/avatargroup.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 propTypes = {exports: {}};
/**
* 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$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
/**
* 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 = ReactPropTypesSecret_1;
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'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'
);
err.name = 'Invariant Violation';
throw err;
} 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,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/**
* 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
propTypes.exports = factoryWithThrowingShims();
}
var PropTypes = propTypes.exports;
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var AvatarGroup = /*#__PURE__*/function (_Component) {
_inherits(AvatarGroup, _Component);
var _super = _createSuper(AvatarGroup);
function AvatarGroup() {
_classCallCheck(this, AvatarGroup);
return _super.apply(this, arguments);
}
_createClass(AvatarGroup, [{
key: "render",
value: function render() {
var containerClassName = classNames('p-avatar-group p-component', this.props.className);
return /*#__PURE__*/React.createElement("div", {
className: containerClassName,
style: this.props.style
}, this.props.children);
}
}]);
return AvatarGroup;
}(Component);
_defineProperty(AvatarGroup, "defaultProps", {
style: null,
className: null
});
_defineProperty(AvatarGroup, "propTypes", {
style: PropTypes.object,
className: PropTypes.string
});
export { AvatarGroup };
|
ajax/libs/primereact/7.0.0-rc.1/slider/slider.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, classNames } from 'primereact/core';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Slider = /*#__PURE__*/function (_Component) {
_inherits(Slider, _Component);
var _super = _createSuper(Slider);
function Slider(props) {
var _this;
_classCallCheck(this, Slider);
_this = _super.call(this, props);
_this.onBarClick = _this.onBarClick.bind(_assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
_this.handleIndex = 0;
return _this;
}
_createClass(Slider, [{
key: "value",
get: function get() {
return this.props.range ? this.props.value || [0, 100] : this.props.value || 0;
}
}, {
key: "spin",
value: function spin(event, dir) {
var value = this.props.range ? this.value[this.handleIndex] : this.value;
var step = (this.props.step || 1) * dir;
this.updateValue(event, value + step);
event.preventDefault();
}
}, {
key: "onDragStart",
value: function onDragStart(event, index) {
if (this.props.disabled) {
return;
}
this.dragging = true;
this.updateDomData();
this.sliderHandleClick = true;
this.handleIndex = index; //event.preventDefault();
}
}, {
key: "onMouseDown",
value: function onMouseDown(event, index) {
this.bindDragListeners();
this.onDragStart(event, index);
}
}, {
key: "onTouchStart",
value: function onTouchStart(event, index) {
this.bindTouchListeners();
this.onDragStart(event, index);
}
}, {
key: "onKeyDown",
value: function onKeyDown(event, index) {
if (this.props.disabled) {
return;
}
this.handleIndex = index;
var key = event.key;
if (key === 'ArrowRight' || key === 'ArrowUp') {
this.spin(event, 1);
} else if (key === 'ArrowLeft' || key === 'ArrowDown') {
this.spin(event, -1);
}
}
}, {
key: "onBarClick",
value: function onBarClick(event) {
if (this.props.disabled) {
return;
}
if (!this.sliderHandleClick) {
this.updateDomData();
this.setValue(event);
}
this.sliderHandleClick = false;
}
}, {
key: "onDrag",
value: function onDrag(event) {
if (this.dragging) {
this.setValue(event);
event.preventDefault();
}
}
}, {
key: "onDragEnd",
value: function onDragEnd(event) {
if (this.dragging) {
this.dragging = false;
if (this.props.onSlideEnd) {
this.props.onSlideEnd({
originalEvent: event,
value: this.props.value
});
}
this.unbindDragListeners();
this.unbindTouchListeners();
}
}
}, {
key: "bindDragListeners",
value: function bindDragListeners() {
if (!this.dragListener) {
this.dragListener = this.onDrag.bind(this);
document.addEventListener('mousemove', this.dragListener);
}
if (!this.dragEndListener) {
this.dragEndListener = this.onDragEnd.bind(this);
document.addEventListener('mouseup', this.dragEndListener);
}
}
}, {
key: "unbindDragListeners",
value: function unbindDragListeners() {
if (this.dragListener) {
document.removeEventListener('mousemove', this.dragListener);
this.dragListener = null;
}
if (this.dragEndListener) {
document.removeEventListener('mouseup', this.dragEndListener);
this.dragEndListener = null;
}
}
}, {
key: "bindTouchListeners",
value: function bindTouchListeners() {
if (!this.dragListener) {
this.dragListener = this.onDrag.bind(this);
document.addEventListener('touchmove', this.dragListener);
}
if (!this.dragEndListener) {
this.dragEndListener = this.onDragEnd.bind(this);
document.addEventListener('touchend', this.dragEndListener);
}
}
}, {
key: "unbindTouchListeners",
value: function unbindTouchListeners() {
if (this.dragListener) {
document.removeEventListener('touchmove', this.dragListener);
this.dragListener = null;
}
if (this.dragEndListener) {
document.removeEventListener('touchend', this.dragEndListener);
this.dragEndListener = null;
}
}
}, {
key: "updateDomData",
value: function updateDomData() {
var rect = this.el.getBoundingClientRect();
this.initX = rect.left + DomHandler.getWindowScrollLeft();
this.initY = rect.top + DomHandler.getWindowScrollTop();
this.barWidth = this.el.offsetWidth;
this.barHeight = this.el.offsetHeight;
}
}, {
key: "setValue",
value: function setValue(event) {
var handleValue;
var pageX = event.touches ? event.touches[0].pageX : event.pageX;
var pageY = event.touches ? event.touches[0].pageY : event.pageY;
if (this.props.orientation === 'horizontal') handleValue = (pageX - this.initX) * 100 / this.barWidth;else handleValue = (this.initY + this.barHeight - pageY) * 100 / this.barHeight;
var newValue = (this.props.max - this.props.min) * (handleValue / 100) + this.props.min;
if (this.props.step) {
var oldValue = this.props.range ? this.value[this.handleIndex] : this.value;
var diff = newValue - oldValue;
if (diff < 0) newValue = oldValue + Math.ceil(newValue / this.props.step - oldValue / this.props.step) * this.props.step;else if (diff > 0) newValue = oldValue + Math.floor(newValue / this.props.step - oldValue / this.props.step) * this.props.step;
} else {
newValue = Math.floor(newValue);
}
this.updateValue(event, newValue);
}
}, {
key: "updateValue",
value: function updateValue(event, value) {
var newValue = parseFloat(value.toFixed(10));
if (this.props.range) {
if (this.handleIndex === 0) {
if (newValue < this.props.min) newValue = this.props.min;else if (newValue > this.value[1]) newValue = this.value[1];
} else {
if (newValue > this.props.max) newValue = this.props.max;else if (newValue < this.value[0]) newValue = this.value[0];
}
var newValues = _toConsumableArray(this.value);
newValues[this.handleIndex] = newValue;
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: newValues
});
}
} else {
if (newValue < this.props.min) newValue = this.props.min;else if (newValue > this.props.max) newValue = this.props.max;
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: newValue
});
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindDragListeners();
this.unbindTouchListeners();
}
}, {
key: "renderHandle",
value: function renderHandle(leftValue, bottomValue, index) {
var _this2 = this;
var handleClassName = classNames('p-slider-handle', {
'p-slider-handle-start': index === 0,
'p-slider-handle-end': index === 1,
'p-slider-handle-active': this.handleIndex === index
});
return /*#__PURE__*/React.createElement("span", {
onMouseDown: function onMouseDown(event) {
return _this2.onMouseDown(event, index);
},
onTouchStart: function onTouchStart(event) {
return _this2.onTouchStart(event, index);
},
onKeyDown: function onKeyDown(event) {
return _this2.onKeyDown(event, index);
},
tabIndex: this.props.tabIndex,
className: handleClassName,
style: {
transition: this.dragging ? 'none' : null,
left: leftValue !== null && leftValue + '%',
bottom: bottomValue && bottomValue + '%'
},
role: "slider",
"aria-valuemin": this.props.min,
"aria-valuemax": this.props.max,
"aria-valuenow": leftValue || bottomValue,
"aria-labelledby": this.props.ariaLabelledBy
});
}
}, {
key: "renderRangeSlider",
value: function renderRangeSlider() {
var values = this.value;
var horizontal = this.props.orientation === 'horizontal';
var handleValueStart = (values[0] < this.props.min ? 0 : values[0] - this.props.min) * 100 / (this.props.max - this.props.min);
var handleValueEnd = (values[1] > this.props.max ? 100 : values[1] - this.props.min) * 100 / (this.props.max - this.props.min);
var rangeStartHandle = horizontal ? this.renderHandle(handleValueStart, null, 0) : this.renderHandle(null, handleValueStart, 0);
var rangeEndHandle = horizontal ? this.renderHandle(handleValueEnd, null, 1) : this.renderHandle(null, handleValueEnd, 1);
var rangeStyle = horizontal ? {
left: handleValueStart + '%',
width: handleValueEnd - handleValueStart + '%'
} : {
bottom: handleValueStart + '%',
height: handleValueEnd - handleValueStart + '%'
};
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
className: "p-slider-range",
style: rangeStyle
}), rangeStartHandle, rangeEndHandle);
}
}, {
key: "renderSingleSlider",
value: function renderSingleSlider() {
var value = this.value;
var handleValue;
if (value < this.props.min) handleValue = 0;else if (value > this.props.max) handleValue = 100;else handleValue = (value - this.props.min) * 100 / (this.props.max - this.props.min);
var rangeStyle = this.props.orientation === 'horizontal' ? {
width: handleValue + '%'
} : {
height: handleValue + '%'
};
var handle = this.props.orientation === 'horizontal' ? this.renderHandle(handleValue, null, null) : this.renderHandle(null, handleValue, null);
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
className: "p-slider-range",
style: rangeStyle
}), handle);
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var className = classNames('p-slider p-component', this.props.className, {
'p-disabled': this.props.disabled,
'p-slider-horizontal': this.props.orientation === 'horizontal',
'p-slider-vertical': this.props.orientation === 'vertical'
});
var content = this.props.range ? this.renderRangeSlider() : this.renderSingleSlider();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
ref: function ref(el) {
return _this3.el = el;
},
style: this.props.style,
className: className,
onClick: this.onBarClick
}, content);
}
}]);
return Slider;
}(Component);
_defineProperty(Slider, "defaultProps", {
id: null,
value: null,
min: 0,
max: 100,
orientation: 'horizontal',
step: null,
range: false,
style: null,
className: null,
disabled: false,
tabIndex: 0,
ariaLabelledBy: null,
onChange: null,
onSlideEnd: null
});
export { Slider };
|
ajax/libs/primereact/7.0.1/fieldset/fieldset.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { UniqueComponentId, classNames } from 'primereact/utils';
import { CSSTransition } from 'primereact/csstransition';
import { Ripple } from 'primereact/ripple';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Fieldset = /*#__PURE__*/function (_Component) {
_inherits(Fieldset, _Component);
var _super = _createSuper(Fieldset);
function Fieldset(props) {
var _this;
_classCallCheck(this, Fieldset);
_this = _super.call(this, props);
var state = {
id: props.id
};
if (!_this.props.onToggle) {
state = _objectSpread(_objectSpread({}, state), {}, {
collapsed: props.collapsed
});
}
_this.state = state;
_this.toggle = _this.toggle.bind(_assertThisInitialized(_this));
_this.contentRef = /*#__PURE__*/React.createRef();
return _this;
}
_createClass(Fieldset, [{
key: "toggle",
value: function toggle(event) {
if (this.props.toggleable) {
var collapsed = this.props.onToggle ? this.props.collapsed : this.state.collapsed;
if (collapsed) this.expand(event);else this.collapse(event);
if (this.props.onToggle) {
this.props.onToggle({
originalEvent: event,
value: !collapsed
});
}
}
event.preventDefault();
}
}, {
key: "expand",
value: function expand(event) {
if (!this.props.onToggle) {
this.setState({
collapsed: false
});
}
if (this.props.onExpand) {
this.props.onExpand(event);
}
}
}, {
key: "collapse",
value: function collapse(event) {
if (!this.props.onToggle) {
this.setState({
collapsed: true
});
}
if (this.props.onCollapse) {
this.props.onCollapse(event);
}
}
}, {
key: "isCollapsed",
value: function isCollapsed() {
return this.props.toggleable ? this.props.onToggle ? this.props.collapsed : this.state.collapsed : false;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (!this.state.id) {
this.setState({
id: UniqueComponentId()
});
}
}
}, {
key: "renderContent",
value: function renderContent(collapsed) {
var id = this.state.id + '_content';
return /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: this.contentRef,
classNames: "p-toggleable-content",
timeout: {
enter: 1000,
exit: 450
},
in: !collapsed,
unmountOnExit: true,
options: this.props.transitionOptions
}, /*#__PURE__*/React.createElement("div", {
ref: this.contentRef,
id: id,
className: "p-toggleable-content",
"aria-hidden": collapsed,
role: "region",
"aria-labelledby": this.state.id + '_header'
}, /*#__PURE__*/React.createElement("div", {
className: "p-fieldset-content"
}, this.props.children)));
}
}, {
key: "renderToggleIcon",
value: function renderToggleIcon(collapsed) {
if (this.props.toggleable) {
var className = classNames('p-fieldset-toggler pi', {
'pi-plus': collapsed,
'pi-minus': !collapsed
});
return /*#__PURE__*/React.createElement("span", {
className: className
});
}
return null;
}
}, {
key: "renderLegendContent",
value: function renderLegendContent(collapsed) {
if (this.props.toggleable) {
var toggleIcon = this.renderToggleIcon(collapsed);
var ariaControls = this.state.id + '_content';
return /*#__PURE__*/React.createElement("a", {
href: '#' + ariaControls,
"aria-controls": ariaControls,
id: this.state.id + '_header',
"aria-expanded": !collapsed,
tabIndex: this.props.toggleable ? null : -1
}, toggleIcon, /*#__PURE__*/React.createElement("span", {
className: "p-fieldset-legend-text"
}, this.props.legend), /*#__PURE__*/React.createElement(Ripple, null));
}
return /*#__PURE__*/React.createElement("span", {
className: "p-fieldset-legend-text",
id: this.state.id + '_header'
}, this.props.legend);
}
}, {
key: "renderLegend",
value: function renderLegend(collapsed) {
var legendContent = this.renderLegendContent(collapsed);
if (this.props.legend != null || this.props.toggleable) {
return /*#__PURE__*/React.createElement("legend", {
className: "p-fieldset-legend p-unselectable-text",
onClick: this.toggle
}, legendContent);
}
}
}, {
key: "render",
value: function render() {
var className = classNames('p-fieldset p-component', this.props.className, {
'p-fieldset-toggleable': this.props.toggleable
});
var collapsed = this.isCollapsed();
var legend = this.renderLegend(collapsed);
var content = this.renderContent(collapsed);
return /*#__PURE__*/React.createElement("fieldset", {
id: this.props.id,
className: className,
style: this.props.style,
onClick: this.props.onClick
}, legend, content);
}
}]);
return Fieldset;
}(Component);
_defineProperty(Fieldset, "defaultProps", {
id: null,
legend: null,
className: null,
style: null,
toggleable: null,
collapsed: null,
transitionOptions: null,
onExpand: null,
onCollapse: null,
onToggle: null,
onClick: null
});
export { Fieldset };
|
ajax/libs/primereact/6.5.1/slider/slider.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, classNames } from 'primereact/core';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Slider = /*#__PURE__*/function (_Component) {
_inherits(Slider, _Component);
var _super = _createSuper(Slider);
function Slider(props) {
var _this;
_classCallCheck(this, Slider);
_this = _super.call(this, props);
_this.onBarClick = _this.onBarClick.bind(_assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
_this.handleIndex = 0;
return _this;
}
_createClass(Slider, [{
key: "spin",
value: function spin(event, dir) {
var value = (this.props.range ? this.props.value[this.handleIndex] : this.props.value) || 0;
var step = (this.props.step || 1) * dir;
this.updateValue(event, value + step);
event.preventDefault();
}
}, {
key: "onDragStart",
value: function onDragStart(event, index) {
if (this.props.disabled) {
return;
}
this.dragging = true;
this.updateDomData();
this.sliderHandleClick = true;
this.handleIndex = index; //event.preventDefault();
}
}, {
key: "onMouseDown",
value: function onMouseDown(event, index) {
this.bindDragListeners();
this.onDragStart(event, index);
}
}, {
key: "onTouchStart",
value: function onTouchStart(event, index) {
this.bindTouchListeners();
this.onDragStart(event, index);
}
}, {
key: "onKeyDown",
value: function onKeyDown(event, index) {
if (this.props.disabled) {
return;
}
this.handleIndex = index;
var key = event.key;
if (key === 'ArrowRight' || key === 'ArrowUp') {
this.spin(event, 1);
} else if (key === 'ArrowLeft' || key === 'ArrowDown') {
this.spin(event, -1);
}
}
}, {
key: "onBarClick",
value: function onBarClick(event) {
if (this.props.disabled) {
return;
}
if (!this.sliderHandleClick) {
this.updateDomData();
this.setValue(event);
}
this.sliderHandleClick = false;
}
}, {
key: "onDrag",
value: function onDrag(event) {
if (this.dragging) {
this.setValue(event);
event.preventDefault();
}
}
}, {
key: "onDragEnd",
value: function onDragEnd(event) {
if (this.dragging) {
this.dragging = false;
if (this.props.onSlideEnd) {
this.props.onSlideEnd({
originalEvent: event,
value: this.props.value
});
}
this.unbindDragListeners();
this.unbindTouchListeners();
}
}
}, {
key: "bindDragListeners",
value: function bindDragListeners() {
if (!this.dragListener) {
this.dragListener = this.onDrag.bind(this);
document.addEventListener('mousemove', this.dragListener);
}
if (!this.dragEndListener) {
this.dragEndListener = this.onDragEnd.bind(this);
document.addEventListener('mouseup', this.dragEndListener);
}
}
}, {
key: "unbindDragListeners",
value: function unbindDragListeners() {
if (this.dragListener) {
document.removeEventListener('mousemove', this.dragListener);
this.dragListener = null;
}
if (this.dragEndListener) {
document.removeEventListener('mouseup', this.dragEndListener);
this.dragEndListener = null;
}
}
}, {
key: "bindTouchListeners",
value: function bindTouchListeners() {
if (!this.dragListener) {
this.dragListener = this.onDrag.bind(this);
document.addEventListener('touchmove', this.dragListener);
}
if (!this.dragEndListener) {
this.dragEndListener = this.onDragEnd.bind(this);
document.addEventListener('touchend', this.dragEndListener);
}
}
}, {
key: "unbindTouchListeners",
value: function unbindTouchListeners() {
if (this.dragListener) {
document.removeEventListener('touchmove', this.dragListener);
this.dragListener = null;
}
if (this.dragEndListener) {
document.removeEventListener('touchend', this.dragEndListener);
this.dragEndListener = null;
}
}
}, {
key: "updateDomData",
value: function updateDomData() {
var rect = this.el.getBoundingClientRect();
this.initX = rect.left + DomHandler.getWindowScrollLeft();
this.initY = rect.top + DomHandler.getWindowScrollTop();
this.barWidth = this.el.offsetWidth;
this.barHeight = this.el.offsetHeight;
}
}, {
key: "setValue",
value: function setValue(event) {
var handleValue;
var pageX = event.touches ? event.touches[0].pageX : event.pageX;
var pageY = event.touches ? event.touches[0].pageY : event.pageY;
if (this.props.orientation === 'horizontal') handleValue = (pageX - this.initX) * 100 / this.barWidth;else handleValue = (this.initY + this.barHeight - pageY) * 100 / this.barHeight;
var newValue = (this.props.max - this.props.min) * (handleValue / 100) + this.props.min;
if (this.props.step) {
var oldValue = this.props.range ? this.props.value[this.handleIndex] : this.props.value;
var diff = newValue - oldValue;
if (diff < 0) newValue = oldValue + Math.ceil(newValue / this.props.step - oldValue / this.props.step) * this.props.step;else if (diff > 0) newValue = oldValue + Math.floor(newValue / this.props.step - oldValue / this.props.step) * this.props.step;
} else {
newValue = Math.floor(newValue);
}
this.updateValue(event, newValue);
}
}, {
key: "updateValue",
value: function updateValue(event, value) {
var newValue = parseFloat(value.toFixed(10));
if (this.props.range) {
if (this.handleIndex === 0) {
if (newValue < this.props.min) newValue = this.props.min;else if (newValue > this.props.value[1]) newValue = this.props.value[1];
} else {
if (newValue > this.props.max) newValue = this.props.max;else if (newValue < this.props.value[0]) newValue = this.props.value[0];
}
var newValues = _toConsumableArray(this.props.value);
newValues[this.handleIndex] = newValue;
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: newValues
});
}
} else {
if (newValue < this.props.min) newValue = this.props.min;else if (newValue > this.props.max) newValue = this.props.max;
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: newValue
});
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindDragListeners();
this.unbindTouchListeners();
}
}, {
key: "renderHandle",
value: function renderHandle(leftValue, bottomValue, index) {
var _this2 = this;
var handleClassName = classNames('p-slider-handle', {
'p-slider-handle-start': index === 0,
'p-slider-handle-end': index === 1,
'p-slider-handle-active': this.handleIndex === index
});
return /*#__PURE__*/React.createElement("span", {
onMouseDown: function onMouseDown(event) {
return _this2.onMouseDown(event, index);
},
onTouchStart: function onTouchStart(event) {
return _this2.onTouchStart(event, index);
},
onKeyDown: function onKeyDown(event) {
return _this2.onKeyDown(event, index);
},
tabIndex: this.props.tabIndex,
className: handleClassName,
style: {
transition: this.dragging ? 'none' : null,
left: leftValue !== null && leftValue + '%',
bottom: bottomValue && bottomValue + '%'
},
role: "slider",
"aria-valuemin": this.props.min,
"aria-valuemax": this.props.max,
"aria-valuenow": leftValue || bottomValue,
"aria-labelledby": this.props.ariaLabelledBy
});
}
}, {
key: "renderRangeSlider",
value: function renderRangeSlider() {
var values = this.props.value || [0, 0];
var horizontal = this.props.orientation === 'horizontal';
var handleValueStart = (values[0] < this.props.min ? 0 : values[0] - this.props.min) * 100 / (this.props.max - this.props.min);
var handleValueEnd = (values[1] > this.props.max ? 100 : values[1] - this.props.min) * 100 / (this.props.max - this.props.min);
var rangeStartHandle = horizontal ? this.renderHandle(handleValueStart, null, 0) : this.renderHandle(null, handleValueStart, 0);
var rangeEndHandle = horizontal ? this.renderHandle(handleValueEnd, null, 1) : this.renderHandle(null, handleValueEnd, 1);
var rangeStyle = horizontal ? {
left: handleValueStart + '%',
width: handleValueEnd - handleValueStart + '%'
} : {
bottom: handleValueStart + '%',
height: handleValueEnd - handleValueStart + '%'
};
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
className: "p-slider-range",
style: rangeStyle
}), rangeStartHandle, rangeEndHandle);
}
}, {
key: "renderSingleSlider",
value: function renderSingleSlider() {
var value = this.props.value || 0;
var handleValue;
if (value < this.props.min) handleValue = 0;else if (value > this.props.max) handleValue = 100;else handleValue = (value - this.props.min) * 100 / (this.props.max - this.props.min);
var rangeStyle = this.props.orientation === 'horizontal' ? {
width: handleValue + '%'
} : {
height: handleValue + '%'
};
var handle = this.props.orientation === 'horizontal' ? this.renderHandle(handleValue, null, null) : this.renderHandle(null, handleValue, null);
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
className: "p-slider-range",
style: rangeStyle
}), handle);
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var className = classNames('p-slider p-component', this.props.className, {
'p-disabled': this.props.disabled,
'p-slider-horizontal': this.props.orientation === 'horizontal',
'p-slider-vertical': this.props.orientation === 'vertical'
});
var content = this.props.range ? this.renderRangeSlider() : this.renderSingleSlider();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
ref: function ref(el) {
return _this3.el = el;
},
style: this.props.style,
className: className,
onClick: this.onBarClick
}, content);
}
}]);
return Slider;
}(Component);
_defineProperty(Slider, "defaultProps", {
id: null,
value: null,
min: 0,
max: 100,
orientation: 'horizontal',
step: null,
range: false,
style: null,
className: null,
disabled: false,
tabIndex: 0,
ariaLabelledBy: null,
onChange: null,
onSlideEnd: null
});
export { Slider };
|
ajax/libs/material-ui/4.9.2/esm/FilledInput/FilledInput.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import InputBase from '../InputBase';
import withStyles from '../styles/withStyles';
export var styles = function styles(theme) {
var light = theme.palette.type === 'light';
var bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';
var backgroundColor = light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)';
return {
/* Styles applied to the root element. */
root: {
position: 'relative',
backgroundColor: backgroundColor,
borderTopLeftRadius: theme.shape.borderRadius,
borderTopRightRadius: theme.shape.borderRadius,
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shorter,
easing: theme.transitions.easing.easeOut
}),
'&:hover': {
backgroundColor: light ? 'rgba(0, 0, 0, 0.13)' : 'rgba(255, 255, 255, 0.13)',
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: backgroundColor
}
},
'&$focused': {
backgroundColor: light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)'
},
'&$disabled': {
backgroundColor: light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)'
}
},
/* Styles applied to the root element if color secondary. */
colorSecondary: {
'&$underline:after': {
borderBottomColor: theme.palette.secondary.main
}
},
/* Styles applied to the root element if `disableUnderline={false}`. */
underline: {
'&:after': {
borderBottom: "2px solid ".concat(theme.palette.primary.main),
left: 0,
bottom: 0,
// Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
content: '""',
position: 'absolute',
right: 0,
transform: 'scaleX(0)',
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shorter,
easing: theme.transitions.easing.easeOut
}),
pointerEvents: 'none' // Transparent to the hover style.
},
'&$focused:after': {
transform: 'scaleX(1)'
},
'&$error:after': {
borderBottomColor: theme.palette.error.main,
transform: 'scaleX(1)' // error is always underlined in red
},
'&:before': {
borderBottom: "1px solid ".concat(bottomLineColor),
left: 0,
bottom: 0,
// Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
content: '"\\00a0"',
position: 'absolute',
right: 0,
transition: theme.transitions.create('border-bottom-color', {
duration: theme.transitions.duration.shorter
}),
pointerEvents: 'none' // Transparent to the hover style.
},
'&:hover:before': {
borderBottom: "1px solid ".concat(theme.palette.text.primary)
},
'&$disabled:before': {
borderBottomStyle: 'dotted'
}
},
/* Pseudo-class applied to the root element if the component is focused. */
focused: {},
/* Pseudo-class applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if `startAdornment` is provided. */
adornedStart: {
paddingLeft: 12
},
/* Styles applied to the root element if `endAdornment` is provided. */
adornedEnd: {
paddingRight: 12
},
/* Pseudo-class applied to the root element if `error={true}`. */
error: {},
/* Styles applied to the `input` element if `margin="dense"`. */
marginDense: {},
/* Styles applied to the root element if `multiline={true}`. */
multiline: {
padding: '27px 12px 10px',
'&$marginDense': {
paddingTop: 23,
paddingBottom: 6
}
},
/* Styles applied to the `input` element. */
input: {
padding: '27px 12px 10px',
'&:-webkit-autofill': {
WebkitBoxShadow: theme.palette.type === 'dark' ? '0 0 0 100px #266798 inset' : null,
WebkitTextFillColor: theme.palette.type === 'dark' ? '#fff' : null,
borderTopLeftRadius: 'inherit',
borderTopRightRadius: 'inherit'
}
},
/* Styles applied to the `input` element if `margin="dense"`. */
inputMarginDense: {
paddingTop: 23,
paddingBottom: 6
},
/* Styles applied to the `input` if in `<FormControl hiddenLabel />`. */
inputHiddenLabel: {
paddingTop: 18,
paddingBottom: 19,
'&$inputMarginDense': {
paddingTop: 10,
paddingBottom: 11
}
},
/* Styles applied to the `input` element if `multiline={true}`. */
inputMultiline: {
padding: 0
},
/* Styles applied to the `input` element if `startAdornment` is provided. */
inputAdornedStart: {
paddingLeft: 0
},
/* Styles applied to the `input` element if `endAdornment` is provided. */
inputAdornedEnd: {
paddingRight: 0
}
};
};
var FilledInput = React.forwardRef(function FilledInput(props, ref) {
var disableUnderline = props.disableUnderline,
classes = props.classes,
_props$fullWidth = props.fullWidth,
fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
_props$inputComponent = props.inputComponent,
inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,
_props$multiline = props.multiline,
multiline = _props$multiline === void 0 ? false : _props$multiline,
_props$type = props.type,
type = _props$type === void 0 ? 'text' : _props$type,
other = _objectWithoutProperties(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]);
return React.createElement(InputBase, _extends({
classes: _extends({}, classes, {
root: clsx(classes.root, !disableUnderline && classes.underline),
underline: null
}),
fullWidth: fullWidth,
inputComponent: inputComponent,
multiline: multiline,
ref: ref,
type: type
}, other));
});
process.env.NODE_ENV !== "production" ? FilledInput.propTypes = {
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element will be focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The CSS class name of the wrapper element.
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['primary', 'secondary']),
/**
* The default `input` element value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the `input` element will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the input will not have an underline.
*/
disableUnderline: PropTypes.bool,
/**
* End `InputAdornment` for this component.
*/
endAdornment: PropTypes.node,
/**
* If `true`, the input will indicate an error. This is normally obtained via context from
* FormControl.
*/
error: PropTypes.bool,
/**
* If `true`, the input will take up the full width of its container.
*/
fullWidth: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* The component used for the native input.
* Either a string to use a DOM element or a component.
*/
inputComponent: PropTypes.elementType,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
*/
margin: PropTypes.oneOf(['dense', 'none']),
/**
* If `true`, a textarea element will be rendered.
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* Callback fired when the value is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The short hint displayed in the input before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element will be required.
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Start `InputAdornment` for this component.
*/
startAdornment: PropTypes.node,
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
*/
type: PropTypes.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any
} : void 0;
FilledInput.muiName = 'Input';
export default withStyles(styles, {
name: 'MuiFilledInput'
})(FilledInput); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.