onValueChange(target.checked)}\n />\n )}\n disabled={readOnly}\n label={label}\n {...restProps}\n />\n));\n\nBooleanEditorBase.propTypes = {\n label: PropTypes.string,\n readOnly: PropTypes.bool,\n value: PropTypes.bool,\n onValueChange: PropTypes.func.isRequired,\n classes: PropTypes.object.isRequired,\n};\n\nBooleanEditorBase.defaultProps = {\n label: undefined,\n readOnly: false,\n value: false,\n};\n\nexport const BooleanEditor = withStyles(styles)(BooleanEditorBase, { name: 'BooleanEditor' });\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport MenuItem from '@material-ui/core/MenuItem';\nimport { withStyles } from '@material-ui/core/styles';\nimport classNames from 'clsx';\nimport TextField from '@material-ui/core/TextField';\n\nconst styles = ({ typography, spacing }) => ({\n filledSelect: {\n marginTop: spacing(0.375),\n marginBottom: spacing(0.125),\n },\n menuItem: {\n fontSize: typography.fontSize,\n textTransform: 'uppercase',\n },\n});\n\nconst FilledSelectBase = React.memo(({\n value,\n availableOptions,\n onValueChange,\n readOnly,\n classes,\n className,\n ...restProps\n}) => {\n const handleChange = (event) => {\n if (event.target.value !== value) onValueChange(event.target.value);\n };\n\n return (\n \n {availableOptions.map(option => (\n \n ))}\n \n );\n});\n\nFilledSelectBase.propTypes = {\n onValueChange: PropTypes.func,\n classes: PropTypes.object.isRequired,\n value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,\n availableOptions: PropTypes.arrayOf(PropTypes.shape({\n id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n text: PropTypes.string.isRequired,\n })),\n readOnly: PropTypes.bool,\n className: PropTypes.string,\n};\n\nFilledSelectBase.defaultProps = {\n readOnly: false,\n onValueChange: () => undefined,\n availableOptions: [],\n className: undefined,\n};\n\nexport const FilledSelect = withStyles(styles)(FilledSelectBase, { name: 'FilledSelect' });\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { STANDARD_SELECT } from '@devexpress/dx-scheduler-core';\nimport { FilledSelect } from './filled-select';\nimport { OutlinedSelect } from './outlined-select';\n\nexport const Select = React.memo(({\n value,\n availableOptions,\n onValueChange,\n readOnly,\n type,\n ...restProps\n}) => {\n const ResultingSelect = type === STANDARD_SELECT ? FilledSelect : OutlinedSelect;\n\n return (\n \n );\n});\n\nSelect.propTypes = {\n onValueChange: PropTypes.func.isRequired,\n value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,\n availableOptions: PropTypes.arrayOf(PropTypes.shape({\n id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n text: PropTypes.string.isRequired,\n })),\n readOnly: PropTypes.bool,\n type: PropTypes.string,\n};\n\nSelect.defaultProps = {\n readOnly: false,\n availableOptions: [],\n type: STANDARD_SELECT,\n};\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport Grid from '@material-ui/core/Grid';\nimport classNames from 'clsx';\nimport { NUMBER_EDITOR } from '@devexpress/dx-scheduler-core';\n\nconst styles = ({ spacing }) => ({\n grid: {\n marginTop: spacing(1.75),\n },\n label: {\n width: '6.5em',\n },\n labelWithMargin: {\n marginLeft: '1em',\n width: 'calc((100% - 7.5em) * 4 / 7)',\n },\n textEditor: {\n width: 'calc((100% - 7.5em) * 3 / 7)',\n maxWidth: '8em',\n },\n});\n\nconst IntervalEditorBase = ({\n classes,\n className,\n labelComponent: Label,\n textEditorComponent: TextEditor,\n repeatEveryLabel,\n repeatIntervalLabel,\n readOnly,\n interval,\n changeRecurrenceInterval,\n ...restProps\n}) => (\n \n \n \n \n \n);\n\nIntervalEditorBase.propTypes = {\n classes: PropTypes.object.isRequired,\n className: PropTypes.string,\n repeatEveryLabel: PropTypes.string.isRequired,\n repeatIntervalLabel: PropTypes.string.isRequired,\n readOnly: PropTypes.bool.isRequired,\n interval: PropTypes.number,\n changeRecurrenceInterval: PropTypes.func.isRequired,\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n};\n\nIntervalEditorBase.defaultProps = {\n className: undefined,\n interval: 1,\n};\n\nexport const IntervalEditor = withStyles(styles)(IntervalEditorBase, { name: 'IntervalEditor' });\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport {\n getRecurrenceOptions,\n changeRecurrenceOptions,\n checkIsNaturalNumber,\n} from '@devexpress/dx-scheduler-core';\nimport { IntervalEditor } from './interval-editor';\n\nexport const Daily = ({\n weeklyRecurrenceSelectorComponent,\n radioGroupComponent,\n textEditorComponent,\n labelComponent,\n getMessage,\n readOnly,\n onFieldChange,\n appointmentData,\n selectComponent,\n formatDate,\n firstDayOfWeek,\n ...restProps\n}) => {\n const { rRule } = appointmentData;\n const recurrenceOptions = React.useMemo(() => getRecurrenceOptions(rRule) || {}, [rRule]);\n\n const changeRecurrenceInterval = React.useCallback(\n interval => checkIsNaturalNumber(interval) && onFieldChange({\n rRule: changeRecurrenceOptions({ ...recurrenceOptions, interval }),\n }), [recurrenceOptions, onFieldChange],\n );\n return (\n \n );\n};\n\nDaily.propTypes = {\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n radioGroupComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n weeklyRecurrenceSelectorComponent: PropTypes.oneOfType([\n PropTypes.func, PropTypes.object,\n ]).isRequired,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n onFieldChange: PropTypes.func,\n getMessage: PropTypes.func.isRequired,\n readOnly: PropTypes.bool,\n formatDate: PropTypes.func.isRequired,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nDaily.defaultProps = {\n onFieldChange: () => undefined,\n readOnly: false,\n};\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport { getRecurrenceOptions, changeRecurrenceOptions, checkIsNaturalNumber } from '@devexpress/dx-scheduler-core';\nimport { IntervalEditor } from './interval-editor';\n\nconst styles = theme => ({\n container: {\n marginBottom: theme.spacing(2),\n },\n});\n\nconst WeeklyBase = ({\n radioGroupComponent,\n textEditorComponent,\n labelComponent,\n classes,\n getMessage,\n readOnly,\n onFieldChange,\n appointmentData,\n selectComponent,\n weeklyRecurrenceSelectorComponent: WeeklyRecurrenceSelector,\n formatDate,\n firstDayOfWeek,\n ...restProps\n}) => {\n const { rRule } = appointmentData;\n const recurrenceOptions = React.useMemo(() => getRecurrenceOptions(rRule) || {}, [rRule]);\n\n const changeRecurrenceInterval = React.useCallback(\n interval => checkIsNaturalNumber(interval) && onFieldChange({\n rRule: changeRecurrenceOptions({ ...recurrenceOptions, interval }),\n }), [recurrenceOptions, onFieldChange],\n );\n return (\n \n \n \n
\n );\n};\n\nWeeklyBase.propTypes = {\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n radioGroupComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n weeklyRecurrenceSelectorComponent: PropTypes.oneOfType([\n PropTypes.func, PropTypes.object,\n ]).isRequired,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n onFieldChange: PropTypes.func,\n classes: PropTypes.object.isRequired,\n getMessage: PropTypes.func.isRequired,\n readOnly: PropTypes.bool,\n formatDate: PropTypes.func.isRequired,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nWeeklyBase.defaultProps = {\n onFieldChange: () => undefined,\n readOnly: false,\n};\n\nexport const Weekly = withStyles(styles)(WeeklyBase, { name: 'Weekly' });\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport {\n MONTHLY_RADIO_GROUP,\n getRecurrenceOptions,\n changeRecurrenceOptions,\n checkIsNaturalNumber,\n} from '@devexpress/dx-scheduler-core';\nimport { IntervalEditor } from './interval-editor';\n\nconst styles = theme => ({\n container: {\n marginBottom: theme.spacing(1),\n },\n});\n\nconst MonthlyBase = ({\n radioGroupComponent: RadioGroup,\n textEditorComponent,\n labelComponent,\n classes,\n getMessage,\n readOnly,\n onFieldChange,\n appointmentData,\n selectComponent,\n weeklyRecurrenceSelectorComponent,\n formatDate,\n firstDayOfWeek,\n ...restProps\n}) => {\n const { rRule } = appointmentData;\n const recurrenceOptions = React.useMemo(() => getRecurrenceOptions(rRule) || {}, [rRule]);\n\n const changeRecurrenceInterval = React.useCallback(\n interval => checkIsNaturalNumber(interval) && onFieldChange({\n rRule: changeRecurrenceOptions({ ...recurrenceOptions, interval }),\n }), [recurrenceOptions, onFieldChange],\n );\n return (\n \n \n null}\n firstDayOfWeek={firstDayOfWeek}\n />\n
\n );\n};\n\nMonthlyBase.propTypes = {\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n radioGroupComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n weeklyRecurrenceSelectorComponent: PropTypes.oneOfType([\n PropTypes.func, PropTypes.object,\n ]).isRequired,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n onFieldChange: PropTypes.func,\n classes: PropTypes.object.isRequired,\n getMessage: PropTypes.func.isRequired,\n readOnly: PropTypes.bool,\n formatDate: PropTypes.func.isRequired,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nMonthlyBase.defaultProps = {\n onFieldChange: () => undefined,\n readOnly: false,\n};\n\nexport const Monthly = withStyles(styles)(MonthlyBase, { name: 'Monthly' });\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport {\n YEARLY_RADIO_GROUP,\n getRecurrenceOptions,\n changeRecurrenceOptions,\n checkIsNaturalNumber,\n} from '@devexpress/dx-scheduler-core';\nimport { IntervalEditor } from './interval-editor';\n\nconst styles = theme => ({\n radioGroup: {\n marginTop: theme.spacing(1),\n },\n});\n\nconst YearlyBase = ({\n radioGroupComponent: RadioGroup,\n textEditorComponent,\n labelComponent,\n classes,\n getMessage,\n readOnly,\n onFieldChange,\n appointmentData,\n selectComponent,\n weeklyRecurrenceSelectorComponent,\n formatDate,\n firstDayOfWeek,\n ...restProps\n}) => {\n const { rRule } = appointmentData;\n const recurrenceOptions = React.useMemo(() => getRecurrenceOptions(rRule) || {}, [rRule]);\n\n const changeRecurrenceInterval = React.useCallback(\n interval => checkIsNaturalNumber(interval) && onFieldChange({\n rRule: changeRecurrenceOptions({ ...recurrenceOptions, interval }),\n }), [recurrenceOptions, onFieldChange],\n );\n return (\n \n \n null}\n firstDayOfWeek={firstDayOfWeek}\n />\n
\n );\n};\n\nYearlyBase.propTypes = {\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n radioGroupComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n weeklyRecurrenceSelectorComponent: PropTypes.oneOfType([\n PropTypes.func, PropTypes.object,\n ]).isRequired,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n onFieldChange: PropTypes.func,\n classes: PropTypes.object.isRequired,\n getMessage: PropTypes.func.isRequired,\n readOnly: PropTypes.bool,\n formatDate: PropTypes.func.isRequired,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nYearlyBase.defaultProps = {\n onFieldChange: () => undefined,\n readOnly: false,\n};\n\nexport const Yearly = withStyles(styles)(YearlyBase, { name: 'Yearly' });\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport {\n END_REPEAT_RADIO_GROUP,\n TITLE,\n getRecurrenceOptions,\n RRULE_REPEAT_TYPES,\n OUTLINED_SELECT,\n getFrequencyString,\n getAvailableRecurrenceOptions,\n handleChangeFrequency,\n} from '@devexpress/dx-scheduler-core';\nimport classNames from 'clsx';\nimport { Daily as DailyLayout } from './layouts/daily';\nimport { Weekly as WeeklyLayout } from './layouts/weekly';\nimport { Monthly as MonthlyLayout } from './layouts/monthly';\nimport { Yearly as YearlyLayout } from './layouts/yearly';\nimport { TRANSITIONS_TIME, LAYOUT_MEDIA_QUERY } from '../../constants';\n\nconst styles = ({ spacing }) => ({\n root: {\n padding: 0,\n paddingTop: spacing(3),\n overflow: 'hidden',\n width: 0,\n transition: `all ${TRANSITIONS_TIME}ms cubic-bezier(0, 0, 0.2, 1)`,\n boxSizing: 'border-box',\n maxWidth: 0,\n opacity: 0,\n [`${LAYOUT_MEDIA_QUERY}`]: {\n minWidth: '100%',\n maxHeight: 0,\n },\n },\n visible: {\n maxWidth: '500px',\n width: '500px',\n padding: spacing(3),\n paddingRight: spacing(4),\n paddingLeft: spacing(1),\n opacity: 1,\n [`${LAYOUT_MEDIA_QUERY}`]: {\n width: '100%',\n maxWidth: '700px',\n paddingRight: spacing(2),\n paddingLeft: spacing(2),\n maxHeight: 1000,\n },\n '@media (min-width: 700px) and (max-width: 850px)': {\n width: '300px',\n },\n '@media (min-width: 850px) and (max-width: 1000px)': {\n width: '370px',\n },\n '@media (min-width: 1000px) and (max-width: 1150px)': {\n width: '440px',\n },\n },\n invisible: {\n maxHeight: 0,\n '@media (min-width: 700px)': {\n maxHeight: '500px',\n },\n },\n label: {\n width: '8em',\n },\n repeatLabel: {\n marginBottom: spacing(0.375),\n },\n radioGroup: {\n marginTop: spacing(0.5),\n },\n endRepeatLabel: {\n marginTop: spacing(2),\n },\n select: {\n height: '3.8em',\n },\n});\n\nconst getLayoutComponent = (recurrenceOptions) => {\n if (recurrenceOptions) {\n switch (recurrenceOptions.freq) {\n case RRULE_REPEAT_TYPES.DAILY:\n return DailyLayout;\n case RRULE_REPEAT_TYPES.WEEKLY:\n return WeeklyLayout;\n case RRULE_REPEAT_TYPES.MONTHLY:\n return MonthlyLayout;\n case RRULE_REPEAT_TYPES.YEARLY:\n return YearlyLayout;\n default:\n break;\n }\n }\n return () => null;\n};\n\nconst LayoutBase = ({\n radioGroupComponent: RadioGroup,\n textEditorComponent,\n labelComponent: Label,\n dateEditorComponent,\n selectComponent: Select,\n weeklyRecurrenceSelectorComponent,\n children,\n classes,\n className,\n getMessage,\n readOnly,\n onFieldChange,\n appointmentData,\n formatDate,\n locale,\n visible,\n firstDayOfWeek,\n ...restProps\n}) => {\n if (!appointmentData.rRule) {\n return null;\n }\n const recurrenceOptions = getRecurrenceOptions(appointmentData.rRule) || {};\n const MainLayoutComponent = getLayoutComponent(recurrenceOptions);\n const frequency = getFrequencyString(recurrenceOptions.freq);\n\n const { rRule, startDate } = appointmentData;\n const changeFrequency = React.useCallback(repeatType => handleChangeFrequency(\n repeatType, rRule, startDate, onFieldChange,\n ), [rRule, startDate, onFieldChange]);\n const selectOptions = React.useMemo(\n () => getAvailableRecurrenceOptions(getMessage), [getMessage],\n );\n return (\n \n \n \n \n \n \n {children}\n
\n );\n};\n\nLayoutBase.propTypes = {\n locale: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n radioGroupComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n dateEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n weeklyRecurrenceSelectorComponent: PropTypes.oneOfType([\n PropTypes.func, PropTypes.object,\n ]).isRequired,\n onFieldChange: PropTypes.func,\n children: PropTypes.node,\n className: PropTypes.string,\n classes: PropTypes.object.isRequired,\n getMessage: PropTypes.func.isRequired,\n readOnly: PropTypes.bool,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n formatDate: PropTypes.func.isRequired,\n visible: PropTypes.bool.isRequired,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nLayoutBase.defaultProps = {\n locale: 'en-US',\n onFieldChange: () => undefined,\n className: undefined,\n readOnly: false,\n children: null,\n};\n\nexport const Layout = withStyles(styles)(LayoutBase, { name: 'RecurrenceLayout' });\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport RadioGroup from '@material-ui/core/RadioGroup';\nimport FormControlLabel from '@material-ui/core/FormControlLabel';\nimport Radio from '@material-ui/core/Radio';\nimport Grid from '@material-ui/core/Grid';\nimport InputAdornment from '@material-ui/core/InputAdornment';\nimport {\n NUMBER_EDITOR, getRecurrenceOptions, changeRecurrenceOptions,\n checkIsNaturalNumber, isDateValid,\n} from '@devexpress/dx-scheduler-core';\n\nconst styles = ({ spacing, typography }) => ({\n textEditor: {\n width: 'calc(100% - 4.5em)',\n },\n label: {\n width: '4.5em',\n },\n input: {\n paddingBottom: spacing(2.75),\n },\n radioLabel: {\n fontSize: typography.fontSize + 1,\n },\n dateEditor: {\n width: 'calc(100% - 4.5em)',\n },\n formControl: {\n marginRight: 0,\n },\n controlLabel: {\n width: '100%',\n },\n});\n\nconst EndRepeatEditorBase = ({\n classes,\n getMessage,\n labelComponent: Label,\n textEditorComponent: TextEditor,\n dateEditorComponent: DateEditor,\n onFieldChange,\n appointmentData,\n locale,\n readOnly,\n ...restProps\n}) => {\n const [count, setCount] = React.useState(1);\n const [endDate, setEndDate] = React.useState(appointmentData.endDate);\n\n const { rRule } = appointmentData;\n const recurrenceOptions = React.useMemo(() => getRecurrenceOptions(rRule) || {}, [rRule]);\n const changeRecurrenceCount = React.useCallback(\n nextCount => checkIsNaturalNumber(nextCount) && onFieldChange({\n rRule: changeRecurrenceOptions({ ...recurrenceOptions, count: nextCount }),\n }), [recurrenceOptions, onFieldChange],\n );\n const changeRecurrenceEndDate = React.useCallback((date) => {\n if (isDateValid(date)) {\n onFieldChange({\n rRule: changeRecurrenceOptions({ ...recurrenceOptions, until: date }),\n });\n }\n }, [recurrenceOptions, onFieldChange]);\n\n const countEditorProps = React.useMemo(() => ({\n endAdornment: {getMessage('occurrencesLabel')},\n }), []);\n\n const recurrenceCount = recurrenceOptions.count || count;\n const recurrenceEndDate = recurrenceOptions.until || endDate;\n let value;\n if (recurrenceOptions.count) {\n value = 'endAfter';\n } else if (recurrenceOptions.until) {\n value = 'endBy';\n } else {\n value = 'never';\n }\n\n const onRadioGroupValueChange = (event) => {\n let change;\n switch (event.target.value) {\n case 'endAfter':\n setEndDate(recurrenceOptions.until || endDate);\n change = { count, until: undefined };\n break;\n case 'endBy':\n setCount(recurrenceOptions.count || count);\n change = { count: undefined, until: endDate };\n break;\n case 'never':\n setEndDate(recurrenceOptions.until || endDate);\n setCount(recurrenceOptions.count || count);\n change = { count: undefined, until: undefined };\n break;\n default:\n break;\n }\n onFieldChange({\n rRule: changeRecurrenceOptions({\n ...recurrenceOptions, ...change,\n }),\n });\n };\n return (\n \n }\n label={getMessage('never')}\n classes={{ label: classes.radioLabel }}\n disabled={readOnly}\n />\n }\n disabled={readOnly}\n label={(\n \n \n \n \n )}\n />\n }\n label={(\n \n \n \n \n )}\n />\n \n );\n};\n\nEndRepeatEditorBase.propTypes = {\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n dateEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n locale: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]).isRequired,\n classes: PropTypes.object.isRequired,\n getMessage: PropTypes.func,\n onFieldChange: PropTypes.func,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n readOnly: PropTypes.bool,\n};\n\nEndRepeatEditorBase.defaultProps = {\n onFieldChange: () => undefined,\n getMessage: () => undefined,\n readOnly: false,\n};\n\nexport const EndRepeatEditor = withStyles(styles)(EndRepeatEditorBase, { name: 'EndRepeatEditor' });\n","import React, { useState } from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport RadioGroup from '@material-ui/core/RadioGroup';\nimport FormControlLabel from '@material-ui/core/FormControlLabel';\nimport Radio from '@material-ui/core/Radio';\nimport Grid from '@material-ui/core/Grid';\nimport {\n NUMBER_EDITOR,\n handleToDayOfWeekChange,\n getRecurrenceOptions,\n changeRecurrenceOptions,\n handleStartDateChange,\n getRadioGroupDisplayData,\n getWeekNumberLabels,\n getDaysOfWeek,\n} from '@devexpress/dx-scheduler-core';\n\nconst styles = ({ spacing }) => ({\n textEditor: {\n width: 'calc((100% - 5.5em) * 3 / 7)',\n maxWidth: '12em',\n marginRight: '1em',\n },\n input: {\n paddingBottom: spacing(2.75),\n },\n select: {\n width: 'calc((100% - 5.5em) * 3 / 7)',\n maxWidth: '8em',\n },\n longSelect: {\n width: 'calc((100% - 5.5em) * 4 / 7)',\n minWidth: 'calc(100% - 13.5em)',\n marginLeft: '1em',\n },\n label: {\n width: '4.5em',\n },\n longLabel: {\n width: 'calc((100% - 5.5em) * 4 / 7)',\n minWidth: 'calc(100% - 14em)',\n },\n grid: {\n marginTop: spacing(1),\n marginBottom: spacing(1),\n },\n formControl: {\n marginRight: 0,\n },\n controlLabel: {\n width: '100%',\n },\n});\n\nconst MonthlyEditorBase = ({\n classes,\n getMessage,\n labelComponent: Label,\n textEditorComponent: TextEditor,\n selectComponent: Select,\n readOnly,\n appointmentData,\n formatDate,\n onFieldChange,\n firstDayOfWeek,\n ...restProps\n}) => {\n const [dayNumber, setDayNumber] = useState(appointmentData.startDate.getDate());\n const [stateWeekNumber, setStateWeekNumber] = useState(\n Math.trunc((appointmentData.startDate.getDate() - 1) / 7),\n );\n const [stateDayOfWeek, setStateDayOfWeek] = useState(appointmentData.startDate.getDay());\n\n const { rRule } = appointmentData;\n const recurrenceOptions = React.useMemo(() => getRecurrenceOptions(rRule) || {}, [rRule]);\n const changeByMonthDay = React.useCallback(nextByMonthDay => onFieldChange({\n rRule: handleStartDateChange(nextByMonthDay, recurrenceOptions),\n }), [recurrenceOptions]);\n\n const {\n dayOfWeek, weekNumber, dayNumberTextField, radioGroupValue: value,\n } = getRadioGroupDisplayData(\n recurrenceOptions, stateDayOfWeek, stateWeekNumber, dayNumber, 'onDayNumber', 'onDayOfWeek',\n );\n\n const changeWeekNumber = React.useCallback(nextWeekNumber => onFieldChange({\n rRule: handleToDayOfWeekChange(nextWeekNumber, dayOfWeek, recurrenceOptions),\n }), [recurrenceOptions, dayOfWeek]);\n const weekNumbers = React.useMemo(\n () => getWeekNumberLabels(getMessage), [getMessage],\n );\n\n const changeDayOfWeek = React.useCallback(nextDayOfWeek => onFieldChange({\n rRule: handleToDayOfWeekChange(weekNumber, nextDayOfWeek, recurrenceOptions),\n }), [recurrenceOptions, weekNumber]);\n const daysOfWeek = React.useMemo(\n () => getDaysOfWeek(formatDate, firstDayOfWeek), [formatDate, firstDayOfWeek],\n );\n\n const onDayNumberReadOnly = readOnly || value !== 'onDayNumber';\n const onDayOfWeekReadOnly = readOnly || value !== 'onDayOfWeek';\n\n const onRadioGroupValueChange = (event) => {\n switch (event.target.value) {\n case 'onDayNumber':\n setStateWeekNumber(weekNumber);\n setStateDayOfWeek(dayOfWeek);\n onFieldChange({\n rRule: changeRecurrenceOptions({\n ...recurrenceOptions, bymonthday: dayNumber, byweekday: undefined,\n }),\n });\n break;\n case 'onDayOfWeek':\n setDayNumber(recurrenceOptions.bymonthday || dayNumber);\n onFieldChange({\n rRule: handleToDayOfWeekChange(\n stateWeekNumber,\n stateDayOfWeek,\n recurrenceOptions,\n ),\n });\n break;\n default:\n break;\n }\n };\n\n return (\n \n }\n disabled={readOnly}\n label={(\n \n \n \n \n \n )}\n />\n }\n disabled={readOnly}\n label={(\n \n \n \n \n \n )}\n />\n \n );\n};\n\nMonthlyEditorBase.propTypes = {\n classes: PropTypes.object.isRequired,\n getMessage: PropTypes.func,\n onFieldChange: PropTypes.func,\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n readOnly: PropTypes.bool,\n formatDate: PropTypes.func.isRequired,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nMonthlyEditorBase.defaultProps = {\n getMessage: () => undefined,\n onFieldChange: () => undefined,\n readOnly: false,\n};\n\nexport const MonthlyEditor = withStyles(styles)(MonthlyEditorBase, { name: 'MonthlyEditor' });\n","import React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport FormControlLabel from '@material-ui/core/FormControlLabel';\nimport classNames from 'clsx';\nimport Radio from '@material-ui/core/Radio';\nimport Grid from '@material-ui/core/Grid';\nimport { NUMBER_EDITOR } from '@devexpress/dx-scheduler-core';\n\nconst styles = ({ spacing }) => ({\n textEditor: {\n width: 'calc((100% - 5.5em) * 4 / 7)',\n minWidth: 'calc(100% - 13.5em)',\n marginLeft: '1em',\n },\n label: {\n width: '4.5em',\n },\n select: {\n width: 'calc((100% - 5.5em) * 3 / 7)',\n maxWidth: '8em',\n },\n formControl: {\n marginRight: 0,\n marginTop: spacing(1),\n marginBottom: spacing(1),\n },\n controlLabel: {\n width: '100%',\n },\n});\n\nconst ChangeMonthEditorBase = React.memo(({\n classes,\n getMessage,\n labelComponent: Label,\n textEditorComponent: TextEditor,\n selectComponent: Select,\n readOnly,\n readOnlyEditors,\n month,\n changeMonth,\n months,\n dayNumber,\n changeByMonthDay,\n className,\n ...restProps\n}) => (\n }\n disabled={readOnly}\n {...restProps}\n label={(\n \n \n \n \n \n )}\n />\n));\n\nChangeMonthEditorBase.propTypes = {\n classes: PropTypes.object.isRequired,\n getMessage: PropTypes.func,\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n readOnly: PropTypes.bool,\n month: PropTypes.number.isRequired,\n changeMonth: PropTypes.func.isRequired,\n months: PropTypes.arrayOf(PropTypes.shape({\n id: PropTypes.number.isRequired,\n text: PropTypes.string.isRequired,\n })).isRequired,\n dayNumber: PropTypes.number.isRequired,\n changeByMonthDay: PropTypes.func.isRequired,\n className: PropTypes.string,\n readOnlyEditors: PropTypes.bool,\n};\n\nChangeMonthEditorBase.defaultProps = {\n getMessage: () => undefined,\n readOnly: false,\n className: undefined,\n readOnlyEditors: false,\n};\n\nexport const ChangeMonthEditor = withStyles(styles)(ChangeMonthEditorBase, { name: 'ChangeMonthEditor' });\n","import React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport FormControlLabel from '@material-ui/core/FormControlLabel';\nimport classNames from 'clsx';\nimport Radio from '@material-ui/core/Radio';\nimport Grid from '@material-ui/core/Grid';\n\nconst styles = ({ spacing }) => ({\n label: {\n width: '4.5em',\n },\n select: {\n width: 'calc((100% - 5.5em) * 3 / 7)',\n maxWidth: '8em',\n },\n longSelect: {\n width: 'calc((100% - 5.5em) * 4 / 7)',\n minWidth: 'calc(100% - 13.5em)',\n marginLeft: '1em',\n },\n formControlLabel: {\n alignItems: 'flex-start',\n },\n formControl: {\n marginRight: 0,\n marginTop: spacing(1),\n marginBottom: spacing(1),\n },\n doubleSelect: {\n marginLeft: '4.5em',\n width: 'calc(100% - 4.5em)',\n marginTop: spacing(1),\n },\n radioButton: {\n marginTop: spacing(0.75),\n },\n controlLabel: {\n width: '100%',\n },\n});\n\nconst ChangeWeekNumberEditorBase = React.memo(({\n classes,\n getMessage,\n labelComponent: Label,\n selectComponent: Select,\n readOnly,\n readOnlyEditors,\n className,\n weekNumber,\n weekNumbers,\n changeWeekNumber,\n month,\n months,\n changeMonth,\n dayOfWeek,\n daysOfWeek,\n changeDayOfWeek,\n ...restProps\n}) => (\n }\n disabled={readOnly}\n {...restProps}\n label={(\n \n \n \n \n \n \n \n
\n )}\n />\n));\n\nChangeWeekNumberEditorBase.propTypes = {\n classes: PropTypes.object.isRequired,\n getMessage: PropTypes.func,\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n readOnly: PropTypes.bool,\n month: PropTypes.number.isRequired,\n changeMonth: PropTypes.func.isRequired,\n months: PropTypes.arrayOf(PropTypes.shape({\n id: PropTypes.number.isRequired,\n text: PropTypes.string.isRequired,\n })).isRequired,\n weekNumber: PropTypes.number.isRequired,\n changeWeekNumber: PropTypes.func.isRequired,\n weekNumbers: PropTypes.arrayOf(PropTypes.shape({\n id: PropTypes.number.isRequired,\n text: PropTypes.string.isRequired,\n })).isRequired,\n dayOfWeek: PropTypes.number.isRequired,\n changeDayOfWeek: PropTypes.func.isRequired,\n daysOfWeek: PropTypes.arrayOf(PropTypes.shape({\n id: PropTypes.number.isRequired,\n text: PropTypes.string.isRequired,\n })).isRequired,\n className: PropTypes.string,\n readOnlyEditors: PropTypes.bool,\n};\n\nChangeWeekNumberEditorBase.defaultProps = {\n getMessage: () => undefined,\n readOnly: false,\n className: undefined,\n readOnlyEditors: false,\n};\n\nexport const ChangeWeekNumberEditor = withStyles(styles)(ChangeWeekNumberEditorBase, { name: 'ChangeWeekNumberEditor' });\n","import React, { useState } from 'react';\nimport * as PropTypes from 'prop-types';\nimport RadioGroup from '@material-ui/core/RadioGroup';\nimport {\n handleToDayOfWeekChange,\n getRecurrenceOptions,\n changeRecurrenceOptions,\n handleStartDateChange,\n getRadioGroupDisplayData,\n getWeekNumberLabels,\n getDaysOfWeek,\n getMonths,\n getMonthsWithOf,\n} from '@devexpress/dx-scheduler-core';\nimport { ChangeMonthEditor } from './change-month-editor';\nimport { ChangeWeekNumberEditor } from './change-week-number-editor';\n\nconst getCurrentMonth = (recurrenceOptions, appointmentData) => {\n if (recurrenceOptions.bymonth) {\n return recurrenceOptions.bymonth;\n }\n return appointmentData.startDate.getMonth() + 1;\n};\n\nexport const YearlyEditor = ({\n getMessage,\n labelComponent: Label,\n textEditorComponent: TextEditor,\n selectComponent: Select,\n readOnly,\n appointmentData,\n formatDate,\n onFieldChange,\n firstDayOfWeek,\n ...restProps\n}) => {\n const [dayNumber, setDayNumber] = useState(appointmentData.startDate.getDate());\n const [stateWeekNumber, setStateWeekNumber] = useState(\n Math.trunc((appointmentData.startDate.getDate() - 1) / 7),\n );\n const [stateDayOfWeek, setStateDayOfWeek] = useState(appointmentData.startDate.getDay());\n\n const { rRule } = appointmentData;\n const recurrenceOptions = React.useMemo(() => getRecurrenceOptions(rRule) || {}, [rRule]);\n const changeByMonthDay = React.useCallback(nextByMonthDay => onFieldChange({\n rRule: handleStartDateChange(nextByMonthDay, recurrenceOptions),\n }), [recurrenceOptions]);\n\n const {\n dayOfWeek, weekNumber, dayNumberTextField, radioGroupValue: value,\n } = getRadioGroupDisplayData(\n recurrenceOptions, stateDayOfWeek, stateWeekNumber, dayNumber, 'onDayAndMonth', 'onDayOfWeek',\n );\n const month = getCurrentMonth(recurrenceOptions, appointmentData);\n\n const changeMonth = React.useCallback(nextMonth => onFieldChange({\n rRule: changeRecurrenceOptions({\n ...recurrenceOptions, bymonth: nextMonth,\n }),\n }), [recurrenceOptions]);\n const months = React.useMemo(() => getMonths(formatDate), [formatDate]);\n const monthsWithOf = React.useMemo(\n () => getMonthsWithOf(getMessage, formatDate), [getMessage, formatDate],\n );\n\n const changeWeekNumber = React.useCallback(nextWeekNumber => onFieldChange({\n rRule: handleToDayOfWeekChange(nextWeekNumber, dayOfWeek, recurrenceOptions),\n }), [recurrenceOptions, dayOfWeek]);\n const weekNumbers = React.useMemo(\n () => getWeekNumberLabels(getMessage), [getMessage],\n );\n\n const changeDayOfWeek = React.useCallback(nextDayOfWeek => onFieldChange({\n rRule: handleToDayOfWeekChange(weekNumber, nextDayOfWeek, recurrenceOptions),\n }), [recurrenceOptions, weekNumber]);\n const daysOfWeek = React.useMemo(\n () => getDaysOfWeek(formatDate, firstDayOfWeek), [formatDate, firstDayOfWeek],\n );\n\n const onDayAndMonthReadOnly = readOnly || value !== 'onDayAndMonth';\n const onDayOfWeekReadOnly = readOnly || value !== 'onDayOfWeek';\n\n const onRadioGroupValueChange = (event) => {\n switch (event.target.value) {\n case 'onDayAndMonth':\n setStateWeekNumber(weekNumber);\n setStateDayOfWeek(dayOfWeek);\n onFieldChange({\n rRule: changeRecurrenceOptions({\n ...recurrenceOptions,\n bymonthday: dayNumber,\n byweekday: undefined,\n }),\n });\n break;\n case 'onDayOfWeek':\n setDayNumber(recurrenceOptions.bymonthday || dayNumber);\n onFieldChange({\n rRule: handleToDayOfWeekChange(\n stateWeekNumber,\n stateDayOfWeek,\n recurrenceOptions,\n ),\n });\n break;\n default:\n break;\n }\n };\n return (\n \n \n \n \n );\n};\n\nYearlyEditor.propTypes = {\n getMessage: PropTypes.func,\n onFieldChange: PropTypes.func,\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n formatDate: PropTypes.func.isRequired,\n readOnly: PropTypes.bool,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nYearlyEditor.defaultProps = {\n onFieldChange: () => undefined,\n getMessage: () => undefined,\n readOnly: false,\n};\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport {\n END_REPEAT_RADIO_GROUP,\n MONTHLY_RADIO_GROUP,\n YEARLY_RADIO_GROUP,\n} from '@devexpress/dx-scheduler-core';\nimport { EndRepeatEditor } from './end-repeat-editor';\nimport { MonthlyEditor } from './monthly-editor';\nimport { YearlyEditor } from './yealy-editor';\n\nexport const RadioGroup = ({\n dateEditorComponent,\n textEditorComponent,\n selectComponent,\n labelComponent,\n getMessage,\n readOnly,\n appointmentData,\n formatDate,\n onFieldChange,\n type,\n locale,\n firstDayOfWeek,\n ...restProps\n}) => {\n const commonProps = {\n readOnly,\n getMessage,\n textEditorComponent,\n labelComponent,\n appointmentData,\n onFieldChange,\n };\n switch (type) {\n case END_REPEAT_RADIO_GROUP:\n return (\n \n );\n case MONTHLY_RADIO_GROUP:\n return (\n \n );\n case YEARLY_RADIO_GROUP:\n return (\n \n );\n default:\n return () => null;\n }\n};\n\nRadioGroup.propTypes = {\n getMessage: PropTypes.func.isRequired,\n labelComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n textEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n dateEditorComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n selectComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n locale: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),\n readOnly: PropTypes.bool,\n type: PropTypes.string.isRequired,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }).isRequired,\n onFieldChange: PropTypes.func.isRequired,\n formatDate: PropTypes.func.isRequired,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nRadioGroup.defaultProps = {\n locale: undefined,\n readOnly: false,\n};\n","import React from 'react';\nimport Button from '@material-ui/core/Button';\nimport ButtonGroup from '@material-ui/core/ButtonGroup';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport classNames from 'clsx';\nimport {\n getRecurrenceOptions, WEEK_DAY_OPTIONS, handleWeekDaysChange, changeRecurrenceOptions,\n getDaysOfWeekArray, getDaysOfWeekDates,\n} from '@devexpress/dx-scheduler-core';\nimport { ensureColor } from '../../utils';\n\nconst styles = ({ palette, spacing }) => ({\n selectedButton: {\n backgroundColor: ensureColor(400, palette.primary),\n '&:hover': {\n backgroundColor: ensureColor(500, palette.primary),\n },\n border: `1px solid ${ensureColor(400, palette.primary)}!important`,\n borderLeft: `1px solid ${ensureColor(50, palette.primary)}!important`,\n '&:first-child': {\n borderLeft: `1px solid ${ensureColor(400, palette.primary)}!important`,\n },\n color: ensureColor(50, palette.primary),\n },\n button: {\n minWidth: spacing(3),\n },\n buttonGroup: {\n marginBottom: spacing(2),\n },\n});\n\nconst isCurrentWeekDay = (\n { byweekday }, currentWeekDay,\n) => byweekday && byweekday.findIndex(({ weekday }) => weekday === currentWeekDay) > -1;\n\nconst WeeklyRecurrenceSelectorBase = React.memo(({\n formatDate,\n rRule,\n readOnly,\n classes,\n className,\n onValueChange,\n firstDayOfWeek,\n ...restProps\n}) => {\n const recurrenceOptions = getRecurrenceOptions(rRule);\n const daysOfWeekArray = getDaysOfWeekArray(firstDayOfWeek);\n const daysOfWeekDates = getDaysOfWeekDates(firstDayOfWeek);\n\n return (\n \n {\n daysOfWeekArray.map((dayOfWeek, index) => (\n \n ))\n }\n \n );\n});\n\nWeeklyRecurrenceSelectorBase.propTypes = {\n formatDate: PropTypes.func.isRequired,\n classes: PropTypes.object.isRequired,\n rRule: PropTypes.string.isRequired,\n onValueChange: PropTypes.func,\n readOnly: PropTypes.bool,\n className: PropTypes.string,\n firstDayOfWeek: PropTypes.number.isRequired,\n};\n\nWeeklyRecurrenceSelectorBase.defaultProps = {\n onValueChange: () => undefined,\n readOnly: false,\n className: undefined,\n};\n\nexport const WeeklyRecurrenceSelector = withStyles(styles)(WeeklyRecurrenceSelectorBase, { name: 'WeeklyRecurrenceSelector' });\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport classNames from 'clsx';\nimport { withStyles } from '@material-ui/core/styles';\n\nconst styles = {\n container: {\n position: 'absolute',\n width: '100%',\n height: '100%',\n },\n};\n\nexport const OverlayContainerBase = React.forwardRef(({\n children, classes, className, ...restProps\n}, ref) => (\n \n {children}\n
\n));\n\nOverlayContainerBase.propTypes = {\n classes: PropTypes.object.isRequired,\n children: PropTypes.node,\n className: PropTypes.string,\n};\n\nOverlayContainerBase.defaultProps = {\n children: null,\n className: undefined,\n};\n\nexport const OverlayContainer = withStyles(styles, { name: 'OverlayContainer' })(OverlayContainerBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { makeStyles } from '@material-ui/core/styles';\nimport Chip from '@material-ui/core/Chip';\nimport Select from '@material-ui/core/Select';\nimport MenuItem from '@material-ui/core/MenuItem';\nimport classNames from 'clsx';\nimport { getAppointmentColor } from '../../utils';\n\nconst getResourceInstance = (resourceInstances, id) => resourceInstances\n .find(item => item.id === id);\n\nconst useStyles = makeStyles(({ spacing }) => ({\n select: {\n padding: spacing(1),\n },\n selectBox: {\n minHeight: spacing(6.5),\n width: '100%',\n },\n chips: {\n display: 'flex',\n flexWrap: 'wrap',\n },\n chip: {\n color: 'white',\n margin: 2,\n },\n resourceCircle: {\n height: spacing(2),\n width: spacing(2),\n borderRadius: '50%',\n marginRight: spacing(1),\n },\n itemContainer: {\n display: 'flex',\n padding: spacing(0.75),\n },\n circleContainer: {\n display: 'flex',\n alignItems: 'center',\n },\n}));\n\nexport const ResourceEditor = React.memo(({\n readOnly,\n resource,\n appointmentResources,\n onResourceChange,\n className,\n ...restProps\n}) => {\n const classes = useStyles();\n\n const values = appointmentResources.reduce((acc, resourceItem) => (\n resourceItem.fieldName === resource.fieldName\n ? [...acc, resourceItem.id]\n : acc),\n []);\n\n const onChange = (nextValue) => {\n onResourceChange({ [resource.fieldName]: nextValue });\n };\n\n return (\n \n );\n});\n\nResourceEditor.propTypes = {\n readOnly: PropTypes.bool,\n appointmentResources: PropTypes.array,\n onResourceChange: PropTypes.func,\n resource: PropTypes.object,\n className: PropTypes.string,\n};\n\nResourceEditor.defaultProps = {\n className: undefined,\n readOnly: false,\n appointmentResources: [],\n onResourceChange: () => undefined,\n resource: {},\n};\n","import { withComponents } from '@devexpress/dx-react-core';\nimport { AppointmentForm as AppointmentFormBase } from '@devexpress/dx-react-scheduler';\nimport { Layout } from '../templates/appointment-form/layout';\nimport { TextEditor } from '../templates/appointment-form/common/text-editor';\nimport { Layout as BasicLayout } from '../templates/appointment-form/basic/layout';\nimport { Layout as CommandLayout } from '../templates/appointment-form/command/layout';\nimport { CommandButton } from '../templates/appointment-form/command/command-button';\nimport { Overlay } from '../templates/appointment-form/overlay';\nimport { DateEditor } from '../templates/appointment-form/common/date-editor';\nimport { Label } from '../templates/appointment-form/common/label';\nimport { BooleanEditor } from '../templates/appointment-form/common/boolean-editor';\nimport { Select } from '../templates/common/select/select';\nimport { Layout as RecurrenceLayout } from '../templates/appointment-form/recurrence/layout';\nimport { RadioGroup } from '../templates/appointment-form/recurrence/radio-group/radio-group';\nimport { WeeklyRecurrenceSelector } from '../templates/appointment-form/recurrence/weekly-recurrence-selector';\nimport { OverlayContainer as Container } from '../templates/common/overlay-container';\nimport { ResourceEditor } from '../templates/appointment-form/basic/resource-editor';\n\nexport const AppointmentForm = withComponents({\n Overlay,\n Layout,\n TextEditor,\n BasicLayout,\n CommandLayout,\n CommandButton,\n DateEditor,\n Label,\n BooleanEditor,\n Select,\n RecurrenceLayout,\n RadioGroup,\n WeeklyRecurrenceSelector,\n Container,\n ResourceEditor,\n})(AppointmentFormBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport classNames from 'clsx';\nimport Repeat from '@material-ui/icons/Repeat';\nimport { POSITION_START, POSITION_END } from '@devexpress/dx-scheduler-core';\nimport { makeStyles } from '@material-ui/core/styles';\nimport { AppointmentContent } from '../appointment/appointment-content';\nimport { Appointment } from '../appointment/appointment';\nimport { SplitIndicator } from '../appointment/split-indicator';\nimport { getAppointmentColor, getResourceColor } from '../utils';\n\nconst draftStyles = makeStyles(theme => ({\n appointment: {\n boxShadow: theme.shadows[3],\n cursor: 'move',\n overflow: 'hidden',\n backgroundColor: resources => getAppointmentColor(\n 600, getResourceColor(resources), theme.palette.primary,\n ),\n border: 0,\n },\n shadedAppointment: {\n backgroundColor: resources => getAppointmentColor(\n 400, getResourceColor(resources), theme.palette.primary,\n ),\n },\n}));\n\nconst sourceStyles = makeStyles({\n appointment: {\n opacity: 0.5,\n },\n});\n\nexport const DraftAppointment = ({\n className, resources, isShaded, ...restProps\n}) => {\n const classes = draftStyles(resources);\n return (\n \n );\n};\n\nDraftAppointment.propTypes = {\n resources: PropTypes.array,\n className: PropTypes.string,\n isShaded: PropTypes.bool,\n};\n\nDraftAppointment.defaultProps = {\n className: undefined,\n resources: [],\n isShaded: false,\n};\n\nexport const SourceAppointment = ({ className, ...restProps }) => {\n const classes = sourceStyles();\n return (\n \n );\n};\n\nSourceAppointment.propTypes = {\n className: PropTypes.string,\n};\n\nSourceAppointment.defaultProps = {\n className: undefined,\n};\n\nconst AppointmentBase = ({\n className, data, formatDate, type, fromPrev,\n toNext, durationType, isShaded, ...restProps\n}) => (\n \n {fromPrev && }\n \n {toNext && }\n \n);\n\nAppointmentBase.propTypes = {\n data: PropTypes.object.isRequired,\n fromPrev: PropTypes.bool.isRequired,\n toNext: PropTypes.bool.isRequired,\n formatDate: PropTypes.func.isRequired,\n durationType: PropTypes.string,\n className: PropTypes.string,\n type: PropTypes.string,\n isShaded: PropTypes.bool,\n};\n\nAppointmentBase.defaultProps = {\n durationType: undefined,\n className: undefined,\n type: undefined,\n isShaded: false,\n};\n","import { withStyles } from '@material-ui/core/styles';\nimport { ContainerBase } from '../common/container';\n\nconst styles = {\n container: {\n position: 'absolute',\n left: 0,\n top: 0,\n height: '100%',\n width: '100%',\n cursor: 'move',\n },\n};\n\nexport const Container = withStyles(styles, { name: 'DragDropContainer' })(ContainerBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport classNames from 'clsx';\nimport {\n VERTICAL_TYPE, HORIZONTAL_TYPE,\n POSITION_START, POSITION_END,\n} from '@devexpress/dx-scheduler-core';\n\nconst verticalStyles = spacing => ({\n width: '100%',\n height: spacing(1),\n cursor: 'ns-resize',\n});\n\nconst horizontalStyles = spacing => ({\n width: spacing(1),\n height: '100%',\n cursor: 'ew-resize',\n});\n\nconst styles = ({ spacing }) => {\n const vertical = verticalStyles(spacing);\n const horizontal = horizontalStyles(spacing);\n return ({\n resize: {\n position: 'absolute',\n zIndex: 100,\n },\n verticalStart: {\n ...vertical,\n top: 0,\n },\n verticalEnd: {\n ...vertical,\n bottom: 0,\n },\n horizontalStart: {\n ...horizontal,\n left: 0,\n },\n horizontalEnd: {\n ...horizontal,\n right: 0,\n },\n });\n};\n\nconst ResizeBase = React.memo(({\n classes, className,\n position, appointmentType, ...restProps\n}) => {\n const vertical = appointmentType === VERTICAL_TYPE;\n const start = position === POSITION_START;\n return (\n \n );\n});\n\nResizeBase.propTypes = {\n classes: PropTypes.object.isRequired,\n position: PropTypes.oneOf([POSITION_START, POSITION_END]).isRequired,\n appointmentType: PropTypes.oneOf([HORIZONTAL_TYPE, VERTICAL_TYPE]).isRequired,\n className: PropTypes.string,\n};\n\nResizeBase.defaultProps = {\n className: undefined,\n};\n\nexport const Resize = withStyles(styles, { name: 'Resize' })(ResizeBase);\n","import { withComponents } from '@devexpress/dx-react-core';\nimport { DragDropProvider as DragDropProviderBase } from '@devexpress/dx-react-scheduler';\nimport { DraftAppointment, SourceAppointment } from '../templates/drag-drop/appointments';\nimport { Container } from '../templates/drag-drop/container';\nimport { Resize } from '../templates/drag-drop/resize';\n\nexport const DragDropProvider = withComponents({\n DraftAppointment, SourceAppointment, Container, Resize,\n})(DragDropProviderBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\nimport Button from '@material-ui/core/Button';\nimport classNames from 'clsx';\nimport { LAYOUT_MEDIA_QUERY } from '../constants';\n\nconst styles = ({ spacing }) => ({\n button: {\n padding: spacing(0.8, 2),\n marginLeft: spacing(0.5),\n '&:first-child': {\n marginLeft: 0,\n },\n [`${LAYOUT_MEDIA_QUERY}`]: {\n fontSize: '0.75rem',\n },\n },\n});\n\nconst TodayButtonBase = ({\n setCurrentDate, classes, getMessage, className, ...restProps\n}) => {\n const handleClick = () => {\n setCurrentDate(new Date());\n };\n return (\n \n );\n};\n\nTodayButtonBase.propTypes = {\n setCurrentDate: PropTypes.func.isRequired,\n classes: PropTypes.object.isRequired,\n className: PropTypes.string,\n getMessage: PropTypes.func.isRequired,\n};\n\nTodayButtonBase.defaultProps = {\n className: undefined,\n};\n\nexport const TodayButton = withStyles(styles)(TodayButtonBase, { name: 'TodayButton' });\n","import { withComponents } from '@devexpress/dx-react-core';\nimport { TodayButton as TodayButtonBase } from '@devexpress/dx-react-scheduler';\nimport { TodayButton as Button } from '../templates/today-button/today-button';\n\nexport const TodayButton = withComponents({ Button })(TodayButtonBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport classNames from 'clsx';\nimport Dialog from '@material-ui/core/Dialog';\nimport { withStyles } from '@material-ui/core/styles';\n\nconst styles = {\n modal: {\n position: 'absolute!important',\n },\n paper: {\n zIndex: '1302!important',\n },\n root: {\n zIndex: '1301!important',\n },\n};\n\nconst OverlayBase = ({\n children, visible, onHide, target, classes, className, ...restProps\n}) => (\n \n);\n\nOverlayBase.propTypes = {\n children: PropTypes.node.isRequired,\n classes: PropTypes.object.isRequired,\n onHide: PropTypes.func.isRequired,\n target: PropTypes.object.isRequired,\n visible: PropTypes.bool,\n className: PropTypes.string,\n};\n\nOverlayBase.defaultProps = {\n className: undefined,\n visible: false,\n};\n\nexport const Overlay = withStyles(styles, { name: 'Overlay' })(OverlayBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport DialogActions from '@material-ui/core/DialogActions';\nimport DialogContent from '@material-ui/core/DialogContent';\nimport DialogTitle from '@material-ui/core/DialogTitle';\nimport Radio from '@material-ui/core/Radio';\nimport RadioGroup from '@material-ui/core/RadioGroup';\nimport FormControlLabel from '@material-ui/core/FormControlLabel';\nimport { withStyles } from '@material-ui/core/styles';\nimport { SMALL_LAYOUT_MEDIA_QUERY } from '../constants';\n\nconst styles = ({ typography }) => ({\n title: typography.h6,\n content: {\n fontSize: '1rem',\n },\n [`${SMALL_LAYOUT_MEDIA_QUERY}`]: {\n title: {\n fontSize: '1.1rem',\n },\n content: {\n fontSize: '0.9rem',\n },\n },\n});\n\nconst LayoutBase = React.memo(({\n buttonComponent: Button,\n handleClose,\n commit,\n availableOperations,\n getMessage,\n isDeleting,\n classes,\n ...restProps\n}) => {\n const [currentValue, setCurrentValue] = React.useState(availableOperations[0].value);\n const handleChange = React.useCallback(\n (event) => {\n setCurrentValue(event.target.value);\n },\n );\n\n const onCommitButtonClick = () => {\n commit(currentValue);\n };\n\n return (\n \n \n {getMessage(isDeleting ? 'menuDeletingTitle' : 'menuEditingTitle')}\n \n \n \n {availableOperations.map(operation => (\n }\n label={operation.title}\n key={operation.value}\n classes={{ label: classes.content }}\n />\n ))}\n \n \n \n \n \n \n
\n );\n});\n\nLayoutBase.propTypes = {\n buttonComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n availableOperations: PropTypes.array.isRequired,\n handleClose: PropTypes.func,\n commit: PropTypes.func,\n getMessage: PropTypes.func,\n isDeleting: PropTypes.bool,\n classes: PropTypes.object.isRequired,\n};\n\nLayoutBase.defaultProps = {\n handleClose: () => undefined,\n commit: () => undefined,\n getMessage: () => undefined,\n isDeleting: false,\n};\n\nexport const Layout = withStyles(styles, { name: 'Layout' })(LayoutBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport ButtonMUI from '@material-ui/core/Button';\n\nexport const Button = ({\n onClick, title, ...restProps\n}) => (\n \n {title}\n \n);\n\nButton.propTypes = {\n onClick: PropTypes.func.isRequired,\n title: PropTypes.string,\n};\n\nButton.defaultProps = {\n title: '',\n};\n","import { withComponents } from '@devexpress/dx-react-core';\nimport { EditRecurrenceMenu as EditRecurrenceMenuBase } from '@devexpress/dx-react-scheduler';\nimport { Overlay } from '../templates/common/dialog/overlay';\nimport { Layout } from '../templates/edit-recurrence-menu/layout';\nimport { Button } from '../templates/common/dialog/button';\nimport { OverlayContainer as Container } from '../templates/common/overlay-container';\n\nexport const EditRecurrenceMenu = withComponents({\n Layout, Overlay, Button, Container,\n})(EditRecurrenceMenuBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport DialogActions from '@material-ui/core/DialogActions';\nimport DialogTitle from '@material-ui/core/DialogTitle';\nimport { withStyles } from '@material-ui/core/styles';\nimport { SMALL_LAYOUT_MEDIA_QUERY } from '../constants';\n\nconst styles = ({ typography }) => ({\n title: {\n ...typography.h6,\n },\n [`${SMALL_LAYOUT_MEDIA_QUERY}`]: {\n title: {\n fontSize: '1.1rem',\n },\n },\n});\n\nconst LayoutBase = React.memo(({\n buttonComponent: Button,\n handleCancel,\n handleConfirm,\n getMessage,\n isDeleting,\n appointmentData,\n classes,\n ...restProps\n}) => (\n \n \n {getMessage(isDeleting ? 'confirmDeleteMessage' : 'confirmCancelMessage')}\n \n \n \n \n \n
\n));\n\nLayoutBase.propTypes = {\n buttonComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n handleCancel: PropTypes.func,\n handleConfirm: PropTypes.func,\n getMessage: PropTypes.func,\n isDeleting: PropTypes.bool,\n appointmentData: PropTypes.shape({\n title: PropTypes.string,\n startDate: PropTypes.instanceOf(Date),\n endDate: PropTypes.instanceOf(Date),\n rRule: PropTypes.string,\n notes: PropTypes.string,\n additionalInformation: PropTypes.string,\n allDay: PropTypes.bool,\n }),\n classes: PropTypes.object.isRequired,\n};\n\nLayoutBase.defaultProps = {\n handleCancel: () => undefined,\n handleConfirm: () => undefined,\n getMessage: () => undefined,\n isDeleting: false,\n appointmentData: { startDate: new Date(), endDate: new Date() },\n};\n\nexport const Layout = withStyles(styles, { name: 'Layout' })(LayoutBase);\n","import { withComponents } from '@devexpress/dx-react-core';\nimport { ConfirmationDialog as ConfirmationDialogBase } from '@devexpress/dx-react-scheduler';\nimport { Overlay } from '../templates/common/dialog/overlay';\nimport { Layout } from '../templates/confirmation-dialog/layout';\nimport { OverlayContainer as Container } from '../templates/common/overlay-container';\nimport { Button } from '../templates/common/dialog/button';\n\nexport const ConfirmationDialog = withComponents({\n Overlay, Layout, Container, Button,\n})(ConfirmationDialogBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { makeStyles } from '@material-ui/core/styles';\nimport classNames from 'clsx';\n\nconst useStyles = makeStyles(theme => ({\n line: {\n height: '2px',\n width: '100%',\n transform: 'translate(0, -1px)',\n },\n circle: {\n width: theme.spacing(1.5),\n height: theme.spacing(1.5),\n borderRadius: '50%',\n transform: 'translate(-50%, -50%)',\n },\n nowIndicator: {\n position: 'absolute',\n left: 0,\n top: ({ top }) => top,\n background: theme.palette.secondary.main,\n zIndex: 1,\n },\n}));\n\nexport const Indicator = ({\n top, ...restProps\n}) => {\n const classes = useStyles({ top });\n\n return (\n \n );\n};\n\nIndicator.propTypes = {\n top: PropTypes.string,\n};\n\nIndicator.defaultProps = {\n top: 0,\n};\n","import { withComponents } from '@devexpress/dx-react-core';\nimport { CurrentTimeIndicator as CurrentTimeIndicatorBase } from '@devexpress/dx-react-scheduler';\nimport { Indicator } from '../templates/current-time-indicator/indicator';\n\nexport const CurrentTimeIndicator = withComponents({ Indicator })(CurrentTimeIndicatorBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { getCellKey, getRowFromGroups } from '@devexpress/dx-scheduler-core';\n\nexport const HorizontalLayout = ({\n rowComponent: Row,\n cellComponent: Cell,\n groups,\n colSpan,\n cellStyle,\n showHeaderForEveryDate,\n ...restProps\n}) => (\n <>\n {groups.map((groupRow, rowIndex) => {\n const cellColSpan = colSpan / groupRow.length;\n return (\n \n {!showHeaderForEveryDate && groupRow.map((group, index) => (\n | \n ))}\n {showHeaderForEveryDate && (\n getRowFromGroups(colSpan, groupRow, cellStyle, groups, rowIndex).map(({\n group, colSpan: columnSpan, key, endOfGroup,\n }) => (\n | \n ))\n )}\n
\n );\n })}\n >\n);\n\nHorizontalLayout.propTypes = {\n rowComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n cellComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n groups: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.object)).isRequired,\n colSpan: PropTypes.number.isRequired,\n cellStyle: PropTypes.object.isRequired,\n showHeaderForEveryDate: PropTypes.bool,\n};\n\nHorizontalLayout.defaultProps = {\n showHeaderForEveryDate: false,\n};\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport Table from '@material-ui/core/Table';\nimport TableBody from '@material-ui/core/TableBody';\nimport { withStyles } from '@material-ui/core/styles';\nimport classNames from 'clsx';\nimport {\n VERTICAL_GROUP_ORIENTATION, getVerticalRowFromGroups, getGroupsLastRow, VIEW_TYPES,\n} from '@devexpress/dx-scheduler-core';\nimport { BASIC_CELL_HEIGHT } from '../constants';\n\nconst styles = {\n layout: {\n width: 'auto',\n '&:only-child': {\n width: '100%',\n },\n },\n};\nconst allDayCellHeight = BASIC_CELL_HEIGHT[VIEW_TYPES.ALL_DAY_PANEL];\n\nconst VerticalLayoutBase = ({\n rowComponent: Row,\n cellComponent: Cell,\n groups,\n rowSpan,\n viewType,\n classes,\n className,\n cellTextTopOffset,\n alignWithAllDayRow,\n ...restProps\n}) => {\n const timeTableCellHeight = BASIC_CELL_HEIGHT[viewType];\n\n return (\n \n \n {getGroupsLastRow(groups).map((_, groupIndex) => (\n \n {getVerticalRowFromGroups(\n groups, groupIndex, rowSpan, timeTableCellHeight,\n alignWithAllDayRow, allDayCellHeight,\n ).map(({\n group: cellGroup,\n rowSpan: cellRowSpan,\n key, height,\n }) => (\n | \n ))}\n
\n ))}\n \n
\n );\n};\n\nVerticalLayoutBase.propTypes = {\n rowComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n cellComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n alignWithAllDayRow: PropTypes.bool,\n groups: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.object)).isRequired,\n rowSpan: PropTypes.number.isRequired,\n viewType: PropTypes.string.isRequired,\n cellTextTopOffset: PropTypes.number,\n className: PropTypes.string,\n classes: PropTypes.object.isRequired,\n};\n\nVerticalLayoutBase.defaultProps = {\n cellTextTopOffset: undefined,\n className: undefined,\n alignWithAllDayRow: false,\n};\n\nexport const VerticalLayout = withStyles(styles, { name: 'VerticalLayout' })(VerticalLayoutBase);\n","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport classNames from 'clsx';\nimport TableCell from '@material-ui/core/TableCell';\nimport { makeStyles } from '@material-ui/core/styles';\nimport { HORIZONTAL_GROUP_ORIENTATION, VERTICAL_GROUP_ORIENTATION } from '@devexpress/dx-scheduler-core';\nimport { getBrightBorder, getBorder } from '../utils';\nimport { GROUPING_PANEL_VERTICAL_CELL_WIDTH, DEFAULT_SPACING } from '../constants';\n\nconst useStyles = makeStyles(theme => ({\n cell: {\n userSelect: 'none',\n padding: 0,\n paddingTop: theme.spacing(0.5),\n boxSizing: 'border-box',\n borderRight: getBrightBorder(theme),\n '&:last-child': {\n borderRight: 'none',\n },\n height: ({ height }) => (\n height ? theme.spacing(height) : undefined\n ),\n },\n text: ({ textStyle, left }) => ({\n ...theme.typography.caption,\n padding: theme.spacing(1),\n color: theme.palette.text.secondary,\n fontWeight: 'bold',\n fontSize: '1rem',\n position: 'sticky',\n display: 'inline-block',\n left: `${left}px`,\n lineHeight: 1.5,\n whiteSpace: 'pre-wrap',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n boxSizing: 'border-box',\n ...textStyle,\n }),\n horizontalCell: {\n borderBottom: 'none',\n borderTop: getBrightBorder(theme),\n 'tr:first-child &': {\n borderTop: 'none',\n },\n },\n verticalCell: ({ rowSpan, height }) => ({\n borderBottom: getBrightBorder(theme),\n [`tr:nth-last-child(${rowSpan}) &`]: {\n borderBottom: 'none',\n },\n verticalAlign: 'top',\n paddingTop: 0,\n width: theme.spacing(GROUPING_PANEL_VERTICAL_CELL_WIDTH),\n minWidth: theme.spacing(GROUPING_PANEL_VERTICAL_CELL_WIDTH),\n maxWidth: theme.spacing(GROUPING_PANEL_VERTICAL_CELL_WIDTH),\n maxHeight: height ? theme.spacing(height - 2) : undefined,\n }),\n groupedByDate: {\n borderRight: ({ endOfGroup }) => (endOfGroup\n ? getBrightBorder(theme) : getBorder(theme)),\n borderTop: getBorder(theme),\n },\n verticalCellText: {\n top: ({ topOffset }) => `${topOffset}px`,\n width: '100%',\n },\n textContainer: {\n height: '100%',\n },\n}));\n\nexport const Cell = React.memo(({\n className,\n group,\n colSpan,\n rowSpan,\n left,\n endOfGroup,\n groupedByDate,\n children,\n height,\n groupOrientation,\n textStyle,\n topOffset,\n ...restProps\n}) => {\n const cellHeight = height / DEFAULT_SPACING;\n const classes = useStyles({\n left, endOfGroup, height: cellHeight, rowSpan, textStyle, topOffset,\n });\n const isHorizontalGrouping = groupOrientation === HORIZONTAL_GROUP_ORIENTATION;\n const isVerticalGrouping = groupOrientation === VERTICAL_GROUP_ORIENTATION;\n\n return (\n \n {/* NOTE: for sticky text in Safari */}\n \n
\n {group.text}\n {children}\n
\n
\n \n );\n});\n\nCell.propTypes = {\n className: PropTypes.string,\n group: PropTypes.object.isRequired,\n colSpan: PropTypes.number.isRequired,\n rowSpan: PropTypes.number,\n left: PropTypes.number.isRequired,\n endOfGroup: PropTypes.bool,\n groupedByDate: PropTypes.bool,\n height: PropTypes.number,\n groupOrientation: PropTypes.oneOf([HORIZONTAL_GROUP_ORIENTATION, VERTICAL_GROUP_ORIENTATION]),\n textStyle: PropTypes.object,\n topOffset: PropTypes.number,\n children: PropTypes.node,\n};\n\nCell.defaultProps = {\n className: undefined,\n endOfGroup: true,\n rowSpan: 1,\n height: 48,\n groupOrientation: HORIZONTAL_GROUP_ORIENTATION,\n children: null,\n groupedByDate: true,\n textStyle: {},\n topOffset: undefined,\n};\n","import { withComponents } from '@devexpress/dx-react-core';\nimport { GroupingPanel as GroupingPanelBase } from '@devexpress/dx-react-scheduler';\nimport { HorizontalLayout } from '../templates/grouping-panel/horizontal-layout';\nimport { VerticalLayout } from '../templates/grouping-panel/vertical-layout';\nimport { Cell } from '../templates/grouping-panel/cell';\nimport { Row } from '../templates/views/common/row';\n\nexport const GroupingPanel = withComponents({\n HorizontalLayout, VerticalLayout, Cell, Row,\n})(GroupingPanelBase);\n","import unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nexport default function _createForOfIteratorHelper(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n\n if (!it) {\n if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n\n var F = function F() {};\n\n return {\n s: F,\n n: function n() {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n },\n e: function e(_e) {\n throw _e;\n },\n f: F\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n\n var normalCompletion = true,\n didErr = false,\n err;\n return {\n s: function s() {\n it = it.call(o);\n },\n n: function n() {\n var step = it.next();\n normalCompletion = step.done;\n return step;\n },\n e: function e(_e2) {\n didErr = true;\n err = _e2;\n },\n f: function f() {\n try {\n if (!normalCompletion && it[\"return\"] != null) it[\"return\"]();\n } finally {\n if (didErr) throw err;\n }\n }\n };\n}","import arrayWithoutHoles from \"./arrayWithoutHoles.js\";\nimport iterableToArray from \"./iterableToArray.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableSpread from \"./nonIterableSpread.js\";\nexport default function _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return arrayLikeToArray(arr);\n}","export default function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}","export default function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","export default function toInteger(dirtyNumber) {\n if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {\n return NaN;\n }\n\n var number = Number(dirtyNumber);\n\n if (isNaN(number)) {\n return number;\n }\n\n return number < 0 ? Math.ceil(number) : Math.floor(number);\n}","import { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\n// It should to be noted that this function isn't equivalent to `text-transform: capitalize`.\n//\n// A strict capitalization should uppercase the first letter of each word a the sentence.\n// We only handle the first word.\nexport default function capitalize(string) {\n if (typeof string !== 'string') {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: capitalize(string) expects a string argument.\" : _formatMuiErrorMessage(7));\n }\n\n return string.charAt(0).toUpperCase() + string.slice(1);\n}","'use strict';\n\nfunction checkDCE() {\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n if (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'\n ) {\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // This branch is unreachable because this function is only called\n // in production, but the condition is true only in development.\n // Therefore if the branch is still here, dead code elimination wasn't\n // properly applied.\n // Don't change the message. React DevTools relies on it. Also make sure\n // this message doesn't occur elsewhere in this function, or it will cause\n // a false positive.\n throw new Error('^_^');\n }\n try {\n // Verify that the code above has been dead code eliminated (DCE'd).\n __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);\n } catch (err) {\n // DevTools shouldn't crash React, no matter what.\n // We should still report in case we break this code.\n console.error(err);\n }\n}\n\nif (process.env.NODE_ENV === 'production') {\n // DCE check should happen before ReactDOM bundle executes so that\n // DevTools can report bad minification during injection.\n checkDCE();\n module.exports = require('./cjs/react-dom.production.min.js');\n} else {\n module.exports = require('./cjs/react-dom.development.js');\n}\n",null,null,"/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"import _extends from '@babel/runtime/helpers/esm/extends';\nimport { jsx, keyframes, css as css$2, ClassNames } from '@emotion/react';\nimport _taggedTemplateLiteral from '@babel/runtime/helpers/esm/taggedTemplateLiteral';\nimport _objectWithoutProperties from '@babel/runtime/helpers/esm/objectWithoutProperties';\nimport _typeof from '@babel/runtime/helpers/esm/typeof';\nimport _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';\nimport _createClass from '@babel/runtime/helpers/esm/createClass';\nimport _inherits from '@babel/runtime/helpers/esm/inherits';\nimport _defineProperty$1 from '@babel/runtime/helpers/esm/defineProperty';\nimport { Component, createContext } from 'react';\nimport { createPortal } from 'react-dom';\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (enumerableOnly) {\n symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n }\n\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n}\n\nfunction _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}\n\nfunction _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (typeof call === \"object\" || typeof call === \"function\")) {\n return call;\n }\n\n return _assertThisInitialized(self);\n}\n\nfunction _createSuper(Derived) {\n var hasNativeReflectConstruct = _isNativeReflectConstruct();\n return function _createSuperInternal() {\n var Super = _getPrototypeOf(Derived),\n result;\n\n if (hasNativeReflectConstruct) {\n var NewTarget = _getPrototypeOf(this).constructor;\n result = Reflect.construct(Super, arguments, NewTarget);\n } else {\n result = Super.apply(this, arguments);\n }\n\n return _possibleConstructorReturn(this, result);\n };\n}\n\nvar _excluded$3 = [\"className\", \"clearValue\", \"cx\", \"getStyles\", \"getValue\", \"hasValue\", \"isMulti\", \"isRtl\", \"options\", \"selectOption\", \"selectProps\", \"setValue\", \"theme\"];\n// ==============================\n// NO OP\n// ==============================\nvar noop = function noop() {};\n// Class Name Prefixer\n// ==============================\n\n/**\n String representation of component state for styling with class names.\n\n Expects an array of strings OR a string/object pair:\n - className(['comp', 'comp-arg', 'comp-arg-2'])\n @returns 'react-select__comp react-select__comp-arg react-select__comp-arg-2'\n - className('comp', { some: true, state: false })\n @returns 'react-select__comp react-select__comp--some'\n*/\n\nfunction applyPrefixToName(prefix, name) {\n if (!name) {\n return prefix;\n } else if (name[0] === '-') {\n return prefix + name;\n } else {\n return prefix + '__' + name;\n }\n}\n\nfunction classNames(prefix, state, className) {\n var arr = [className];\n\n if (state && prefix) {\n for (var key in state) {\n if (state.hasOwnProperty(key) && state[key]) {\n arr.push(\"\".concat(applyPrefixToName(prefix, key)));\n }\n }\n }\n\n return arr.filter(function (i) {\n return i;\n }).map(function (i) {\n return String(i).trim();\n }).join(' ');\n} // ==============================\n// Clean Value\n// ==============================\n\nvar cleanValue = function cleanValue(value) {\n if (isArray(value)) return value.filter(Boolean);\n if (_typeof(value) === 'object' && value !== null) return [value];\n return [];\n}; // ==============================\n// Clean Common Props\n// ==============================\n\nvar cleanCommonProps = function cleanCommonProps(props) {\n //className\n props.className;\n props.clearValue;\n props.cx;\n props.getStyles;\n props.getValue;\n props.hasValue;\n props.isMulti;\n props.isRtl;\n props.options;\n props.selectOption;\n props.selectProps;\n props.setValue;\n props.theme;\n var innerProps = _objectWithoutProperties(props, _excluded$3);\n\n return _objectSpread2({}, innerProps);\n}; // ==============================\n// Handle Input Change\n// ==============================\n\nfunction handleInputChange(inputValue, actionMeta, onInputChange) {\n if (onInputChange) {\n var _newValue = onInputChange(inputValue, actionMeta);\n\n if (typeof _newValue === 'string') return _newValue;\n }\n\n return inputValue;\n} // ==============================\n// Scroll Helpers\n// ==============================\n\nfunction isDocumentElement(el) {\n return [document.documentElement, document.body, window].indexOf(el) > -1;\n} // Normalized Scroll Top\n// ------------------------------\n\nfunction getScrollTop(el) {\n if (isDocumentElement(el)) {\n return window.pageYOffset;\n }\n\n return el.scrollTop;\n}\nfunction scrollTo(el, top) {\n // with a scroll distance, we perform scroll on the element\n if (isDocumentElement(el)) {\n window.scrollTo(0, top);\n return;\n }\n\n el.scrollTop = top;\n} // Get Scroll Parent\n// ------------------------------\n\nfunction getScrollParent(element) {\n var style = getComputedStyle(element);\n var excludeStaticParent = style.position === 'absolute';\n var overflowRx = /(auto|scroll)/;\n if (style.position === 'fixed') return document.documentElement;\n\n for (var parent = element; parent = parent.parentElement;) {\n style = getComputedStyle(parent);\n\n if (excludeStaticParent && style.position === 'static') {\n continue;\n }\n\n if (overflowRx.test(style.overflow + style.overflowY + style.overflowX)) {\n return parent;\n }\n }\n\n return document.documentElement;\n} // Animated Scroll To\n// ------------------------------\n\n/**\n @param t: time (elapsed)\n @param b: initial value\n @param c: amount of change\n @param d: duration\n*/\n\nfunction easeOutCubic(t, b, c, d) {\n return c * ((t = t / d - 1) * t * t + 1) + b;\n}\n\nfunction animatedScrollTo(element, to) {\n var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 200;\n var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop;\n var start = getScrollTop(element);\n var change = to - start;\n var increment = 10;\n var currentTime = 0;\n\n function animateScroll() {\n currentTime += increment;\n var val = easeOutCubic(currentTime, start, change, duration);\n scrollTo(element, val);\n\n if (currentTime < duration) {\n window.requestAnimationFrame(animateScroll);\n } else {\n callback(element);\n }\n }\n\n animateScroll();\n} // Scroll Into View\n// ------------------------------\n\nfunction scrollIntoView(menuEl, focusedEl) {\n var menuRect = menuEl.getBoundingClientRect();\n var focusedRect = focusedEl.getBoundingClientRect();\n var overScroll = focusedEl.offsetHeight / 3;\n\n if (focusedRect.bottom + overScroll > menuRect.bottom) {\n scrollTo(menuEl, Math.min(focusedEl.offsetTop + focusedEl.clientHeight - menuEl.offsetHeight + overScroll, menuEl.scrollHeight));\n } else if (focusedRect.top - overScroll < menuRect.top) {\n scrollTo(menuEl, Math.max(focusedEl.offsetTop - overScroll, 0));\n }\n} // ==============================\n// Get bounding client object\n// ==============================\n// cannot get keys using array notation with DOMRect\n\nfunction getBoundingClientObj(element) {\n var rect = element.getBoundingClientRect();\n return {\n bottom: rect.bottom,\n height: rect.height,\n left: rect.left,\n right: rect.right,\n top: rect.top,\n width: rect.width\n };\n}\n// Touch Capability Detector\n// ==============================\n\nfunction isTouchCapable() {\n try {\n document.createEvent('TouchEvent');\n return true;\n } catch (e) {\n return false;\n }\n} // ==============================\n// Mobile Device Detector\n// ==============================\n\nfunction isMobileDevice() {\n try {\n return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);\n } catch (e) {\n return false;\n }\n} // ==============================\n// Passive Event Detector\n// ==============================\n// https://github.com/rafgraph/detect-it/blob/main/src/index.ts#L19-L36\n\nvar passiveOptionAccessed = false;\nvar options = {\n get passive() {\n return passiveOptionAccessed = true;\n }\n\n}; // check for SSR\n\nvar w = typeof window !== 'undefined' ? window : {};\n\nif (w.addEventListener && w.removeEventListener) {\n w.addEventListener('p', noop, options);\n w.removeEventListener('p', noop, false);\n}\n\nvar supportsPassiveEvents = passiveOptionAccessed;\nfunction notNullish(item) {\n return item != null;\n}\nfunction isArray(arg) {\n return Array.isArray(arg);\n}\nfunction valueTernary(isMulti, multiValue, singleValue) {\n return isMulti ? multiValue : singleValue;\n}\nfunction singleValueAsValue(singleValue) {\n return singleValue;\n}\nfunction multiValueAsValue(multiValue) {\n return multiValue;\n}\n\nfunction getMenuPlacement(_ref) {\n var maxHeight = _ref.maxHeight,\n menuEl = _ref.menuEl,\n minHeight = _ref.minHeight,\n placement = _ref.placement,\n shouldScroll = _ref.shouldScroll,\n isFixedPosition = _ref.isFixedPosition,\n theme = _ref.theme;\n var spacing = theme.spacing;\n var scrollParent = getScrollParent(menuEl);\n var defaultState = {\n placement: 'bottom',\n maxHeight: maxHeight\n }; // something went wrong, return default state\n\n if (!menuEl || !menuEl.offsetParent) return defaultState; // we can't trust `scrollParent.scrollHeight` --> it may increase when\n // the menu is rendered\n\n var _scrollParent$getBoun = scrollParent.getBoundingClientRect(),\n scrollHeight = _scrollParent$getBoun.height;\n\n var _menuEl$getBoundingCl = menuEl.getBoundingClientRect(),\n menuBottom = _menuEl$getBoundingCl.bottom,\n menuHeight = _menuEl$getBoundingCl.height,\n menuTop = _menuEl$getBoundingCl.top;\n\n var _menuEl$offsetParent$ = menuEl.offsetParent.getBoundingClientRect(),\n containerTop = _menuEl$offsetParent$.top;\n\n var viewHeight = window.innerHeight;\n var scrollTop = getScrollTop(scrollParent);\n var marginBottom = parseInt(getComputedStyle(menuEl).marginBottom, 10);\n var marginTop = parseInt(getComputedStyle(menuEl).marginTop, 10);\n var viewSpaceAbove = containerTop - marginTop;\n var viewSpaceBelow = viewHeight - menuTop;\n var scrollSpaceAbove = viewSpaceAbove + scrollTop;\n var scrollSpaceBelow = scrollHeight - scrollTop - menuTop;\n var scrollDown = menuBottom - viewHeight + scrollTop + marginBottom;\n var scrollUp = scrollTop + menuTop - marginTop;\n var scrollDuration = 160;\n\n switch (placement) {\n case 'auto':\n case 'bottom':\n // 1: the menu will fit, do nothing\n if (viewSpaceBelow >= menuHeight) {\n return {\n placement: 'bottom',\n maxHeight: maxHeight\n };\n } // 2: the menu will fit, if scrolled\n\n\n if (scrollSpaceBelow >= menuHeight && !isFixedPosition) {\n if (shouldScroll) {\n animatedScrollTo(scrollParent, scrollDown, scrollDuration);\n }\n\n return {\n placement: 'bottom',\n maxHeight: maxHeight\n };\n } // 3: the menu will fit, if constrained\n\n\n if (!isFixedPosition && scrollSpaceBelow >= minHeight || isFixedPosition && viewSpaceBelow >= minHeight) {\n if (shouldScroll) {\n animatedScrollTo(scrollParent, scrollDown, scrollDuration);\n } // we want to provide as much of the menu as possible to the user,\n // so give them whatever is available below rather than the minHeight.\n\n\n var constrainedHeight = isFixedPosition ? viewSpaceBelow - marginBottom : scrollSpaceBelow - marginBottom;\n return {\n placement: 'bottom',\n maxHeight: constrainedHeight\n };\n } // 4. Forked beviour when there isn't enough space below\n // AUTO: flip the menu, render above\n\n\n if (placement === 'auto' || isFixedPosition) {\n // may need to be constrained after flipping\n var _constrainedHeight = maxHeight;\n var spaceAbove = isFixedPosition ? viewSpaceAbove : scrollSpaceAbove;\n\n if (spaceAbove >= minHeight) {\n _constrainedHeight = Math.min(spaceAbove - marginBottom - spacing.controlHeight, maxHeight);\n }\n\n return {\n placement: 'top',\n maxHeight: _constrainedHeight\n };\n } // BOTTOM: allow browser to increase scrollable area and immediately set scroll\n\n\n if (placement === 'bottom') {\n if (shouldScroll) {\n scrollTo(scrollParent, scrollDown);\n }\n\n return {\n placement: 'bottom',\n maxHeight: maxHeight\n };\n }\n\n break;\n\n case 'top':\n // 1: the menu will fit, do nothing\n if (viewSpaceAbove >= menuHeight) {\n return {\n placement: 'top',\n maxHeight: maxHeight\n };\n } // 2: the menu will fit, if scrolled\n\n\n if (scrollSpaceAbove >= menuHeight && !isFixedPosition) {\n if (shouldScroll) {\n animatedScrollTo(scrollParent, scrollUp, scrollDuration);\n }\n\n return {\n placement: 'top',\n maxHeight: maxHeight\n };\n } // 3: the menu will fit, if constrained\n\n\n if (!isFixedPosition && scrollSpaceAbove >= minHeight || isFixedPosition && viewSpaceAbove >= minHeight) {\n var _constrainedHeight2 = maxHeight; // we want to provide as much of the menu as possible to the user,\n // so give them whatever is available below rather than the minHeight.\n\n if (!isFixedPosition && scrollSpaceAbove >= minHeight || isFixedPosition && viewSpaceAbove >= minHeight) {\n _constrainedHeight2 = isFixedPosition ? viewSpaceAbove - marginTop : scrollSpaceAbove - marginTop;\n }\n\n if (shouldScroll) {\n animatedScrollTo(scrollParent, scrollUp, scrollDuration);\n }\n\n return {\n placement: 'top',\n maxHeight: _constrainedHeight2\n };\n } // 4. not enough space, the browser WILL NOT increase scrollable area when\n // absolutely positioned element rendered above the viewport (only below).\n // Flip the menu, render below\n\n\n return {\n placement: 'bottom',\n maxHeight: maxHeight\n };\n\n default:\n throw new Error(\"Invalid placement provided \\\"\".concat(placement, \"\\\".\"));\n }\n\n return defaultState;\n} // Menu Component\n// ------------------------------\n\nfunction alignToControl(placement) {\n var placementToCSSProp = {\n bottom: 'top',\n top: 'bottom'\n };\n return placement ? placementToCSSProp[placement] : 'bottom';\n}\n\nvar coercePlacement = function coercePlacement(p) {\n return p === 'auto' ? 'bottom' : p;\n};\n\nvar menuCSS = function menuCSS(_ref2) {\n var _ref3;\n\n var placement = _ref2.placement,\n _ref2$theme = _ref2.theme,\n borderRadius = _ref2$theme.borderRadius,\n spacing = _ref2$theme.spacing,\n colors = _ref2$theme.colors;\n return _ref3 = {\n label: 'menu'\n }, _defineProperty$1(_ref3, alignToControl(placement), '100%'), _defineProperty$1(_ref3, \"backgroundColor\", colors.neutral0), _defineProperty$1(_ref3, \"borderRadius\", borderRadius), _defineProperty$1(_ref3, \"boxShadow\", '0 0 0 1px hsla(0, 0%, 0%, 0.1), 0 4px 11px hsla(0, 0%, 0%, 0.1)'), _defineProperty$1(_ref3, \"marginBottom\", spacing.menuGutter), _defineProperty$1(_ref3, \"marginTop\", spacing.menuGutter), _defineProperty$1(_ref3, \"position\", 'absolute'), _defineProperty$1(_ref3, \"width\", '100%'), _defineProperty$1(_ref3, \"zIndex\", 1), _ref3;\n};\nvar PortalPlacementContext = /*#__PURE__*/createContext({\n getPortalPlacement: null\n}); // NOTE: internal only\n\nvar MenuPlacer = /*#__PURE__*/function (_Component) {\n _inherits(MenuPlacer, _Component);\n\n var _super = _createSuper(MenuPlacer);\n\n function MenuPlacer() {\n var _this;\n\n _classCallCheck(this, MenuPlacer);\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _super.call.apply(_super, [this].concat(args));\n _this.state = {\n maxHeight: _this.props.maxMenuHeight,\n placement: null\n };\n _this.context = void 0;\n\n _this.getPlacement = function (ref) {\n var _this$props = _this.props,\n minMenuHeight = _this$props.minMenuHeight,\n maxMenuHeight = _this$props.maxMenuHeight,\n menuPlacement = _this$props.menuPlacement,\n menuPosition = _this$props.menuPosition,\n menuShouldScrollIntoView = _this$props.menuShouldScrollIntoView,\n theme = _this$props.theme;\n if (!ref) return; // DO NOT scroll if position is fixed\n\n var isFixedPosition = menuPosition === 'fixed';\n var shouldScroll = menuShouldScrollIntoView && !isFixedPosition;\n var state = getMenuPlacement({\n maxHeight: maxMenuHeight,\n menuEl: ref,\n minHeight: minMenuHeight,\n placement: menuPlacement,\n shouldScroll: shouldScroll,\n isFixedPosition: isFixedPosition,\n theme: theme\n });\n var getPortalPlacement = _this.context.getPortalPlacement;\n if (getPortalPlacement) getPortalPlacement(state);\n\n _this.setState(state);\n };\n\n _this.getUpdatedProps = function () {\n var menuPlacement = _this.props.menuPlacement;\n var placement = _this.state.placement || coercePlacement(menuPlacement);\n return _objectSpread2(_objectSpread2({}, _this.props), {}, {\n placement: placement,\n maxHeight: _this.state.maxHeight\n });\n };\n\n return _this;\n }\n\n _createClass(MenuPlacer, [{\n key: \"render\",\n value: function render() {\n var children = this.props.children;\n return children({\n ref: this.getPlacement,\n placerProps: this.getUpdatedProps()\n });\n }\n }]);\n\n return MenuPlacer;\n}(Component);\nMenuPlacer.contextType = PortalPlacementContext;\n\nvar Menu = function Menu(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerRef = props.innerRef,\n innerProps = props.innerProps;\n return jsx(\"div\", _extends({\n css: getStyles('menu', props),\n className: cx({\n menu: true\n }, className),\n ref: innerRef\n }, innerProps), children);\n};\n// Menu List\n// ==============================\n\nvar menuListCSS = function menuListCSS(_ref4) {\n var maxHeight = _ref4.maxHeight,\n baseUnit = _ref4.theme.spacing.baseUnit;\n return {\n maxHeight: maxHeight,\n overflowY: 'auto',\n paddingBottom: baseUnit,\n paddingTop: baseUnit,\n position: 'relative',\n // required for offset[Height, Top] > keyboard scroll\n WebkitOverflowScrolling: 'touch'\n };\n};\nvar MenuList = function MenuList(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps,\n innerRef = props.innerRef,\n isMulti = props.isMulti;\n return jsx(\"div\", _extends({\n css: getStyles('menuList', props),\n className: cx({\n 'menu-list': true,\n 'menu-list--is-multi': isMulti\n }, className),\n ref: innerRef\n }, innerProps), children);\n}; // ==============================\n// Menu Notices\n// ==============================\n\nvar noticeCSS = function noticeCSS(_ref5) {\n var _ref5$theme = _ref5.theme,\n baseUnit = _ref5$theme.spacing.baseUnit,\n colors = _ref5$theme.colors;\n return {\n color: colors.neutral40,\n padding: \"\".concat(baseUnit * 2, \"px \").concat(baseUnit * 3, \"px\"),\n textAlign: 'center'\n };\n};\n\nvar noOptionsMessageCSS = noticeCSS;\nvar loadingMessageCSS = noticeCSS;\nvar NoOptionsMessage = function NoOptionsMessage(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps;\n return jsx(\"div\", _extends({\n css: getStyles('noOptionsMessage', props),\n className: cx({\n 'menu-notice': true,\n 'menu-notice--no-options': true\n }, className)\n }, innerProps), children);\n};\nNoOptionsMessage.defaultProps = {\n children: 'No options'\n};\nvar LoadingMessage = function LoadingMessage(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps;\n return jsx(\"div\", _extends({\n css: getStyles('loadingMessage', props),\n className: cx({\n 'menu-notice': true,\n 'menu-notice--loading': true\n }, className)\n }, innerProps), children);\n};\nLoadingMessage.defaultProps = {\n children: 'Loading...'\n}; // ==============================\n// Menu Portal\n// ==============================\n\nvar menuPortalCSS = function menuPortalCSS(_ref6) {\n var rect = _ref6.rect,\n offset = _ref6.offset,\n position = _ref6.position;\n return {\n left: rect.left,\n position: position,\n top: offset,\n width: rect.width,\n zIndex: 1\n };\n};\nvar MenuPortal = /*#__PURE__*/function (_Component2) {\n _inherits(MenuPortal, _Component2);\n\n var _super2 = _createSuper(MenuPortal);\n\n function MenuPortal() {\n var _this2;\n\n _classCallCheck(this, MenuPortal);\n\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n _this2 = _super2.call.apply(_super2, [this].concat(args));\n _this2.state = {\n placement: null\n };\n\n _this2.getPortalPlacement = function (_ref7) {\n var placement = _ref7.placement;\n var initialPlacement = coercePlacement(_this2.props.menuPlacement); // avoid re-renders if the placement has not changed\n\n if (placement !== initialPlacement) {\n _this2.setState({\n placement: placement\n });\n }\n };\n\n return _this2;\n }\n\n _createClass(MenuPortal, [{\n key: \"render\",\n value: function render() {\n var _this$props2 = this.props,\n appendTo = _this$props2.appendTo,\n children = _this$props2.children,\n className = _this$props2.className,\n controlElement = _this$props2.controlElement,\n cx = _this$props2.cx,\n innerProps = _this$props2.innerProps,\n menuPlacement = _this$props2.menuPlacement,\n position = _this$props2.menuPosition,\n getStyles = _this$props2.getStyles;\n var isFixed = position === 'fixed'; // bail early if required elements aren't present\n\n if (!appendTo && !isFixed || !controlElement) {\n return null;\n }\n\n var placement = this.state.placement || coercePlacement(menuPlacement);\n var rect = getBoundingClientObj(controlElement);\n var scrollDistance = isFixed ? 0 : window.pageYOffset;\n var offset = rect[placement] + scrollDistance;\n var state = {\n offset: offset,\n position: position,\n rect: rect\n }; // same wrapper element whether fixed or portalled\n\n var menuWrapper = jsx(\"div\", _extends({\n css: getStyles('menuPortal', state),\n className: cx({\n 'menu-portal': true\n }, className)\n }, innerProps), children);\n return jsx(PortalPlacementContext.Provider, {\n value: {\n getPortalPlacement: this.getPortalPlacement\n }\n }, appendTo ? /*#__PURE__*/createPortal(menuWrapper, appendTo) : menuWrapper);\n }\n }]);\n\n return MenuPortal;\n}(Component);\n\nvar containerCSS = function containerCSS(_ref) {\n var isDisabled = _ref.isDisabled,\n isRtl = _ref.isRtl;\n return {\n label: 'container',\n direction: isRtl ? 'rtl' : undefined,\n pointerEvents: isDisabled ? 'none' : undefined,\n // cancel mouse events when disabled\n position: 'relative'\n };\n};\nvar SelectContainer = function SelectContainer(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps,\n isDisabled = props.isDisabled,\n isRtl = props.isRtl;\n return jsx(\"div\", _extends({\n css: getStyles('container', props),\n className: cx({\n '--is-disabled': isDisabled,\n '--is-rtl': isRtl\n }, className)\n }, innerProps), children);\n}; // ==============================\n// Value Container\n// ==============================\n\nvar valueContainerCSS = function valueContainerCSS(_ref2) {\n var spacing = _ref2.theme.spacing,\n isMulti = _ref2.isMulti,\n hasValue = _ref2.hasValue,\n controlShouldRenderValue = _ref2.selectProps.controlShouldRenderValue;\n return {\n alignItems: 'center',\n display: isMulti && hasValue && controlShouldRenderValue ? 'flex' : 'grid',\n flex: 1,\n flexWrap: 'wrap',\n padding: \"\".concat(spacing.baseUnit / 2, \"px \").concat(spacing.baseUnit * 2, \"px\"),\n WebkitOverflowScrolling: 'touch',\n position: 'relative',\n overflow: 'hidden'\n };\n};\nvar ValueContainer = function ValueContainer(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n innerProps = props.innerProps,\n isMulti = props.isMulti,\n getStyles = props.getStyles,\n hasValue = props.hasValue;\n return jsx(\"div\", _extends({\n css: getStyles('valueContainer', props),\n className: cx({\n 'value-container': true,\n 'value-container--is-multi': isMulti,\n 'value-container--has-value': hasValue\n }, className)\n }, innerProps), children);\n}; // ==============================\n// Indicator Container\n// ==============================\n\nvar indicatorsContainerCSS = function indicatorsContainerCSS() {\n return {\n alignItems: 'center',\n alignSelf: 'stretch',\n display: 'flex',\n flexShrink: 0\n };\n};\nvar IndicatorsContainer = function IndicatorsContainer(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n innerProps = props.innerProps,\n getStyles = props.getStyles;\n return jsx(\"div\", _extends({\n css: getStyles('indicatorsContainer', props),\n className: cx({\n indicators: true\n }, className)\n }, innerProps), children);\n};\n\nvar _templateObject;\n\nvar _excluded$2 = [\"size\"];\n\nfunction _EMOTION_STRINGIFIED_CSS_ERROR__() { return \"You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop).\"; }\n\nvar _ref2 = process.env.NODE_ENV === \"production\" ? {\n name: \"8mmkcg\",\n styles: \"display:inline-block;fill:currentColor;line-height:1;stroke:currentColor;stroke-width:0\"\n} : {\n name: \"tj5bde-Svg\",\n styles: \"display:inline-block;fill:currentColor;line-height:1;stroke:currentColor;stroke-width:0;label:Svg;\",\n map: \"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGljYXRvcnMudHN4Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQXdCSSIsImZpbGUiOiJpbmRpY2F0b3JzLnRzeCIsInNvdXJjZXNDb250ZW50IjpbIi8qKiBAanN4IGpzeCAqL1xuaW1wb3J0IHsgUmVhY3ROb2RlIH0gZnJvbSAncmVhY3QnO1xuaW1wb3J0IHsganN4LCBrZXlmcmFtZXMgfSBmcm9tICdAZW1vdGlvbi9yZWFjdCc7XG5cbmltcG9ydCB7XG4gIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lLFxuICBDU1NPYmplY3RXaXRoTGFiZWwsXG4gIEdyb3VwQmFzZSxcbn0gZnJvbSAnLi4vdHlwZXMnO1xuXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cbi8vIERyb3Bkb3duICYgQ2xlYXIgSWNvbnNcbi8vID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVxuXG5jb25zdCBTdmcgPSAoe1xuICBzaXplLFxuICAuLi5wcm9wc1xufTogSlNYLkludHJpbnNpY0VsZW1lbnRzWydzdmcnXSAmIHsgc2l6ZTogbnVtYmVyIH0pID0+IChcbiAgPHN2Z1xuICAgIGhlaWdodD17c2l6ZX1cbiAgICB3aWR0aD17c2l6ZX1cbiAgICB2aWV3Qm94PVwiMCAwIDIwIDIwXCJcbiAgICBhcmlhLWhpZGRlbj1cInRydWVcIlxuICAgIGZvY3VzYWJsZT1cImZhbHNlXCJcbiAgICBjc3M9e3tcbiAgICAgIGRpc3BsYXk6ICdpbmxpbmUtYmxvY2snLFxuICAgICAgZmlsbDogJ2N1cnJlbnRDb2xvcicsXG4gICAgICBsaW5lSGVpZ2h0OiAxLFxuICAgICAgc3Ryb2tlOiAnY3VycmVudENvbG9yJyxcbiAgICAgIHN0cm9rZVdpZHRoOiAwLFxuICAgIH19XG4gICAgey4uLnByb3BzfVxuICAvPlxuKTtcblxuZXhwb3J0IHR5cGUgQ3Jvc3NJY29uUHJvcHMgPSBKU1guSW50cmluc2ljRWxlbWVudHNbJ3N2ZyddICYgeyBzaXplPzogbnVtYmVyIH07XG5leHBvcnQgY29uc3QgQ3Jvc3NJY29uID0gKHByb3BzOiBDcm9zc0ljb25Qcm9wcykgPT4gKFxuICA8U3ZnIHNpemU9ezIwfSB7Li4ucHJvcHN9PlxuICAgIDxwYXRoIGQ9XCJNMTQuMzQ4IDE0Ljg0OWMtMC40NjkgMC40NjktMS4yMjkgMC40NjktMS42OTcgMGwtMi42NTEtMy4wMzAtMi42NTEgMy4wMjljLTAuNDY5IDAuNDY5LTEuMjI5IDAuNDY5LTEuNjk3IDAtMC40NjktMC40NjktMC40NjktMS4yMjkgMC0xLjY5N2wyLjc1OC0zLjE1LTIuNzU5LTMuMTUyYy0wLjQ2OS0wLjQ2OS0wLjQ2OS0xLjIyOCAwLTEuNjk3czEuMjI4LTAuNDY5IDEuNjk3IDBsMi42NTIgMy4wMzEgMi42NTEtMy4wMzFjMC40NjktMC40NjkgMS4yMjgtMC40NjkgMS42OTcgMHMwLjQ2OSAxLjIyOSAwIDEuNjk3bC0yLjc1OCAzLjE1MiAyLjc1OCAzLjE1YzAuNDY5IDAuNDY5IDAuNDY5IDEuMjI5IDAgMS42OTh6XCIgLz5cbiAgPC9Tdmc+XG4pO1xuZXhwb3J0IHR5cGUgRG93bkNoZXZyb25Qcm9wcyA9IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snc3ZnJ10gJiB7IHNpemU/OiBudW1iZXIgfTtcbmV4cG9ydCBjb25zdCBEb3duQ2hldnJvbiA9IChwcm9wczogRG93bkNoZXZyb25Qcm9wcykgPT4gKFxuICA8U3ZnIHNpemU9ezIwfSB7Li4ucHJvcHN9PlxuICAgIDxwYXRoIGQ9XCJNNC41MTYgNy41NDhjMC40MzYtMC40NDYgMS4wNDMtMC40ODEgMS41NzYgMGwzLjkwOCAzLjc0NyAzLjkwOC0zLjc0N2MwLjUzMy0wLjQ4MSAxLjE0MS0wLjQ0NiAxLjU3NCAwIDAuNDM2IDAuNDQ1IDAuNDA4IDEuMTk3IDAgMS42MTUtMC40MDYgMC40MTgtNC42OTUgNC41MDItNC42OTUgNC41MDItMC4yMTcgMC4yMjMtMC41MDIgMC4zMzUtMC43ODcgMC4zMzVzLTAuNTctMC4xMTItMC43ODktMC4zMzVjMCAwLTQuMjg3LTQuMDg0LTQuNjk1LTQuNTAycy0wLjQzNi0xLjE3IDAtMS42MTV6XCIgLz5cbiAgPC9Tdmc+XG4pO1xuXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cbi8vIERyb3Bkb3duICYgQ2xlYXIgQnV0dG9uc1xuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG5cbmV4cG9ydCBpbnRlcmZhY2UgRHJvcGRvd25JbmRpY2F0b3JQcm9wczxcbiAgT3B0aW9uID0gdW5rbm93bixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4gPSBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+ID0gR3JvdXBCYXNlPE9wdGlvbj5cbj4gZXh0ZW5kcyBDb21tb25Qcm9wc0FuZENsYXNzTmFtZTxPcHRpb24sIElzTXVsdGksIEdyb3VwPiB7XG4gIC8qKiBUaGUgY2hpbGRyZW4gdG8gYmUgcmVuZGVyZWQgaW5zaWRlIHRoZSBpbmRpY2F0b3IuICovXG4gIGNoaWxkcmVuPzogUmVhY3ROb2RlO1xuICAvKiogUHJvcHMgdGhhdCB3aWxsIGJlIHBhc3NlZCBvbiB0byB0aGUgY2hpbGRyZW4uICovXG4gIGlubmVyUHJvcHM6IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snZGl2J107XG4gIC8qKiBUaGUgZm9jdXNlZCBzdGF0ZSBvZiB0aGUgc2VsZWN0LiAqL1xuICBpc0ZvY3VzZWQ6IGJvb2xlYW47XG4gIGlzRGlzYWJsZWQ6IGJvb2xlYW47XG59XG5cbmNvbnN0IGJhc2VDU1MgPSA8XG4gIE9wdGlvbixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj5cbj4oe1xuICBpc0ZvY3VzZWQsXG4gIHRoZW1lOiB7XG4gICAgc3BhY2luZzogeyBiYXNlVW5pdCB9LFxuICAgIGNvbG9ycyxcbiAgfSxcbn06XG4gIHwgRHJvcGRvd25JbmRpY2F0b3JQcm9wczxPcHRpb24sIElzTXVsdGksIEdyb3VwPlxuICB8IENsZWFySW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD4pOiBDU1NPYmplY3RXaXRoTGFiZWwgPT4gKHtcbiAgbGFiZWw6ICdpbmRpY2F0b3JDb250YWluZXInLFxuICBjb2xvcjogaXNGb2N1c2VkID8gY29sb3JzLm5ldXRyYWw2MCA6IGNvbG9ycy5uZXV0cmFsMjAsXG4gIGRpc3BsYXk6ICdmbGV4JyxcbiAgcGFkZGluZzogYmFzZVVuaXQgKiAyLFxuICB0cmFuc2l0aW9uOiAnY29sb3IgMTUwbXMnLFxuXG4gICc6aG92ZXInOiB7XG4gICAgY29sb3I6IGlzRm9jdXNlZCA/IGNvbG9ycy5uZXV0cmFsODAgOiBjb2xvcnMubmV1dHJhbDQwLFxuICB9LFxufSk7XG5cbmV4cG9ydCBjb25zdCBkcm9wZG93bkluZGljYXRvckNTUyA9IGJhc2VDU1M7XG5leHBvcnQgY29uc3QgRHJvcGRvd25JbmRpY2F0b3IgPSA8XG4gIE9wdGlvbixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj5cbj4oXG4gIHByb3BzOiBEcm9wZG93bkluZGljYXRvclByb3BzPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+XG4pID0+IHtcbiAgY29uc3QgeyBjaGlsZHJlbiwgY2xhc3NOYW1lLCBjeCwgZ2V0U3R5bGVzLCBpbm5lclByb3BzIH0gPSBwcm9wcztcbiAgcmV0dXJuIChcbiAgICA8ZGl2XG4gICAgICBjc3M9e2dldFN0eWxlcygnZHJvcGRvd25JbmRpY2F0b3InLCBwcm9wcyl9XG4gICAgICBjbGFzc05hbWU9e2N4KFxuICAgICAgICB7XG4gICAgICAgICAgaW5kaWNhdG9yOiB0cnVlLFxuICAgICAgICAgICdkcm9wZG93bi1pbmRpY2F0b3InOiB0cnVlLFxuICAgICAgICB9LFxuICAgICAgICBjbGFzc05hbWVcbiAgICAgICl9XG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICA+XG4gICAgICB7Y2hpbGRyZW4gfHwgPERvd25DaGV2cm9uIC8+fVxuICAgIDwvZGl2PlxuICApO1xufTtcblxuZXhwb3J0IGludGVyZmFjZSBDbGVhckluZGljYXRvclByb3BzPFxuICBPcHRpb24gPSB1bmtub3duLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbiA9IGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj4gPSBHcm91cEJhc2U8T3B0aW9uPlxuPiBleHRlbmRzIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+IHtcbiAgLyoqIFRoZSBjaGlsZHJlbiB0byBiZSByZW5kZXJlZCBpbnNpZGUgdGhlIGluZGljYXRvci4gKi9cbiAgY2hpbGRyZW4/OiBSZWFjdE5vZGU7XG4gIC8qKiBQcm9wcyB0aGF0IHdpbGwgYmUgcGFzc2VkIG9uIHRvIHRoZSBjaGlsZHJlbi4gKi9cbiAgaW5uZXJQcm9wczogSlNYLkludHJpbnNpY0VsZW1lbnRzWydkaXYnXTtcbiAgLyoqIFRoZSBmb2N1c2VkIHN0YXRlIG9mIHRoZSBzZWxlY3QuICovXG4gIGlzRm9jdXNlZDogYm9vbGVhbjtcbn1cblxuZXhwb3J0IGNvbnN0IGNsZWFySW5kaWNhdG9yQ1NTID0gYmFzZUNTUztcbmV4cG9ydCBjb25zdCBDbGVhckluZGljYXRvciA9IDxcbiAgT3B0aW9uLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbixcbiAgR3JvdXAgZXh0ZW5kcyBHcm91cEJhc2U8T3B0aW9uPlxuPihcbiAgcHJvcHM6IENsZWFySW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNoaWxkcmVuLCBjbGFzc05hbWUsIGN4LCBnZXRTdHlsZXMsIGlubmVyUHJvcHMgfSA9IHByb3BzO1xuICByZXR1cm4gKFxuICAgIDxkaXZcbiAgICAgIGNzcz17Z2V0U3R5bGVzKCdjbGVhckluZGljYXRvcicsIHByb3BzKX1cbiAgICAgIGNsYXNzTmFtZT17Y3goXG4gICAgICAgIHtcbiAgICAgICAgICBpbmRpY2F0b3I6IHRydWUsXG4gICAgICAgICAgJ2NsZWFyLWluZGljYXRvcic6IHRydWUsXG4gICAgICAgIH0sXG4gICAgICAgIGNsYXNzTmFtZVxuICAgICAgKX1cbiAgICAgIHsuLi5pbm5lclByb3BzfVxuICAgID5cbiAgICAgIHtjaGlsZHJlbiB8fCA8Q3Jvc3NJY29uIC8+fVxuICAgIDwvZGl2PlxuICApO1xufTtcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBTZXBhcmF0b3Jcbi8vID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVxuXG5leHBvcnQgaW50ZXJmYWNlIEluZGljYXRvclNlcGFyYXRvclByb3BzPFxuICBPcHRpb24gPSB1bmtub3duLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbiA9IGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj4gPSBHcm91cEJhc2U8T3B0aW9uPlxuPiBleHRlbmRzIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+IHtcbiAgaXNEaXNhYmxlZDogYm9vbGVhbjtcbiAgaXNGb2N1c2VkOiBib29sZWFuO1xuICBpbm5lclByb3BzPzogSlNYLkludHJpbnNpY0VsZW1lbnRzWydzcGFuJ107XG59XG5cbmV4cG9ydCBjb25zdCBpbmRpY2F0b3JTZXBhcmF0b3JDU1MgPSA8XG4gIE9wdGlvbixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj5cbj4oe1xuICBpc0Rpc2FibGVkLFxuICB0aGVtZToge1xuICAgIHNwYWNpbmc6IHsgYmFzZVVuaXQgfSxcbiAgICBjb2xvcnMsXG4gIH0sXG59OiBJbmRpY2F0b3JTZXBhcmF0b3JQcm9wczxPcHRpb24sIElzTXVsdGksIEdyb3VwPik6IENTU09iamVjdFdpdGhMYWJlbCA9PiAoe1xuICBsYWJlbDogJ2luZGljYXRvclNlcGFyYXRvcicsXG4gIGFsaWduU2VsZjogJ3N0cmV0Y2gnLFxuICBiYWNrZ3JvdW5kQ29sb3I6IGlzRGlzYWJsZWQgPyBjb2xvcnMubmV1dHJhbDEwIDogY29sb3JzLm5ldXRyYWwyMCxcbiAgbWFyZ2luQm90dG9tOiBiYXNlVW5pdCAqIDIsXG4gIG1hcmdpblRvcDogYmFzZVVuaXQgKiAyLFxuICB3aWR0aDogMSxcbn0pO1xuXG5leHBvcnQgY29uc3QgSW5kaWNhdG9yU2VwYXJhdG9yID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICBwcm9wczogSW5kaWNhdG9yU2VwYXJhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNsYXNzTmFtZSwgY3gsIGdldFN0eWxlcywgaW5uZXJQcm9wcyB9ID0gcHJvcHM7XG4gIHJldHVybiAoXG4gICAgPHNwYW5cbiAgICAgIHsuLi5pbm5lclByb3BzfVxuICAgICAgY3NzPXtnZXRTdHlsZXMoJ2luZGljYXRvclNlcGFyYXRvcicsIHByb3BzKX1cbiAgICAgIGNsYXNzTmFtZT17Y3goeyAnaW5kaWNhdG9yLXNlcGFyYXRvcic6IHRydWUgfSwgY2xhc3NOYW1lKX1cbiAgICAvPlxuICApO1xufTtcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBMb2FkaW5nXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cblxuY29uc3QgbG9hZGluZ0RvdEFuaW1hdGlvbnMgPSBrZXlmcmFtZXNgXG4gIDAlLCA4MCUsIDEwMCUgeyBvcGFjaXR5OiAwOyB9XG4gIDQwJSB7IG9wYWNpdHk6IDE7IH1cbmA7XG5cbmV4cG9ydCBjb25zdCBsb2FkaW5nSW5kaWNhdG9yQ1NTID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KHtcbiAgaXNGb2N1c2VkLFxuICBzaXplLFxuICB0aGVtZToge1xuICAgIGNvbG9ycyxcbiAgICBzcGFjaW5nOiB7IGJhc2VVbml0IH0sXG4gIH0sXG59OiBMb2FkaW5nSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD4pOiBDU1NPYmplY3RXaXRoTGFiZWwgPT4gKHtcbiAgbGFiZWw6ICdsb2FkaW5nSW5kaWNhdG9yJyxcbiAgY29sb3I6IGlzRm9jdXNlZCA/IGNvbG9ycy5uZXV0cmFsNjAgOiBjb2xvcnMubmV1dHJhbDIwLFxuICBkaXNwbGF5OiAnZmxleCcsXG4gIHBhZGRpbmc6IGJhc2VVbml0ICogMixcbiAgdHJhbnNpdGlvbjogJ2NvbG9yIDE1MG1zJyxcbiAgYWxpZ25TZWxmOiAnY2VudGVyJyxcbiAgZm9udFNpemU6IHNpemUsXG4gIGxpbmVIZWlnaHQ6IDEsXG4gIG1hcmdpblJpZ2h0OiBzaXplLFxuICB0ZXh0QWxpZ246ICdjZW50ZXInLFxuICB2ZXJ0aWNhbEFsaWduOiAnbWlkZGxlJyxcbn0pO1xuXG5pbnRlcmZhY2UgTG9hZGluZ0RvdFByb3BzIHtcbiAgZGVsYXk6IG51bWJlcjtcbiAgb2Zmc2V0OiBib29sZWFuO1xufVxuY29uc3QgTG9hZGluZ0RvdCA9ICh7IGRlbGF5LCBvZmZzZXQgfTogTG9hZGluZ0RvdFByb3BzKSA9PiAoXG4gIDxzcGFuXG4gICAgY3NzPXt7XG4gICAgICBhbmltYXRpb246IGAke2xvYWRpbmdEb3RBbmltYXRpb25zfSAxcyBlYXNlLWluLW91dCAke2RlbGF5fW1zIGluZmluaXRlO2AsXG4gICAgICBiYWNrZ3JvdW5kQ29sb3I6ICdjdXJyZW50Q29sb3InLFxuICAgICAgYm9yZGVyUmFkaXVzOiAnMWVtJyxcbiAgICAgIGRpc3BsYXk6ICdpbmxpbmUtYmxvY2snLFxuICAgICAgbWFyZ2luTGVmdDogb2Zmc2V0ID8gJzFlbScgOiB1bmRlZmluZWQsXG4gICAgICBoZWlnaHQ6ICcxZW0nLFxuICAgICAgdmVydGljYWxBbGlnbjogJ3RvcCcsXG4gICAgICB3aWR0aDogJzFlbScsXG4gICAgfX1cbiAgLz5cbik7XG5cbmV4cG9ydCBpbnRlcmZhY2UgTG9hZGluZ0luZGljYXRvclByb3BzPFxuICBPcHRpb24gPSB1bmtub3duLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbiA9IGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj4gPSBHcm91cEJhc2U8T3B0aW9uPlxuPiBleHRlbmRzIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+IHtcbiAgLyoqIFByb3BzIHRoYXQgd2lsbCBiZSBwYXNzZWQgb24gdG8gdGhlIGNoaWxkcmVuLiAqL1xuICBpbm5lclByb3BzOiBKU1guSW50cmluc2ljRWxlbWVudHNbJ2RpdiddO1xuICAvKiogVGhlIGZvY3VzZWQgc3RhdGUgb2YgdGhlIHNlbGVjdC4gKi9cbiAgaXNGb2N1c2VkOiBib29sZWFuO1xuICBpc0Rpc2FibGVkOiBib29sZWFuO1xuICAvKiogU2V0IHNpemUgb2YgdGhlIGNvbnRhaW5lci4gKi9cbiAgc2l6ZTogbnVtYmVyO1xufVxuZXhwb3J0IGNvbnN0IExvYWRpbmdJbmRpY2F0b3IgPSA8XG4gIE9wdGlvbixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj5cbj4oXG4gIHByb3BzOiBMb2FkaW5nSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNsYXNzTmFtZSwgY3gsIGdldFN0eWxlcywgaW5uZXJQcm9wcywgaXNSdGwgfSA9IHByb3BzO1xuXG4gIHJldHVybiAoXG4gICAgPGRpdlxuICAgICAgY3NzPXtnZXRTdHlsZXMoJ2xvYWRpbmdJbmRpY2F0b3InLCBwcm9wcyl9XG4gICAgICBjbGFzc05hbWU9e2N4KFxuICAgICAgICB7XG4gICAgICAgICAgaW5kaWNhdG9yOiB0cnVlLFxuICAgICAgICAgICdsb2FkaW5nLWluZGljYXRvcic6IHRydWUsXG4gICAgICAgIH0sXG4gICAgICAgIGNsYXNzTmFtZVxuICAgICAgKX1cbiAgICAgIHsuLi5pbm5lclByb3BzfVxuICAgID5cbiAgICAgIDxMb2FkaW5nRG90IGRlbGF5PXswfSBvZmZzZXQ9e2lzUnRsfSAvPlxuICAgICAgPExvYWRpbmdEb3QgZGVsYXk9ezE2MH0gb2Zmc2V0IC8+XG4gICAgICA8TG9hZGluZ0RvdCBkZWxheT17MzIwfSBvZmZzZXQ9eyFpc1J0bH0gLz5cbiAgICA8L2Rpdj5cbiAgKTtcbn07XG5Mb2FkaW5nSW5kaWNhdG9yLmRlZmF1bHRQcm9wcyA9IHsgc2l6ZTogNCB9O1xuIl19 */\",\n toString: _EMOTION_STRINGIFIED_CSS_ERROR__\n};\n\n// ==============================\n// Dropdown & Clear Icons\n// ==============================\nvar Svg = function Svg(_ref) {\n var size = _ref.size,\n props = _objectWithoutProperties(_ref, _excluded$2);\n\n return jsx(\"svg\", _extends({\n height: size,\n width: size,\n viewBox: \"0 0 20 20\",\n \"aria-hidden\": \"true\",\n focusable: \"false\",\n css: _ref2\n }, props));\n};\n\nvar CrossIcon = function CrossIcon(props) {\n return jsx(Svg, _extends({\n size: 20\n }, props), jsx(\"path\", {\n d: \"M14.348 14.849c-0.469 0.469-1.229 0.469-1.697 0l-2.651-3.030-2.651 3.029c-0.469 0.469-1.229 0.469-1.697 0-0.469-0.469-0.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-0.469-0.469-0.469-1.228 0-1.697s1.228-0.469 1.697 0l2.652 3.031 2.651-3.031c0.469-0.469 1.228-0.469 1.697 0s0.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c0.469 0.469 0.469 1.229 0 1.698z\"\n }));\n};\nvar DownChevron = function DownChevron(props) {\n return jsx(Svg, _extends({\n size: 20\n }, props), jsx(\"path\", {\n d: \"M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747 3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0 1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502 0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0 0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z\"\n }));\n}; // ==============================\n// Dropdown & Clear Buttons\n// ==============================\n\nvar baseCSS = function baseCSS(_ref3) {\n var isFocused = _ref3.isFocused,\n _ref3$theme = _ref3.theme,\n baseUnit = _ref3$theme.spacing.baseUnit,\n colors = _ref3$theme.colors;\n return {\n label: 'indicatorContainer',\n color: isFocused ? colors.neutral60 : colors.neutral20,\n display: 'flex',\n padding: baseUnit * 2,\n transition: 'color 150ms',\n ':hover': {\n color: isFocused ? colors.neutral80 : colors.neutral40\n }\n };\n};\n\nvar dropdownIndicatorCSS = baseCSS;\nvar DropdownIndicator = function DropdownIndicator(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps;\n return jsx(\"div\", _extends({\n css: getStyles('dropdownIndicator', props),\n className: cx({\n indicator: true,\n 'dropdown-indicator': true\n }, className)\n }, innerProps), children || jsx(DownChevron, null));\n};\nvar clearIndicatorCSS = baseCSS;\nvar ClearIndicator = function ClearIndicator(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps;\n return jsx(\"div\", _extends({\n css: getStyles('clearIndicator', props),\n className: cx({\n indicator: true,\n 'clear-indicator': true\n }, className)\n }, innerProps), children || jsx(CrossIcon, null));\n}; // ==============================\n// Separator\n// ==============================\n\nvar indicatorSeparatorCSS = function indicatorSeparatorCSS(_ref4) {\n var isDisabled = _ref4.isDisabled,\n _ref4$theme = _ref4.theme,\n baseUnit = _ref4$theme.spacing.baseUnit,\n colors = _ref4$theme.colors;\n return {\n label: 'indicatorSeparator',\n alignSelf: 'stretch',\n backgroundColor: isDisabled ? colors.neutral10 : colors.neutral20,\n marginBottom: baseUnit * 2,\n marginTop: baseUnit * 2,\n width: 1\n };\n};\nvar IndicatorSeparator = function IndicatorSeparator(props) {\n var className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps;\n return jsx(\"span\", _extends({}, innerProps, {\n css: getStyles('indicatorSeparator', props),\n className: cx({\n 'indicator-separator': true\n }, className)\n }));\n}; // ==============================\n// Loading\n// ==============================\n\nvar loadingDotAnimations = keyframes(_templateObject || (_templateObject = _taggedTemplateLiteral([\"\\n 0%, 80%, 100% { opacity: 0; }\\n 40% { opacity: 1; }\\n\"])));\nvar loadingIndicatorCSS = function loadingIndicatorCSS(_ref5) {\n var isFocused = _ref5.isFocused,\n size = _ref5.size,\n _ref5$theme = _ref5.theme,\n colors = _ref5$theme.colors,\n baseUnit = _ref5$theme.spacing.baseUnit;\n return {\n label: 'loadingIndicator',\n color: isFocused ? colors.neutral60 : colors.neutral20,\n display: 'flex',\n padding: baseUnit * 2,\n transition: 'color 150ms',\n alignSelf: 'center',\n fontSize: size,\n lineHeight: 1,\n marginRight: size,\n textAlign: 'center',\n verticalAlign: 'middle'\n };\n};\n\nvar LoadingDot = function LoadingDot(_ref6) {\n var delay = _ref6.delay,\n offset = _ref6.offset;\n return jsx(\"span\", {\n css: /*#__PURE__*/css$2({\n animation: \"\".concat(loadingDotAnimations, \" 1s ease-in-out \").concat(delay, \"ms infinite;\"),\n backgroundColor: 'currentColor',\n borderRadius: '1em',\n display: 'inline-block',\n marginLeft: offset ? '1em' : undefined,\n height: '1em',\n verticalAlign: 'top',\n width: '1em'\n }, process.env.NODE_ENV === \"production\" ? \"\" : \";label:LoadingDot;\", process.env.NODE_ENV === \"production\" ? \"\" : \"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGljYXRvcnMudHN4Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQXFQSSIsImZpbGUiOiJpbmRpY2F0b3JzLnRzeCIsInNvdXJjZXNDb250ZW50IjpbIi8qKiBAanN4IGpzeCAqL1xuaW1wb3J0IHsgUmVhY3ROb2RlIH0gZnJvbSAncmVhY3QnO1xuaW1wb3J0IHsganN4LCBrZXlmcmFtZXMgfSBmcm9tICdAZW1vdGlvbi9yZWFjdCc7XG5cbmltcG9ydCB7XG4gIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lLFxuICBDU1NPYmplY3RXaXRoTGFiZWwsXG4gIEdyb3VwQmFzZSxcbn0gZnJvbSAnLi4vdHlwZXMnO1xuXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cbi8vIERyb3Bkb3duICYgQ2xlYXIgSWNvbnNcbi8vID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVxuXG5jb25zdCBTdmcgPSAoe1xuICBzaXplLFxuICAuLi5wcm9wc1xufTogSlNYLkludHJpbnNpY0VsZW1lbnRzWydzdmcnXSAmIHsgc2l6ZTogbnVtYmVyIH0pID0+IChcbiAgPHN2Z1xuICAgIGhlaWdodD17c2l6ZX1cbiAgICB3aWR0aD17c2l6ZX1cbiAgICB2aWV3Qm94PVwiMCAwIDIwIDIwXCJcbiAgICBhcmlhLWhpZGRlbj1cInRydWVcIlxuICAgIGZvY3VzYWJsZT1cImZhbHNlXCJcbiAgICBjc3M9e3tcbiAgICAgIGRpc3BsYXk6ICdpbmxpbmUtYmxvY2snLFxuICAgICAgZmlsbDogJ2N1cnJlbnRDb2xvcicsXG4gICAgICBsaW5lSGVpZ2h0OiAxLFxuICAgICAgc3Ryb2tlOiAnY3VycmVudENvbG9yJyxcbiAgICAgIHN0cm9rZVdpZHRoOiAwLFxuICAgIH19XG4gICAgey4uLnByb3BzfVxuICAvPlxuKTtcblxuZXhwb3J0IHR5cGUgQ3Jvc3NJY29uUHJvcHMgPSBKU1guSW50cmluc2ljRWxlbWVudHNbJ3N2ZyddICYgeyBzaXplPzogbnVtYmVyIH07XG5leHBvcnQgY29uc3QgQ3Jvc3NJY29uID0gKHByb3BzOiBDcm9zc0ljb25Qcm9wcykgPT4gKFxuICA8U3ZnIHNpemU9ezIwfSB7Li4ucHJvcHN9PlxuICAgIDxwYXRoIGQ9XCJNMTQuMzQ4IDE0Ljg0OWMtMC40NjkgMC40NjktMS4yMjkgMC40NjktMS42OTcgMGwtMi42NTEtMy4wMzAtMi42NTEgMy4wMjljLTAuNDY5IDAuNDY5LTEuMjI5IDAuNDY5LTEuNjk3IDAtMC40NjktMC40NjktMC40NjktMS4yMjkgMC0xLjY5N2wyLjc1OC0zLjE1LTIuNzU5LTMuMTUyYy0wLjQ2OS0wLjQ2OS0wLjQ2OS0xLjIyOCAwLTEuNjk3czEuMjI4LTAuNDY5IDEuNjk3IDBsMi42NTIgMy4wMzEgMi42NTEtMy4wMzFjMC40NjktMC40NjkgMS4yMjgtMC40NjkgMS42OTcgMHMwLjQ2OSAxLjIyOSAwIDEuNjk3bC0yLjc1OCAzLjE1MiAyLjc1OCAzLjE1YzAuNDY5IDAuNDY5IDAuNDY5IDEuMjI5IDAgMS42OTh6XCIgLz5cbiAgPC9Tdmc+XG4pO1xuZXhwb3J0IHR5cGUgRG93bkNoZXZyb25Qcm9wcyA9IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snc3ZnJ10gJiB7IHNpemU/OiBudW1iZXIgfTtcbmV4cG9ydCBjb25zdCBEb3duQ2hldnJvbiA9IChwcm9wczogRG93bkNoZXZyb25Qcm9wcykgPT4gKFxuICA8U3ZnIHNpemU9ezIwfSB7Li4ucHJvcHN9PlxuICAgIDxwYXRoIGQ9XCJNNC41MTYgNy41NDhjMC40MzYtMC40NDYgMS4wNDMtMC40ODEgMS41NzYgMGwzLjkwOCAzLjc0NyAzLjkwOC0zLjc0N2MwLjUzMy0wLjQ4MSAxLjE0MS0wLjQ0NiAxLjU3NCAwIDAuNDM2IDAuNDQ1IDAuNDA4IDEuMTk3IDAgMS42MTUtMC40MDYgMC40MTgtNC42OTUgNC41MDItNC42OTUgNC41MDItMC4yMTcgMC4yMjMtMC41MDIgMC4zMzUtMC43ODcgMC4zMzVzLTAuNTctMC4xMTItMC43ODktMC4zMzVjMCAwLTQuMjg3LTQuMDg0LTQuNjk1LTQuNTAycy0wLjQzNi0xLjE3IDAtMS42MTV6XCIgLz5cbiAgPC9Tdmc+XG4pO1xuXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cbi8vIERyb3Bkb3duICYgQ2xlYXIgQnV0dG9uc1xuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG5cbmV4cG9ydCBpbnRlcmZhY2UgRHJvcGRvd25JbmRpY2F0b3JQcm9wczxcbiAgT3B0aW9uID0gdW5rbm93bixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4gPSBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+ID0gR3JvdXBCYXNlPE9wdGlvbj5cbj4gZXh0ZW5kcyBDb21tb25Qcm9wc0FuZENsYXNzTmFtZTxPcHRpb24sIElzTXVsdGksIEdyb3VwPiB7XG4gIC8qKiBUaGUgY2hpbGRyZW4gdG8gYmUgcmVuZGVyZWQgaW5zaWRlIHRoZSBpbmRpY2F0b3IuICovXG4gIGNoaWxkcmVuPzogUmVhY3ROb2RlO1xuICAvKiogUHJvcHMgdGhhdCB3aWxsIGJlIHBhc3NlZCBvbiB0byB0aGUgY2hpbGRyZW4uICovXG4gIGlubmVyUHJvcHM6IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snZGl2J107XG4gIC8qKiBUaGUgZm9jdXNlZCBzdGF0ZSBvZiB0aGUgc2VsZWN0LiAqL1xuICBpc0ZvY3VzZWQ6IGJvb2xlYW47XG4gIGlzRGlzYWJsZWQ6IGJvb2xlYW47XG59XG5cbmNvbnN0IGJhc2VDU1MgPSA8XG4gIE9wdGlvbixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj5cbj4oe1xuICBpc0ZvY3VzZWQsXG4gIHRoZW1lOiB7XG4gICAgc3BhY2luZzogeyBiYXNlVW5pdCB9LFxuICAgIGNvbG9ycyxcbiAgfSxcbn06XG4gIHwgRHJvcGRvd25JbmRpY2F0b3JQcm9wczxPcHRpb24sIElzTXVsdGksIEdyb3VwPlxuICB8IENsZWFySW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD4pOiBDU1NPYmplY3RXaXRoTGFiZWwgPT4gKHtcbiAgbGFiZWw6ICdpbmRpY2F0b3JDb250YWluZXInLFxuICBjb2xvcjogaXNGb2N1c2VkID8gY29sb3JzLm5ldXRyYWw2MCA6IGNvbG9ycy5uZXV0cmFsMjAsXG4gIGRpc3BsYXk6ICdmbGV4JyxcbiAgcGFkZGluZzogYmFzZVVuaXQgKiAyLFxuICB0cmFuc2l0aW9uOiAnY29sb3IgMTUwbXMnLFxuXG4gICc6aG92ZXInOiB7XG4gICAgY29sb3I6IGlzRm9jdXNlZCA/IGNvbG9ycy5uZXV0cmFsODAgOiBjb2xvcnMubmV1dHJhbDQwLFxuICB9LFxufSk7XG5cbmV4cG9ydCBjb25zdCBkcm9wZG93bkluZGljYXRvckNTUyA9IGJhc2VDU1M7XG5leHBvcnQgY29uc3QgRHJvcGRvd25JbmRpY2F0b3IgPSA8XG4gIE9wdGlvbixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj5cbj4oXG4gIHByb3BzOiBEcm9wZG93bkluZGljYXRvclByb3BzPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+XG4pID0+IHtcbiAgY29uc3QgeyBjaGlsZHJlbiwgY2xhc3NOYW1lLCBjeCwgZ2V0U3R5bGVzLCBpbm5lclByb3BzIH0gPSBwcm9wcztcbiAgcmV0dXJuIChcbiAgICA8ZGl2XG4gICAgICBjc3M9e2dldFN0eWxlcygnZHJvcGRvd25JbmRpY2F0b3InLCBwcm9wcyl9XG4gICAgICBjbGFzc05hbWU9e2N4KFxuICAgICAgICB7XG4gICAgICAgICAgaW5kaWNhdG9yOiB0cnVlLFxuICAgICAgICAgICdkcm9wZG93bi1pbmRpY2F0b3InOiB0cnVlLFxuICAgICAgICB9LFxuICAgICAgICBjbGFzc05hbWVcbiAgICAgICl9XG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICA+XG4gICAgICB7Y2hpbGRyZW4gfHwgPERvd25DaGV2cm9uIC8+fVxuICAgIDwvZGl2PlxuICApO1xufTtcblxuZXhwb3J0IGludGVyZmFjZSBDbGVhckluZGljYXRvclByb3BzPFxuICBPcHRpb24gPSB1bmtub3duLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbiA9IGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj4gPSBHcm91cEJhc2U8T3B0aW9uPlxuPiBleHRlbmRzIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+IHtcbiAgLyoqIFRoZSBjaGlsZHJlbiB0byBiZSByZW5kZXJlZCBpbnNpZGUgdGhlIGluZGljYXRvci4gKi9cbiAgY2hpbGRyZW4/OiBSZWFjdE5vZGU7XG4gIC8qKiBQcm9wcyB0aGF0IHdpbGwgYmUgcGFzc2VkIG9uIHRvIHRoZSBjaGlsZHJlbi4gKi9cbiAgaW5uZXJQcm9wczogSlNYLkludHJpbnNpY0VsZW1lbnRzWydkaXYnXTtcbiAgLyoqIFRoZSBmb2N1c2VkIHN0YXRlIG9mIHRoZSBzZWxlY3QuICovXG4gIGlzRm9jdXNlZDogYm9vbGVhbjtcbn1cblxuZXhwb3J0IGNvbnN0IGNsZWFySW5kaWNhdG9yQ1NTID0gYmFzZUNTUztcbmV4cG9ydCBjb25zdCBDbGVhckluZGljYXRvciA9IDxcbiAgT3B0aW9uLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbixcbiAgR3JvdXAgZXh0ZW5kcyBHcm91cEJhc2U8T3B0aW9uPlxuPihcbiAgcHJvcHM6IENsZWFySW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNoaWxkcmVuLCBjbGFzc05hbWUsIGN4LCBnZXRTdHlsZXMsIGlubmVyUHJvcHMgfSA9IHByb3BzO1xuICByZXR1cm4gKFxuICAgIDxkaXZcbiAgICAgIGNzcz17Z2V0U3R5bGVzKCdjbGVhckluZGljYXRvcicsIHByb3BzKX1cbiAgICAgIGNsYXNzTmFtZT17Y3goXG4gICAgICAgIHtcbiAgICAgICAgICBpbmRpY2F0b3I6IHRydWUsXG4gICAgICAgICAgJ2NsZWFyLWluZGljYXRvcic6IHRydWUsXG4gICAgICAgIH0sXG4gICAgICAgIGNsYXNzTmFtZVxuICAgICAgKX1cbiAgICAgIHsuLi5pbm5lclByb3BzfVxuICAgID5cbiAgICAgIHtjaGlsZHJlbiB8fCA8Q3Jvc3NJY29uIC8+fVxuICAgIDwvZGl2PlxuICApO1xufTtcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBTZXBhcmF0b3Jcbi8vID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVxuXG5leHBvcnQgaW50ZXJmYWNlIEluZGljYXRvclNlcGFyYXRvclByb3BzPFxuICBPcHRpb24gPSB1bmtub3duLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbiA9IGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj4gPSBHcm91cEJhc2U8T3B0aW9uPlxuPiBleHRlbmRzIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+IHtcbiAgaXNEaXNhYmxlZDogYm9vbGVhbjtcbiAgaXNGb2N1c2VkOiBib29sZWFuO1xuICBpbm5lclByb3BzPzogSlNYLkludHJpbnNpY0VsZW1lbnRzWydzcGFuJ107XG59XG5cbmV4cG9ydCBjb25zdCBpbmRpY2F0b3JTZXBhcmF0b3JDU1MgPSA8XG4gIE9wdGlvbixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj5cbj4oe1xuICBpc0Rpc2FibGVkLFxuICB0aGVtZToge1xuICAgIHNwYWNpbmc6IHsgYmFzZVVuaXQgfSxcbiAgICBjb2xvcnMsXG4gIH0sXG59OiBJbmRpY2F0b3JTZXBhcmF0b3JQcm9wczxPcHRpb24sIElzTXVsdGksIEdyb3VwPik6IENTU09iamVjdFdpdGhMYWJlbCA9PiAoe1xuICBsYWJlbDogJ2luZGljYXRvclNlcGFyYXRvcicsXG4gIGFsaWduU2VsZjogJ3N0cmV0Y2gnLFxuICBiYWNrZ3JvdW5kQ29sb3I6IGlzRGlzYWJsZWQgPyBjb2xvcnMubmV1dHJhbDEwIDogY29sb3JzLm5ldXRyYWwyMCxcbiAgbWFyZ2luQm90dG9tOiBiYXNlVW5pdCAqIDIsXG4gIG1hcmdpblRvcDogYmFzZVVuaXQgKiAyLFxuICB3aWR0aDogMSxcbn0pO1xuXG5leHBvcnQgY29uc3QgSW5kaWNhdG9yU2VwYXJhdG9yID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICBwcm9wczogSW5kaWNhdG9yU2VwYXJhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNsYXNzTmFtZSwgY3gsIGdldFN0eWxlcywgaW5uZXJQcm9wcyB9ID0gcHJvcHM7XG4gIHJldHVybiAoXG4gICAgPHNwYW5cbiAgICAgIHsuLi5pbm5lclByb3BzfVxuICAgICAgY3NzPXtnZXRTdHlsZXMoJ2luZGljYXRvclNlcGFyYXRvcicsIHByb3BzKX1cbiAgICAgIGNsYXNzTmFtZT17Y3goeyAnaW5kaWNhdG9yLXNlcGFyYXRvcic6IHRydWUgfSwgY2xhc3NOYW1lKX1cbiAgICAvPlxuICApO1xufTtcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBMb2FkaW5nXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cblxuY29uc3QgbG9hZGluZ0RvdEFuaW1hdGlvbnMgPSBrZXlmcmFtZXNgXG4gIDAlLCA4MCUsIDEwMCUgeyBvcGFjaXR5OiAwOyB9XG4gIDQwJSB7IG9wYWNpdHk6IDE7IH1cbmA7XG5cbmV4cG9ydCBjb25zdCBsb2FkaW5nSW5kaWNhdG9yQ1NTID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KHtcbiAgaXNGb2N1c2VkLFxuICBzaXplLFxuICB0aGVtZToge1xuICAgIGNvbG9ycyxcbiAgICBzcGFjaW5nOiB7IGJhc2VVbml0IH0sXG4gIH0sXG59OiBMb2FkaW5nSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD4pOiBDU1NPYmplY3RXaXRoTGFiZWwgPT4gKHtcbiAgbGFiZWw6ICdsb2FkaW5nSW5kaWNhdG9yJyxcbiAgY29sb3I6IGlzRm9jdXNlZCA/IGNvbG9ycy5uZXV0cmFsNjAgOiBjb2xvcnMubmV1dHJhbDIwLFxuICBkaXNwbGF5OiAnZmxleCcsXG4gIHBhZGRpbmc6IGJhc2VVbml0ICogMixcbiAgdHJhbnNpdGlvbjogJ2NvbG9yIDE1MG1zJyxcbiAgYWxpZ25TZWxmOiAnY2VudGVyJyxcbiAgZm9udFNpemU6IHNpemUsXG4gIGxpbmVIZWlnaHQ6IDEsXG4gIG1hcmdpblJpZ2h0OiBzaXplLFxuICB0ZXh0QWxpZ246ICdjZW50ZXInLFxuICB2ZXJ0aWNhbEFsaWduOiAnbWlkZGxlJyxcbn0pO1xuXG5pbnRlcmZhY2UgTG9hZGluZ0RvdFByb3BzIHtcbiAgZGVsYXk6IG51bWJlcjtcbiAgb2Zmc2V0OiBib29sZWFuO1xufVxuY29uc3QgTG9hZGluZ0RvdCA9ICh7IGRlbGF5LCBvZmZzZXQgfTogTG9hZGluZ0RvdFByb3BzKSA9PiAoXG4gIDxzcGFuXG4gICAgY3NzPXt7XG4gICAgICBhbmltYXRpb246IGAke2xvYWRpbmdEb3RBbmltYXRpb25zfSAxcyBlYXNlLWluLW91dCAke2RlbGF5fW1zIGluZmluaXRlO2AsXG4gICAgICBiYWNrZ3JvdW5kQ29sb3I6ICdjdXJyZW50Q29sb3InLFxuICAgICAgYm9yZGVyUmFkaXVzOiAnMWVtJyxcbiAgICAgIGRpc3BsYXk6ICdpbmxpbmUtYmxvY2snLFxuICAgICAgbWFyZ2luTGVmdDogb2Zmc2V0ID8gJzFlbScgOiB1bmRlZmluZWQsXG4gICAgICBoZWlnaHQ6ICcxZW0nLFxuICAgICAgdmVydGljYWxBbGlnbjogJ3RvcCcsXG4gICAgICB3aWR0aDogJzFlbScsXG4gICAgfX1cbiAgLz5cbik7XG5cbmV4cG9ydCBpbnRlcmZhY2UgTG9hZGluZ0luZGljYXRvclByb3BzPFxuICBPcHRpb24gPSB1bmtub3duLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbiA9IGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj4gPSBHcm91cEJhc2U8T3B0aW9uPlxuPiBleHRlbmRzIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+IHtcbiAgLyoqIFByb3BzIHRoYXQgd2lsbCBiZSBwYXNzZWQgb24gdG8gdGhlIGNoaWxkcmVuLiAqL1xuICBpbm5lclByb3BzOiBKU1guSW50cmluc2ljRWxlbWVudHNbJ2RpdiddO1xuICAvKiogVGhlIGZvY3VzZWQgc3RhdGUgb2YgdGhlIHNlbGVjdC4gKi9cbiAgaXNGb2N1c2VkOiBib29sZWFuO1xuICBpc0Rpc2FibGVkOiBib29sZWFuO1xuICAvKiogU2V0IHNpemUgb2YgdGhlIGNvbnRhaW5lci4gKi9cbiAgc2l6ZTogbnVtYmVyO1xufVxuZXhwb3J0IGNvbnN0IExvYWRpbmdJbmRpY2F0b3IgPSA8XG4gIE9wdGlvbixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj5cbj4oXG4gIHByb3BzOiBMb2FkaW5nSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNsYXNzTmFtZSwgY3gsIGdldFN0eWxlcywgaW5uZXJQcm9wcywgaXNSdGwgfSA9IHByb3BzO1xuXG4gIHJldHVybiAoXG4gICAgPGRpdlxuICAgICAgY3NzPXtnZXRTdHlsZXMoJ2xvYWRpbmdJbmRpY2F0b3InLCBwcm9wcyl9XG4gICAgICBjbGFzc05hbWU9e2N4KFxuICAgICAgICB7XG4gICAgICAgICAgaW5kaWNhdG9yOiB0cnVlLFxuICAgICAgICAgICdsb2FkaW5nLWluZGljYXRvcic6IHRydWUsXG4gICAgICAgIH0sXG4gICAgICAgIGNsYXNzTmFtZVxuICAgICAgKX1cbiAgICAgIHsuLi5pbm5lclByb3BzfVxuICAgID5cbiAgICAgIDxMb2FkaW5nRG90IGRlbGF5PXswfSBvZmZzZXQ9e2lzUnRsfSAvPlxuICAgICAgPExvYWRpbmdEb3QgZGVsYXk9ezE2MH0gb2Zmc2V0IC8+XG4gICAgICA8TG9hZGluZ0RvdCBkZWxheT17MzIwfSBvZmZzZXQ9eyFpc1J0bH0gLz5cbiAgICA8L2Rpdj5cbiAgKTtcbn07XG5Mb2FkaW5nSW5kaWNhdG9yLmRlZmF1bHRQcm9wcyA9IHsgc2l6ZTogNCB9O1xuIl19 */\")\n });\n};\n\nvar LoadingIndicator = function LoadingIndicator(props) {\n var className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps,\n isRtl = props.isRtl;\n return jsx(\"div\", _extends({\n css: getStyles('loadingIndicator', props),\n className: cx({\n indicator: true,\n 'loading-indicator': true\n }, className)\n }, innerProps), jsx(LoadingDot, {\n delay: 0,\n offset: isRtl\n }), jsx(LoadingDot, {\n delay: 160,\n offset: true\n }), jsx(LoadingDot, {\n delay: 320,\n offset: !isRtl\n }));\n};\nLoadingIndicator.defaultProps = {\n size: 4\n};\n\nvar css$1 = function css(_ref) {\n var isDisabled = _ref.isDisabled,\n isFocused = _ref.isFocused,\n _ref$theme = _ref.theme,\n colors = _ref$theme.colors,\n borderRadius = _ref$theme.borderRadius,\n spacing = _ref$theme.spacing;\n return {\n label: 'control',\n alignItems: 'center',\n backgroundColor: isDisabled ? colors.neutral5 : colors.neutral0,\n borderColor: isDisabled ? colors.neutral10 : isFocused ? colors.primary : colors.neutral20,\n borderRadius: borderRadius,\n borderStyle: 'solid',\n borderWidth: 1,\n boxShadow: isFocused ? \"0 0 0 1px \".concat(colors.primary) : undefined,\n cursor: 'default',\n display: 'flex',\n flexWrap: 'wrap',\n justifyContent: 'space-between',\n minHeight: spacing.controlHeight,\n outline: '0 !important',\n position: 'relative',\n transition: 'all 100ms',\n '&:hover': {\n borderColor: isFocused ? colors.primary : colors.neutral30\n }\n };\n};\n\nvar Control = function Control(props) {\n var children = props.children,\n cx = props.cx,\n getStyles = props.getStyles,\n className = props.className,\n isDisabled = props.isDisabled,\n isFocused = props.isFocused,\n innerRef = props.innerRef,\n innerProps = props.innerProps,\n menuIsOpen = props.menuIsOpen;\n return jsx(\"div\", _extends({\n ref: innerRef,\n css: getStyles('control', props),\n className: cx({\n control: true,\n 'control--is-disabled': isDisabled,\n 'control--is-focused': isFocused,\n 'control--menu-is-open': menuIsOpen\n }, className)\n }, innerProps), children);\n};\n\nvar _excluded$1 = [\"data\"];\nvar groupCSS = function groupCSS(_ref) {\n var spacing = _ref.theme.spacing;\n return {\n paddingBottom: spacing.baseUnit * 2,\n paddingTop: spacing.baseUnit * 2\n };\n};\n\nvar Group = function Group(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n Heading = props.Heading,\n headingProps = props.headingProps,\n innerProps = props.innerProps,\n label = props.label,\n theme = props.theme,\n selectProps = props.selectProps;\n return jsx(\"div\", _extends({\n css: getStyles('group', props),\n className: cx({\n group: true\n }, className)\n }, innerProps), jsx(Heading, _extends({}, headingProps, {\n selectProps: selectProps,\n theme: theme,\n getStyles: getStyles,\n cx: cx\n }), label), jsx(\"div\", null, children));\n};\n\nvar groupHeadingCSS = function groupHeadingCSS(_ref2) {\n var spacing = _ref2.theme.spacing;\n return {\n label: 'group',\n color: '#999',\n cursor: 'default',\n display: 'block',\n fontSize: '75%',\n fontWeight: 500,\n marginBottom: '0.25em',\n paddingLeft: spacing.baseUnit * 3,\n paddingRight: spacing.baseUnit * 3,\n textTransform: 'uppercase'\n };\n};\nvar GroupHeading = function GroupHeading(props) {\n var getStyles = props.getStyles,\n cx = props.cx,\n className = props.className;\n\n var _cleanCommonProps = cleanCommonProps(props);\n _cleanCommonProps.data;\n var innerProps = _objectWithoutProperties(_cleanCommonProps, _excluded$1);\n\n return jsx(\"div\", _extends({\n css: getStyles('groupHeading', props),\n className: cx({\n 'group-heading': true\n }, className)\n }, innerProps));\n};\n\nvar _excluded = [\"innerRef\", \"isDisabled\", \"isHidden\", \"inputClassName\"];\nvar inputCSS = function inputCSS(_ref) {\n var isDisabled = _ref.isDisabled,\n value = _ref.value,\n _ref$theme = _ref.theme,\n spacing = _ref$theme.spacing,\n colors = _ref$theme.colors;\n return _objectSpread2({\n margin: spacing.baseUnit / 2,\n paddingBottom: spacing.baseUnit / 2,\n paddingTop: spacing.baseUnit / 2,\n visibility: isDisabled ? 'hidden' : 'visible',\n color: colors.neutral80,\n // force css to recompute when value change due to @emotion bug.\n // We can remove it whenever the bug is fixed.\n transform: value ? 'translateZ(0)' : ''\n }, containerStyle);\n};\nvar spacingStyle = {\n gridArea: '1 / 2',\n font: 'inherit',\n minWidth: '2px',\n border: 0,\n margin: 0,\n outline: 0,\n padding: 0\n};\nvar containerStyle = {\n flex: '1 1 auto',\n display: 'inline-grid',\n gridArea: '1 / 1 / 2 / 3',\n gridTemplateColumns: '0 min-content',\n '&:after': _objectSpread2({\n content: 'attr(data-value) \" \"',\n visibility: 'hidden',\n whiteSpace: 'pre'\n }, spacingStyle)\n};\n\nvar inputStyle = function inputStyle(isHidden) {\n return _objectSpread2({\n label: 'input',\n color: 'inherit',\n background: 0,\n opacity: isHidden ? 0 : 1,\n width: '100%'\n }, spacingStyle);\n};\n\nvar Input = function Input(props) {\n var className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n value = props.value;\n\n var _cleanCommonProps = cleanCommonProps(props),\n innerRef = _cleanCommonProps.innerRef,\n isDisabled = _cleanCommonProps.isDisabled,\n isHidden = _cleanCommonProps.isHidden,\n inputClassName = _cleanCommonProps.inputClassName,\n innerProps = _objectWithoutProperties(_cleanCommonProps, _excluded);\n\n return jsx(\"div\", {\n className: cx({\n 'input-container': true\n }, className),\n css: getStyles('input', props),\n \"data-value\": value || ''\n }, jsx(\"input\", _extends({\n className: cx({\n input: true\n }, inputClassName),\n ref: innerRef,\n style: inputStyle(isHidden),\n disabled: isDisabled\n }, innerProps)));\n};\n\nvar multiValueCSS = function multiValueCSS(_ref) {\n var _ref$theme = _ref.theme,\n spacing = _ref$theme.spacing,\n borderRadius = _ref$theme.borderRadius,\n colors = _ref$theme.colors;\n return {\n label: 'multiValue',\n backgroundColor: colors.neutral10,\n borderRadius: borderRadius / 2,\n display: 'flex',\n margin: spacing.baseUnit / 2,\n minWidth: 0 // resolves flex/text-overflow bug\n\n };\n};\nvar multiValueLabelCSS = function multiValueLabelCSS(_ref2) {\n var _ref2$theme = _ref2.theme,\n borderRadius = _ref2$theme.borderRadius,\n colors = _ref2$theme.colors,\n cropWithEllipsis = _ref2.cropWithEllipsis;\n return {\n borderRadius: borderRadius / 2,\n color: colors.neutral80,\n fontSize: '85%',\n overflow: 'hidden',\n padding: 3,\n paddingLeft: 6,\n textOverflow: cropWithEllipsis || cropWithEllipsis === undefined ? 'ellipsis' : undefined,\n whiteSpace: 'nowrap'\n };\n};\nvar multiValueRemoveCSS = function multiValueRemoveCSS(_ref3) {\n var _ref3$theme = _ref3.theme,\n spacing = _ref3$theme.spacing,\n borderRadius = _ref3$theme.borderRadius,\n colors = _ref3$theme.colors,\n isFocused = _ref3.isFocused;\n return {\n alignItems: 'center',\n borderRadius: borderRadius / 2,\n backgroundColor: isFocused ? colors.dangerLight : undefined,\n display: 'flex',\n paddingLeft: spacing.baseUnit,\n paddingRight: spacing.baseUnit,\n ':hover': {\n backgroundColor: colors.dangerLight,\n color: colors.danger\n }\n };\n};\nvar MultiValueGeneric = function MultiValueGeneric(_ref4) {\n var children = _ref4.children,\n innerProps = _ref4.innerProps;\n return jsx(\"div\", innerProps, children);\n};\nvar MultiValueContainer = MultiValueGeneric;\nvar MultiValueLabel = MultiValueGeneric;\nfunction MultiValueRemove(_ref5) {\n var children = _ref5.children,\n innerProps = _ref5.innerProps;\n return jsx(\"div\", _extends({\n role: \"button\"\n }, innerProps), children || jsx(CrossIcon, {\n size: 14\n }));\n}\n\nvar MultiValue = function MultiValue(props) {\n var children = props.children,\n className = props.className,\n components = props.components,\n cx = props.cx,\n data = props.data,\n getStyles = props.getStyles,\n innerProps = props.innerProps,\n isDisabled = props.isDisabled,\n removeProps = props.removeProps,\n selectProps = props.selectProps;\n var Container = components.Container,\n Label = components.Label,\n Remove = components.Remove;\n return jsx(ClassNames, null, function (_ref6) {\n var css = _ref6.css,\n emotionCx = _ref6.cx;\n return jsx(Container, {\n data: data,\n innerProps: _objectSpread2({\n className: emotionCx(css(getStyles('multiValue', props)), cx({\n 'multi-value': true,\n 'multi-value--is-disabled': isDisabled\n }, className))\n }, innerProps),\n selectProps: selectProps\n }, jsx(Label, {\n data: data,\n innerProps: {\n className: emotionCx(css(getStyles('multiValueLabel', props)), cx({\n 'multi-value__label': true\n }, className))\n },\n selectProps: selectProps\n }, children), jsx(Remove, {\n data: data,\n innerProps: _objectSpread2({\n className: emotionCx(css(getStyles('multiValueRemove', props)), cx({\n 'multi-value__remove': true\n }, className)),\n 'aria-label': \"Remove \".concat(children || 'option')\n }, removeProps),\n selectProps: selectProps\n }));\n });\n};\n\nvar optionCSS = function optionCSS(_ref) {\n var isDisabled = _ref.isDisabled,\n isFocused = _ref.isFocused,\n isSelected = _ref.isSelected,\n _ref$theme = _ref.theme,\n spacing = _ref$theme.spacing,\n colors = _ref$theme.colors;\n return {\n label: 'option',\n backgroundColor: isSelected ? colors.primary : isFocused ? colors.primary25 : 'transparent',\n color: isDisabled ? colors.neutral20 : isSelected ? colors.neutral0 : 'inherit',\n cursor: 'default',\n display: 'block',\n fontSize: 'inherit',\n padding: \"\".concat(spacing.baseUnit * 2, \"px \").concat(spacing.baseUnit * 3, \"px\"),\n width: '100%',\n userSelect: 'none',\n WebkitTapHighlightColor: 'rgba(0, 0, 0, 0)',\n // provide some affordance on touch devices\n ':active': {\n backgroundColor: !isDisabled ? isSelected ? colors.primary : colors.primary50 : undefined\n }\n };\n};\n\nvar Option = function Option(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n isDisabled = props.isDisabled,\n isFocused = props.isFocused,\n isSelected = props.isSelected,\n innerRef = props.innerRef,\n innerProps = props.innerProps;\n return jsx(\"div\", _extends({\n css: getStyles('option', props),\n className: cx({\n option: true,\n 'option--is-disabled': isDisabled,\n 'option--is-focused': isFocused,\n 'option--is-selected': isSelected\n }, className),\n ref: innerRef,\n \"aria-disabled\": isDisabled\n }, innerProps), children);\n};\n\nvar placeholderCSS = function placeholderCSS(_ref) {\n var _ref$theme = _ref.theme,\n spacing = _ref$theme.spacing,\n colors = _ref$theme.colors;\n return {\n label: 'placeholder',\n color: colors.neutral50,\n gridArea: '1 / 1 / 2 / 3',\n marginLeft: spacing.baseUnit / 2,\n marginRight: spacing.baseUnit / 2\n };\n};\n\nvar Placeholder = function Placeholder(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n innerProps = props.innerProps;\n return jsx(\"div\", _extends({\n css: getStyles('placeholder', props),\n className: cx({\n placeholder: true\n }, className)\n }, innerProps), children);\n};\n\nvar css = function css(_ref) {\n var isDisabled = _ref.isDisabled,\n _ref$theme = _ref.theme,\n spacing = _ref$theme.spacing,\n colors = _ref$theme.colors;\n return {\n label: 'singleValue',\n color: isDisabled ? colors.neutral40 : colors.neutral80,\n gridArea: '1 / 1 / 2 / 3',\n marginLeft: spacing.baseUnit / 2,\n marginRight: spacing.baseUnit / 2,\n maxWidth: '100%',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap'\n };\n};\n\nvar SingleValue = function SingleValue(props) {\n var children = props.children,\n className = props.className,\n cx = props.cx,\n getStyles = props.getStyles,\n isDisabled = props.isDisabled,\n innerProps = props.innerProps;\n return jsx(\"div\", _extends({\n css: getStyles('singleValue', props),\n className: cx({\n 'single-value': true,\n 'single-value--is-disabled': isDisabled\n }, className)\n }, innerProps), children);\n};\n\nvar components = {\n ClearIndicator: ClearIndicator,\n Control: Control,\n DropdownIndicator: DropdownIndicator,\n DownChevron: DownChevron,\n CrossIcon: CrossIcon,\n Group: Group,\n GroupHeading: GroupHeading,\n IndicatorsContainer: IndicatorsContainer,\n IndicatorSeparator: IndicatorSeparator,\n Input: Input,\n LoadingIndicator: LoadingIndicator,\n Menu: Menu,\n MenuList: MenuList,\n MenuPortal: MenuPortal,\n LoadingMessage: LoadingMessage,\n NoOptionsMessage: NoOptionsMessage,\n MultiValue: MultiValue,\n MultiValueContainer: MultiValueContainer,\n MultiValueLabel: MultiValueLabel,\n MultiValueRemove: MultiValueRemove,\n Option: Option,\n Placeholder: Placeholder,\n SelectContainer: SelectContainer,\n SingleValue: SingleValue,\n ValueContainer: ValueContainer\n};\nvar defaultComponents = function defaultComponents(props) {\n return _objectSpread2(_objectSpread2({}, components), props.components);\n};\n\nexport { isMobileDevice as A, multiValueAsValue as B, singleValueAsValue as C, valueTernary as D, classNames as E, defaultComponents as F, notNullish as G, isDocumentElement as H, cleanValue as I, scrollIntoView as J, noop as K, handleInputChange as L, MenuPlacer as M, _createSuper as _, _objectSpread2 as a, clearIndicatorCSS as b, components as c, containerCSS as d, css$1 as e, dropdownIndicatorCSS as f, groupCSS as g, groupHeadingCSS as h, indicatorsContainerCSS as i, indicatorSeparatorCSS as j, inputCSS as k, loadingIndicatorCSS as l, loadingMessageCSS as m, menuCSS as n, menuListCSS as o, menuPortalCSS as p, multiValueCSS as q, multiValueLabelCSS as r, supportsPassiveEvents as s, multiValueRemoveCSS as t, noOptionsMessageCSS as u, optionCSS as v, placeholderCSS as w, css as x, valueContainerCSS as y, isTouchCapable as z };\n","export default function _taggedTemplateLiteral(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n return Object.freeze(Object.defineProperties(strings, {\n raw: {\n value: Object.freeze(raw)\n }\n }));\n}","function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\n\nmodule.exports = _interopRequireDefault;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import * as React from 'react';\nimport { createElement, useLayoutEffect, useContext, useRef, Fragment } from 'react';\nimport '@emotion/cache';\nimport { h as hasOwnProperty, E as Emotion, c as createEmotionProps, w as withEmotionCache, T as ThemeContext, u as useInsertionEffectMaybe } from './emotion-element-cbed451f.browser.esm.js';\nexport { C as CacheProvider, T as ThemeContext, b as ThemeProvider, _ as __unsafe_useEmotionCache, a as useTheme, w as withEmotionCache, d as withTheme } from './emotion-element-cbed451f.browser.esm.js';\nimport '@babel/runtime/helpers/extends';\nimport '@emotion/weak-memoize';\nimport 'hoist-non-react-statics';\nimport '../_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js';\nimport { insertStyles, registerStyles, getRegisteredStyles } from '@emotion/utils';\nimport { serializeStyles } from '@emotion/serialize';\n\nvar pkg = {\n\tname: \"@emotion/react\",\n\tversion: \"11.8.2\",\n\tmain: \"dist/emotion-react.cjs.js\",\n\tmodule: \"dist/emotion-react.esm.js\",\n\tbrowser: {\n\t\t\"./dist/emotion-react.cjs.js\": \"./dist/emotion-react.browser.cjs.js\",\n\t\t\"./dist/emotion-react.esm.js\": \"./dist/emotion-react.browser.esm.js\"\n\t},\n\ttypes: \"types/index.d.ts\",\n\tfiles: [\n\t\t\"src\",\n\t\t\"dist\",\n\t\t\"jsx-runtime\",\n\t\t\"jsx-dev-runtime\",\n\t\t\"_isolated-hnrs\",\n\t\t\"types/*.d.ts\",\n\t\t\"macro.js\",\n\t\t\"macro.d.ts\",\n\t\t\"macro.js.flow\"\n\t],\n\tsideEffects: false,\n\tauthor: \"Emotion Contributors\",\n\tlicense: \"MIT\",\n\tscripts: {\n\t\t\"test:typescript\": \"dtslint types\"\n\t},\n\tdependencies: {\n\t\t\"@babel/runtime\": \"^7.13.10\",\n\t\t\"@emotion/babel-plugin\": \"^11.7.1\",\n\t\t\"@emotion/cache\": \"^11.7.1\",\n\t\t\"@emotion/serialize\": \"^1.0.2\",\n\t\t\"@emotion/utils\": \"^1.1.0\",\n\t\t\"@emotion/weak-memoize\": \"^0.2.5\",\n\t\t\"hoist-non-react-statics\": \"^3.3.1\"\n\t},\n\tpeerDependencies: {\n\t\t\"@babel/core\": \"^7.0.0\",\n\t\treact: \">=16.8.0\"\n\t},\n\tpeerDependenciesMeta: {\n\t\t\"@babel/core\": {\n\t\t\toptional: true\n\t\t},\n\t\t\"@types/react\": {\n\t\t\toptional: true\n\t\t}\n\t},\n\tdevDependencies: {\n\t\t\"@babel/core\": \"^7.13.10\",\n\t\t\"@emotion/css\": \"11.7.1\",\n\t\t\"@emotion/css-prettifier\": \"1.0.1\",\n\t\t\"@emotion/server\": \"11.4.0\",\n\t\t\"@emotion/styled\": \"11.8.1\",\n\t\t\"@types/react\": \"^16.9.11\",\n\t\tdtslint: \"^4.2.1\",\n\t\t\"html-tag-names\": \"^1.1.2\",\n\t\treact: \"16.14.0\",\n\t\t\"svg-tag-names\": \"^1.1.1\",\n\t\ttypescript: \"^4.5.5\"\n\t},\n\trepository: \"https://github.com/emotion-js/emotion/tree/main/packages/react\",\n\tpublishConfig: {\n\t\taccess: \"public\"\n\t},\n\t\"umd:main\": \"dist/emotion-react.umd.min.js\",\n\tpreconstruct: {\n\t\tentrypoints: [\n\t\t\t\"./index.js\",\n\t\t\t\"./jsx-runtime.js\",\n\t\t\t\"./jsx-dev-runtime.js\",\n\t\t\t\"./_isolated-hnrs.js\"\n\t\t],\n\t\tumdName: \"emotionReact\"\n\t}\n};\n\nvar jsx = function jsx(type, props) {\n var args = arguments;\n\n if (props == null || !hasOwnProperty.call(props, 'css')) {\n // $FlowFixMe\n return createElement.apply(undefined, args);\n }\n\n var argsLength = args.length;\n var createElementArgArray = new Array(argsLength);\n createElementArgArray[0] = Emotion;\n createElementArgArray[1] = createEmotionProps(type, props);\n\n for (var i = 2; i < argsLength; i++) {\n createElementArgArray[i] = args[i];\n } // $FlowFixMe\n\n\n return createElement.apply(null, createElementArgArray);\n};\n\nvar useInsertionEffect = React['useInsertion' + 'Effect'] ? React['useInsertion' + 'Effect'] : useLayoutEffect;\nvar warnedAboutCssPropForGlobal = false; // maintain place over rerenders.\n// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild\n// initial client-side render from SSR, use place of hydrating tag\n\nvar Global = /* #__PURE__ */withEmotionCache(function (props, cache) {\n if (process.env.NODE_ENV !== 'production' && !warnedAboutCssPropForGlobal && ( // check for className as well since the user is\n // probably using the custom createElement which\n // means it will be turned into a className prop\n // $FlowFixMe I don't really want to add it to the type since it shouldn't be used\n props.className || props.css)) {\n console.error(\"It looks like you're using the css prop on Global, did you mean to use the styles prop instead?\");\n warnedAboutCssPropForGlobal = true;\n }\n\n var styles = props.styles;\n var serialized = serializeStyles([styles], undefined, useContext(ThemeContext));\n // but it is based on a constant that will never change at runtime\n // it's effectively like having two implementations and switching them out\n // so it's not actually breaking anything\n\n\n var sheetRef = useRef();\n useInsertionEffect(function () {\n var key = cache.key + \"-global\"; // use case of https://github.com/emotion-js/emotion/issues/2675\n\n var sheet = new cache.sheet.constructor({\n key: key,\n nonce: cache.sheet.nonce,\n container: cache.sheet.container,\n speedy: cache.sheet.isSpeedy\n });\n var rehydrating = false; // $FlowFixMe\n\n var node = document.querySelector(\"style[data-emotion=\\\"\" + key + \" \" + serialized.name + \"\\\"]\");\n\n if (cache.sheet.tags.length) {\n sheet.before = cache.sheet.tags[0];\n }\n\n if (node !== null) {\n rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other s\n\n node.setAttribute('data-emotion', key);\n sheet.hydrate([node]);\n }\n\n sheetRef.current = [sheet, rehydrating];\n return function () {\n sheet.flush();\n };\n }, [cache]);\n useInsertionEffect(function () {\n var sheetRefCurrent = sheetRef.current;\n var sheet = sheetRefCurrent[0],\n rehydrating = sheetRefCurrent[1];\n\n if (rehydrating) {\n sheetRefCurrent[1] = false;\n return;\n }\n\n if (serialized.next !== undefined) {\n // insert keyframes\n insertStyles(cache, serialized.next, true);\n }\n\n if (sheet.tags.length) {\n // if this doesn't exist then it will be null so the style element will be appended\n var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;\n sheet.before = element;\n sheet.flush();\n }\n\n cache.insert(\"\", serialized, sheet, false);\n }, [cache, serialized.name]);\n return null;\n});\n\nif (process.env.NODE_ENV !== 'production') {\n Global.displayName = 'EmotionGlobal';\n}\n\nfunction css() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return serializeStyles(args);\n}\n\nvar keyframes = function keyframes() {\n var insertable = css.apply(void 0, arguments);\n var name = \"animation-\" + insertable.name; // $FlowFixMe\n\n return {\n name: name,\n styles: \"@keyframes \" + name + \"{\" + insertable.styles + \"}\",\n anim: 1,\n toString: function toString() {\n return \"_EMO_\" + this.name + \"_\" + this.styles + \"_EMO_\";\n }\n };\n};\n\nvar classnames = function classnames(args) {\n var len = args.length;\n var i = 0;\n var cls = '';\n\n for (; i < len; i++) {\n var arg = args[i];\n if (arg == null) continue;\n var toAdd = void 0;\n\n switch (typeof arg) {\n case 'boolean':\n break;\n\n case 'object':\n {\n if (Array.isArray(arg)) {\n toAdd = classnames(arg);\n } else {\n if (process.env.NODE_ENV !== 'production' && arg.styles !== undefined && arg.name !== undefined) {\n console.error('You have passed styles created with `css` from `@emotion/react` package to the `cx`.\\n' + '`cx` is meant to compose class names (strings) so you should convert those styles to a class name by passing them to the `css` received from component.');\n }\n\n toAdd = '';\n\n for (var k in arg) {\n if (arg[k] && k) {\n toAdd && (toAdd += ' ');\n toAdd += k;\n }\n }\n }\n\n break;\n }\n\n default:\n {\n toAdd = arg;\n }\n }\n\n if (toAdd) {\n cls && (cls += ' ');\n cls += toAdd;\n }\n }\n\n return cls;\n};\n\nfunction merge(registered, css, className) {\n var registeredStyles = [];\n var rawClassName = getRegisteredStyles(registered, registeredStyles, className);\n\n if (registeredStyles.length < 2) {\n return className;\n }\n\n return rawClassName + css(registeredStyles);\n}\n\nvar Insertion = function Insertion(_ref) {\n var cache = _ref.cache,\n serializedArr = _ref.serializedArr;\n var rules = useInsertionEffectMaybe(function () {\n\n for (var i = 0; i < serializedArr.length; i++) {\n var res = insertStyles(cache, serializedArr[i], false);\n }\n });\n\n return null;\n};\n\nvar ClassNames = /* #__PURE__ */withEmotionCache(function (props, cache) {\n var hasRendered = false;\n var serializedArr = [];\n\n var css = function css() {\n if (hasRendered && process.env.NODE_ENV !== 'production') {\n throw new Error('css can only be used during render');\n }\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var serialized = serializeStyles(args, cache.registered);\n serializedArr.push(serialized); // registration has to happen here as the result of this might get consumed by `cx`\n\n registerStyles(cache, serialized, false);\n return cache.key + \"-\" + serialized.name;\n };\n\n var cx = function cx() {\n if (hasRendered && process.env.NODE_ENV !== 'production') {\n throw new Error('cx can only be used during render');\n }\n\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return merge(cache.registered, css, classnames(args));\n };\n\n var content = {\n css: css,\n cx: cx,\n theme: useContext(ThemeContext)\n };\n var ele = props.children(content);\n hasRendered = true;\n return /*#__PURE__*/createElement(Fragment, null, /*#__PURE__*/createElement(Insertion, {\n cache: cache,\n serializedArr: serializedArr\n }), ele);\n});\n\nif (process.env.NODE_ENV !== 'production') {\n ClassNames.displayName = 'EmotionClassNames';\n}\n\nif (process.env.NODE_ENV !== 'production') {\n var isBrowser = \"object\" !== 'undefined'; // #1727 for some reason Jest evaluates modules twice if some consuming module gets mocked with jest.mock\n\n var isJest = typeof jest !== 'undefined';\n\n if (isBrowser && !isJest) {\n // globalThis has wide browser support - https://caniuse.com/?search=globalThis, Node.js 12 and later\n var globalContext = // $FlowIgnore\n typeof globalThis !== 'undefined' ? globalThis // eslint-disable-line no-undef\n : isBrowser ? window : global;\n var globalKey = \"__EMOTION_REACT_\" + pkg.version.split('.')[0] + \"__\";\n\n if (globalContext[globalKey]) {\n console.warn('You are loading @emotion/react when it is already loaded. Running ' + 'multiple instances may cause problems. This can happen if multiple ' + 'versions are used, or if multiple builds of the same version are ' + 'used.');\n }\n\n globalContext[globalKey] = true;\n }\n}\n\nexport { ClassNames, Global, jsx as createElement, css, jsx, keyframes };\n","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function _typeof(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}","import _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport { generate as generateColor } from '@ant-design/colors';\nimport React, { useContext, useEffect } from 'react';\nimport warn from \"rc-util/es/warning\";\nimport { updateCSS } from \"rc-util/es/Dom/dynamicCSS\";\nimport IconContext from './components/Context';\nexport function warning(valid, message) {\n warn(valid, \"[@ant-design/icons] \".concat(message));\n}\nexport function isIconDefinition(target) {\n return _typeof(target) === 'object' && typeof target.name === 'string' && typeof target.theme === 'string' && (_typeof(target.icon) === 'object' || typeof target.icon === 'function');\n}\nexport function normalizeAttrs() {\n var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return Object.keys(attrs).reduce(function (acc, key) {\n var val = attrs[key];\n\n switch (key) {\n case 'class':\n acc.className = val;\n delete acc.class;\n break;\n\n default:\n acc[key] = val;\n }\n\n return acc;\n }, {});\n}\nexport function generate(node, key, rootProps) {\n if (!rootProps) {\n return /*#__PURE__*/React.createElement(node.tag, _objectSpread({\n key: key\n }, normalizeAttrs(node.attrs)), (node.children || []).map(function (child, index) {\n return generate(child, \"\".concat(key, \"-\").concat(node.tag, \"-\").concat(index));\n }));\n }\n\n return /*#__PURE__*/React.createElement(node.tag, _objectSpread(_objectSpread({\n key: key\n }, normalizeAttrs(node.attrs)), rootProps), (node.children || []).map(function (child, index) {\n return generate(child, \"\".concat(key, \"-\").concat(node.tag, \"-\").concat(index));\n }));\n}\nexport function getSecondaryColor(primaryColor) {\n // choose the second color\n return generateColor(primaryColor)[0];\n}\nexport function normalizeTwoToneColors(twoToneColor) {\n if (!twoToneColor) {\n return [];\n }\n\n return Array.isArray(twoToneColor) ? twoToneColor : [twoToneColor];\n} // These props make sure that the SVG behaviours like general text.\n// Reference: https://blog.prototypr.io/align-svg-icons-to-text-and-say-goodbye-to-font-icons-d44b3d7b26b4\n\nexport var svgBaseProps = {\n width: '1em',\n height: '1em',\n fill: 'currentColor',\n 'aria-hidden': 'true',\n focusable: 'false'\n};\nexport var iconStyles = \"\\n.anticon {\\n display: inline-block;\\n color: inherit;\\n font-style: normal;\\n line-height: 0;\\n text-align: center;\\n text-transform: none;\\n vertical-align: -0.125em;\\n text-rendering: optimizeLegibility;\\n -webkit-font-smoothing: antialiased;\\n -moz-osx-font-smoothing: grayscale;\\n}\\n\\n.anticon > * {\\n line-height: 1;\\n}\\n\\n.anticon svg {\\n display: inline-block;\\n}\\n\\n.anticon::before {\\n display: none;\\n}\\n\\n.anticon .anticon-icon {\\n display: block;\\n}\\n\\n.anticon[tabindex] {\\n cursor: pointer;\\n}\\n\\n.anticon-spin::before,\\n.anticon-spin {\\n display: inline-block;\\n -webkit-animation: loadingCircle 1s infinite linear;\\n animation: loadingCircle 1s infinite linear;\\n}\\n\\n@-webkit-keyframes loadingCircle {\\n 100% {\\n -webkit-transform: rotate(360deg);\\n transform: rotate(360deg);\\n }\\n}\\n\\n@keyframes loadingCircle {\\n 100% {\\n -webkit-transform: rotate(360deg);\\n transform: rotate(360deg);\\n }\\n}\\n\";\nexport var useInsertStyles = function useInsertStyles() {\n var styleStr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : iconStyles;\n\n var _useContext = useContext(IconContext),\n csp = _useContext.csp;\n\n useEffect(function () {\n updateCSS(styleStr, '@ant-design-icons', {\n prepend: true,\n csp: csp\n });\n }, []);\n};","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport { generate, getSecondaryColor, isIconDefinition, warning, useInsertStyles } from '../utils';\nvar twoToneColorPalette = {\n primaryColor: '#333',\n secondaryColor: '#E6E6E6',\n calculated: false\n};\n\nfunction setTwoToneColors(_ref) {\n var primaryColor = _ref.primaryColor,\n secondaryColor = _ref.secondaryColor;\n twoToneColorPalette.primaryColor = primaryColor;\n twoToneColorPalette.secondaryColor = secondaryColor || getSecondaryColor(primaryColor);\n twoToneColorPalette.calculated = !!secondaryColor;\n}\n\nfunction getTwoToneColors() {\n return _objectSpread({}, twoToneColorPalette);\n}\n\nvar IconBase = function IconBase(props) {\n var icon = props.icon,\n className = props.className,\n onClick = props.onClick,\n style = props.style,\n primaryColor = props.primaryColor,\n secondaryColor = props.secondaryColor,\n restProps = _objectWithoutProperties(props, [\"icon\", \"className\", \"onClick\", \"style\", \"primaryColor\", \"secondaryColor\"]);\n\n var colors = twoToneColorPalette;\n\n if (primaryColor) {\n colors = {\n primaryColor: primaryColor,\n secondaryColor: secondaryColor || getSecondaryColor(primaryColor)\n };\n }\n\n useInsertStyles();\n warning(isIconDefinition(icon), \"icon should be icon definiton, but got \".concat(icon));\n\n if (!isIconDefinition(icon)) {\n return null;\n }\n\n var target = icon;\n\n if (target && typeof target.icon === 'function') {\n target = _objectSpread(_objectSpread({}, target), {}, {\n icon: target.icon(colors.primaryColor, colors.secondaryColor)\n });\n }\n\n return generate(target.icon, \"svg-\".concat(target.name), _objectSpread({\n className: className,\n onClick: onClick,\n style: style,\n 'data-icon': target.name,\n width: '1em',\n height: '1em',\n fill: 'currentColor',\n 'aria-hidden': 'true'\n }, restProps));\n};\n\nIconBase.displayName = 'IconReact';\nIconBase.getTwoToneColors = getTwoToneColors;\nIconBase.setTwoToneColors = setTwoToneColors;\nexport default IconBase;","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport ReactIcon from './IconBase';\nimport { normalizeTwoToneColors } from '../utils';\nexport function setTwoToneColor(twoToneColor) {\n var _normalizeTwoToneColo = normalizeTwoToneColors(twoToneColor),\n _normalizeTwoToneColo2 = _slicedToArray(_normalizeTwoToneColo, 2),\n primaryColor = _normalizeTwoToneColo2[0],\n secondaryColor = _normalizeTwoToneColo2[1];\n\n return ReactIcon.setTwoToneColors({\n primaryColor: primaryColor,\n secondaryColor: secondaryColor\n });\n}\nexport function getTwoToneColor() {\n var colors = ReactIcon.getTwoToneColors();\n\n if (!colors.calculated) {\n return colors.primaryColor;\n }\n\n return [colors.primaryColor, colors.secondaryColor];\n}","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport Context from './Context';\nimport ReactIcon from './IconBase';\nimport { getTwoToneColor, setTwoToneColor } from './twoTonePrimaryColor';\nimport { normalizeTwoToneColors } from '../utils'; // Initial setting\n// should move it to antd main repo?\n\nsetTwoToneColor('#1890ff');\nvar Icon = /*#__PURE__*/React.forwardRef(function (props, ref) {\n var _classNames;\n\n var className = props.className,\n icon = props.icon,\n spin = props.spin,\n rotate = props.rotate,\n tabIndex = props.tabIndex,\n onClick = props.onClick,\n twoToneColor = props.twoToneColor,\n restProps = _objectWithoutProperties(props, [\"className\", \"icon\", \"spin\", \"rotate\", \"tabIndex\", \"onClick\", \"twoToneColor\"]);\n\n var _React$useContext = React.useContext(Context),\n _React$useContext$pre = _React$useContext.prefixCls,\n prefixCls = _React$useContext$pre === void 0 ? 'anticon' : _React$useContext$pre;\n\n var classString = classNames(prefixCls, (_classNames = {}, _defineProperty(_classNames, \"\".concat(prefixCls, \"-\").concat(icon.name), !!icon.name), _defineProperty(_classNames, \"\".concat(prefixCls, \"-spin\"), !!spin || icon.name === 'loading'), _classNames), className);\n var iconTabIndex = tabIndex;\n\n if (iconTabIndex === undefined && onClick) {\n iconTabIndex = -1;\n }\n\n var svgStyle = rotate ? {\n msTransform: \"rotate(\".concat(rotate, \"deg)\"),\n transform: \"rotate(\".concat(rotate, \"deg)\")\n } : undefined;\n\n var _normalizeTwoToneColo = normalizeTwoToneColors(twoToneColor),\n _normalizeTwoToneColo2 = _slicedToArray(_normalizeTwoToneColo, 2),\n primaryColor = _normalizeTwoToneColo2[0],\n secondaryColor = _normalizeTwoToneColo2[1];\n\n return /*#__PURE__*/React.createElement(\"span\", Object.assign({\n role: \"img\",\n \"aria-label\": icon.name\n }, restProps, {\n ref: ref,\n tabIndex: iconTabIndex,\n onClick: onClick,\n className: classString\n }), /*#__PURE__*/React.createElement(ReactIcon, {\n icon: icon,\n primaryColor: primaryColor,\n secondaryColor: secondaryColor,\n style: svgStyle\n }));\n});\nIcon.displayName = 'AntdIcon';\nIcon.getTwoToneColor = getTwoToneColor;\nIcon.setTwoToneColor = setTwoToneColor;\nexport default Icon;","import { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Returns a number whose value is limited to the given range.\n *\n * @param {number} value The value to be clamped\n * @param {number} min The lower boundary of the output range\n * @param {number} max The upper boundary of the output range\n * @returns {number} A number in the range [min, max]\n */\nfunction clamp(value) {\n var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (value < min || value > max) {\n console.error(\"Material-UI: The value provided \".concat(value, \" is out of range [\").concat(min, \", \").concat(max, \"].\"));\n }\n }\n\n return Math.min(Math.max(min, value), max);\n}\n/**\n * Converts a color from CSS hex format to CSS rgb format.\n *\n * @param {string} color - Hex color, i.e. #nnn or #nnnnnn\n * @returns {string} A CSS rgb color string\n */\n\n\nexport function hexToRgb(color) {\n color = color.substr(1);\n var re = new RegExp(\".{1,\".concat(color.length >= 6 ? 2 : 1, \"}\"), 'g');\n var colors = color.match(re);\n\n if (colors && colors[0].length === 1) {\n colors = colors.map(function (n) {\n return n + n;\n });\n }\n\n return colors ? \"rgb\".concat(colors.length === 4 ? 'a' : '', \"(\").concat(colors.map(function (n, index) {\n return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000;\n }).join(', '), \")\") : '';\n}\n\nfunction intToHex(int) {\n var hex = int.toString(16);\n return hex.length === 1 ? \"0\".concat(hex) : hex;\n}\n/**\n * Converts a color from CSS rgb format to CSS hex format.\n *\n * @param {string} color - RGB color, i.e. rgb(n, n, n)\n * @returns {string} A CSS rgb color string, i.e. #nnnnnn\n */\n\n\nexport function rgbToHex(color) {\n // Idempotent\n if (color.indexOf('#') === 0) {\n return color;\n }\n\n var _decomposeColor = decomposeColor(color),\n values = _decomposeColor.values;\n\n return \"#\".concat(values.map(function (n) {\n return intToHex(n);\n }).join(''));\n}\n/**\n * Converts a color from hsl format to rgb format.\n *\n * @param {string} color - HSL color values\n * @returns {string} rgb color values\n */\n\nexport function hslToRgb(color) {\n color = decomposeColor(color);\n var _color = color,\n values = _color.values;\n var h = values[0];\n var s = values[1] / 100;\n var l = values[2] / 100;\n var a = s * Math.min(l, 1 - l);\n\n var f = function f(n) {\n var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;\n return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n };\n\n var type = 'rgb';\n var rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];\n\n if (color.type === 'hsla') {\n type += 'a';\n rgb.push(values[3]);\n }\n\n return recomposeColor({\n type: type,\n values: rgb\n });\n}\n/**\n * Returns an object with the type and values of a color.\n *\n * Note: Does not support rgb % values.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {object} - A MUI color object: {type: string, values: number[]}\n */\n\nexport function decomposeColor(color) {\n // Idempotent\n if (color.type) {\n return color;\n }\n\n if (color.charAt(0) === '#') {\n return decomposeColor(hexToRgb(color));\n }\n\n var marker = color.indexOf('(');\n var type = color.substring(0, marker);\n\n if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: Unsupported `\".concat(color, \"` color.\\nWe support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().\") : _formatMuiErrorMessage(3, color));\n }\n\n var values = color.substring(marker + 1, color.length - 1).split(',');\n values = values.map(function (value) {\n return parseFloat(value);\n });\n return {\n type: type,\n values: values\n };\n}\n/**\n * Converts a color object with type and values to a string.\n *\n * @param {object} color - Decomposed color\n * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'\n * @param {array} color.values - [n,n,n] or [n,n,n,n]\n * @returns {string} A CSS color string\n */\n\nexport function recomposeColor(color) {\n var type = color.type;\n var values = color.values;\n\n if (type.indexOf('rgb') !== -1) {\n // Only convert the first 3 values to int (i.e. not alpha)\n values = values.map(function (n, i) {\n return i < 3 ? parseInt(n, 10) : n;\n });\n } else if (type.indexOf('hsl') !== -1) {\n values[1] = \"\".concat(values[1], \"%\");\n values[2] = \"\".concat(values[2], \"%\");\n }\n\n return \"\".concat(type, \"(\").concat(values.join(', '), \")\");\n}\n/**\n * Calculates the contrast ratio between two colors.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} A contrast ratio value in the range 0 - 21.\n */\n\nexport function getContrastRatio(foreground, background) {\n var lumA = getLuminance(foreground);\n var lumB = getLuminance(background);\n return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n}\n/**\n * The relative brightness of any point in a color space,\n * normalized to 0 for darkest black and 1 for lightest white.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} The relative brightness of the color in the range 0 - 1\n */\n\nexport function getLuminance(color) {\n color = decomposeColor(color);\n var rgb = color.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : color.values;\n rgb = rgb.map(function (val) {\n val /= 255; // normalized\n\n return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);\n }); // Truncate at 3 digits\n\n return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));\n}\n/**\n * Darken or lighten a color, depending on its luminance.\n * Light colors are darkened, dark colors are lightened.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient=0.15 - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function emphasize(color) {\n var coefficient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.15;\n return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);\n}\nvar warnedOnce = false;\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha values are overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0 -1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n *\n * @deprecated\n * Use `import { alpha } from '@material-ui/core/styles'` instead.\n */\n\nexport function fade(color, value) {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n warnedOnce = true;\n console.error(['Material-UI: The `fade` color utility was renamed to `alpha` to better describe its functionality.', '', \"You should use `import { alpha } from '@material-ui/core/styles'`\"].join('\\n'));\n }\n }\n\n return alpha(color, value);\n}\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha value is overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0-1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function alpha(color, value) {\n color = decomposeColor(color);\n value = clamp(value);\n\n if (color.type === 'rgb' || color.type === 'hsl') {\n color.type += 'a';\n }\n\n color.values[3] = value;\n return recomposeColor(color);\n}\n/**\n * Darkens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function darken(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] *= 1 - coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] *= 1 - coefficient;\n }\n }\n\n return recomposeColor(color);\n}\n/**\n * Lightens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function lighten(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] += (100 - color.values[2]) * coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] += (255 - color.values[i]) * coefficient;\n }\n }\n\n return recomposeColor(color);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}","var raf = function raf(callback) {\n return +setTimeout(callback, 16);\n};\n\nvar caf = function caf(num) {\n return clearTimeout(num);\n};\n\nif (typeof window !== 'undefined' && 'requestAnimationFrame' in window) {\n raf = function raf(callback) {\n return window.requestAnimationFrame(callback);\n };\n\n caf = function caf(handle) {\n return window.cancelAnimationFrame(handle);\n };\n}\n\nvar rafUUID = 0;\nvar rafIds = new Map();\n\nfunction cleanup(id) {\n rafIds.delete(id);\n}\n\nexport default function wrapperRaf(callback) {\n var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n rafUUID += 1;\n var id = rafUUID;\n\n function callRef(leftTimes) {\n if (leftTimes === 0) {\n // Clean up\n cleanup(id); // Trigger\n\n callback();\n } else {\n // Next raf\n var realId = raf(function () {\n callRef(leftTimes - 1);\n }); // Bind real raf id\n\n rafIds.set(id, realId);\n }\n }\n\n callRef(times);\n return id;\n}\n\nwrapperRaf.cancel = function (id) {\n var realId = rafIds.get(id);\n cleanup(realId);\n return caf(realId);\n};","import { insertPlugin, removePlugin } from './utils';\nimport { Getters } from '@devexpress/dx-react-core';\n\nconst getDependencyError = (\n pluginName, dependencyName,\n ) => new Error(\n `The '${pluginName}' plugin requires '${dependencyName}' to be defined before it.`,\n );\n\n/** @internal */\nexport type PluginPositionFn = () => number[];\n\nexport interface IDependency { name: string; optional?: boolean; }\n\n/** @internal */\nexport type InnerPlugin = {\n position: PluginPositionFn;\n name?: string;\n dependencies?: IDependency[];\n} & Getters;\n\n/** @internal */\nexport class PluginHost {\n private plugins: InnerPlugin[];\n private subscriptions: Set;\n private gettersCache: object = {};\n private knownKeysCache: object = {};\n private validationRequired: boolean = true;\n\n constructor() {\n this.plugins = [];\n this.subscriptions = new Set();\n }\n\n ensureDependencies() {\n const defined: Set = new Set();\n const knownOptionals: Map = new Map();\n this.plugins\n .filter(plugin => plugin.container)\n .forEach((plugin) => {\n const pluginName = plugin.name || '';\n if (knownOptionals.has(pluginName)) {\n throw (getDependencyError(knownOptionals.get(pluginName), pluginName));\n }\n\n (plugin.dependencies || [])\n .forEach((dependency) => {\n if (defined.has(dependency.name)) return;\n if (dependency.optional) {\n if (!knownOptionals.has(dependency.name)) {\n knownOptionals.set(dependency.name, pluginName);\n }\n return;\n }\n throw (getDependencyError(pluginName, dependency.name));\n });\n\n defined.add(pluginName);\n });\n }\n\n registerPlugin(plugin) {\n this.plugins = insertPlugin(this.plugins, plugin);\n this.cleanPluginsCache();\n }\n\n unregisterPlugin(plugin) {\n this.plugins = removePlugin(this.plugins, plugin);\n this.cleanPluginsCache();\n }\n\n knownKeys(postfix) {\n if (!this.knownKeysCache[postfix]) {\n this.knownKeysCache[postfix] = Array.from(this.plugins\n .map(plugin => Object.keys(plugin))\n .map(keys => keys.filter(key => key.endsWith(postfix))[0])\n .filter(key => !!key)\n .reduce((acc, key) => acc.add(key), new Set()))\n .map(key => key.replace(postfix, ''));\n }\n return this.knownKeysCache[postfix];\n }\n\n collect(key, upTo?) {\n if (this.validationRequired) {\n this.ensureDependencies();\n this.validationRequired = false;\n }\n\n let res = this.gettersCache[key];\n if (!res) {\n // Add cache for original plugin indexes\n const indexCache = this.plugins\n .map((plugin, index) => ({ key: plugin[key], index }))\n .filter(plugin => !!plugin.key);\n this.gettersCache[`${key}_i`] = indexCache;\n res = indexCache.map(item => item.key);\n this.gettersCache[key] = res;\n }\n\n if (!upTo) return res;\n\n const upToIndex = this.plugins.indexOf(upTo);\n\n // Try to get a result from upToIndex cache first.\n const upToIndexKey = key + upToIndex;\n let upToRes = this.gettersCache[upToIndexKey];\n\n if (!upToRes) {\n const indexCache = this.gettersCache[`${key}_i`];\n upToRes = this.gettersCache[key]\n .filter((getter, index) => indexCache[index].index < upToIndex);\n this.gettersCache[upToIndexKey] = upToRes;\n }\n\n return upToRes;\n }\n\n get(key, upTo) {\n const plugins = this.collect(key, upTo);\n\n if (!plugins.length) return undefined;\n\n let result;\n // slice creates shallow copy, when do it many times, it costs about 5%\n plugins.forEach((plugin) => {\n result = plugin(result);\n });\n return result;\n }\n\n registerSubscription(subscription) {\n this.subscriptions.add(subscription);\n }\n\n unregisterSubscription(subscription) {\n this.subscriptions.delete(subscription);\n }\n\n broadcast(event, message?: any) {\n this.subscriptions.forEach(subscription => subscription[event] && subscription[event](message));\n }\n\n private cleanPluginsCache() {\n this.validationRequired = true;\n this.gettersCache = {};\n this.knownKeysCache = {};\n }\n}\n","type Handler = (e: object) => void;\n\n/** @internal */\nexport class EventEmitter {\n private handlers: Handler[];\n\n constructor() {\n this.handlers = [];\n }\n\n emit(e) {\n this.handlers.forEach(handler => handler(e));\n }\n\n subscribe(handler) {\n this.handlers.push(handler);\n }\n\n unsubscribe(handler) {\n this.handlers.splice(this.handlers.indexOf(handler), 1);\n }\n}\n","/** @internal */\nexport const shallowEqual = (objA, objB) => {\n if (objA === objB) {\n return true;\n }\n\n const keysA = Object.keys(objA);\n const keysB = Object.keys(objB);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n // Test for A's keys different from B.\n const hasOwn = Object.prototype.hasOwnProperty;\n // tslint:disable-next-line: prefer-for-of\n for (let i = 0; i < keysA.length; i += 1) {\n if (!hasOwn.call(objB, keysA[i])\n || objA[keysA[i]] !== objB[keysA[i]]) {\n return false;\n }\n\n const valA = objA[keysA[i]];\n const valB = objB[keysA[i]];\n\n if (valA !== valB) {\n return false;\n }\n }\n\n return true;\n};\n\n/** @internal */\nexport const argumentsShallowEqual = (prev, next) => {\n if (prev === null || next === null || prev.length !== next.length) {\n return false;\n }\n\n for (let i = 0; i < prev.length; i += 1) {\n if (prev[i] !== next[i]) {\n return false;\n }\n }\n\n return true;\n};\n","import { argumentsShallowEqual } from './shallow-equal';\n\n/** @internal */\nexport const memoize = (func) => {\n let lastArgs: any = null;\n let lastResult: ReturnType = null;\n return (...args) => {\n if (lastArgs === null || !argumentsShallowEqual(lastArgs, args)) {\n lastResult = func(...args);\n }\n lastArgs = args;\n return lastResult;\n };\n};\n","import { GetMessagesFormatterFn } from './types';\n\nconst processPattern = (pattern, params) => Object.keys(params).reduce(\n (msg, key) => msg.replace(`{${key}}`, params[key]),\n pattern,\n);\n\n/** @internal */\nexport const getMessagesFormatter: GetMessagesFormatterFn = messages => (key, params?) => {\n const message = messages[key];\n\n if (typeof message === 'function') {\n return message(params);\n }\n if (params) {\n return processPattern(message, params);\n }\n return message ?? '';\n};\n","/* eslint-disable no-console */\nvar warned = {};\nexport function warning(valid, message) {\n // Support uglify\n if (process.env.NODE_ENV !== 'production' && !valid && console !== undefined) {\n console.error(\"Warning: \".concat(message));\n }\n}\nexport function note(valid, message) {\n // Support uglify\n if (process.env.NODE_ENV !== 'production' && !valid && console !== undefined) {\n console.warn(\"Note: \".concat(message));\n }\n}\nexport function resetWarned() {\n warned = {};\n}\nexport function call(method, valid, message) {\n if (!valid && !warned[message]) {\n method(false, message);\n warned[message] = true;\n }\n}\nexport function warningOnce(valid, message) {\n call(warning, valid, message);\n}\nexport function noteOnce(valid, message) {\n call(note, valid, message);\n}\nexport default warningOnce;\n/* eslint-enable */","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.js\";\nexport default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}","/**\n * @ignore\n * some key-codes definition and utils from closure-library\n * @author yiminghe@gmail.com\n */\nvar KeyCode = {\n /**\n * MAC_ENTER\n */\n MAC_ENTER: 3,\n\n /**\n * BACKSPACE\n */\n BACKSPACE: 8,\n\n /**\n * TAB\n */\n TAB: 9,\n\n /**\n * NUMLOCK on FF/Safari Mac\n */\n NUM_CENTER: 12,\n\n /**\n * ENTER\n */\n ENTER: 13,\n\n /**\n * SHIFT\n */\n SHIFT: 16,\n\n /**\n * CTRL\n */\n CTRL: 17,\n\n /**\n * ALT\n */\n ALT: 18,\n\n /**\n * PAUSE\n */\n PAUSE: 19,\n\n /**\n * CAPS_LOCK\n */\n CAPS_LOCK: 20,\n\n /**\n * ESC\n */\n ESC: 27,\n\n /**\n * SPACE\n */\n SPACE: 32,\n\n /**\n * PAGE_UP\n */\n PAGE_UP: 33,\n\n /**\n * PAGE_DOWN\n */\n PAGE_DOWN: 34,\n\n /**\n * END\n */\n END: 35,\n\n /**\n * HOME\n */\n HOME: 36,\n\n /**\n * LEFT\n */\n LEFT: 37,\n\n /**\n * UP\n */\n UP: 38,\n\n /**\n * RIGHT\n */\n RIGHT: 39,\n\n /**\n * DOWN\n */\n DOWN: 40,\n\n /**\n * PRINT_SCREEN\n */\n PRINT_SCREEN: 44,\n\n /**\n * INSERT\n */\n INSERT: 45,\n\n /**\n * DELETE\n */\n DELETE: 46,\n\n /**\n * ZERO\n */\n ZERO: 48,\n\n /**\n * ONE\n */\n ONE: 49,\n\n /**\n * TWO\n */\n TWO: 50,\n\n /**\n * THREE\n */\n THREE: 51,\n\n /**\n * FOUR\n */\n FOUR: 52,\n\n /**\n * FIVE\n */\n FIVE: 53,\n\n /**\n * SIX\n */\n SIX: 54,\n\n /**\n * SEVEN\n */\n SEVEN: 55,\n\n /**\n * EIGHT\n */\n EIGHT: 56,\n\n /**\n * NINE\n */\n NINE: 57,\n\n /**\n * QUESTION_MARK\n */\n QUESTION_MARK: 63,\n\n /**\n * A\n */\n A: 65,\n\n /**\n * B\n */\n B: 66,\n\n /**\n * C\n */\n C: 67,\n\n /**\n * D\n */\n D: 68,\n\n /**\n * E\n */\n E: 69,\n\n /**\n * F\n */\n F: 70,\n\n /**\n * G\n */\n G: 71,\n\n /**\n * H\n */\n H: 72,\n\n /**\n * I\n */\n I: 73,\n\n /**\n * J\n */\n J: 74,\n\n /**\n * K\n */\n K: 75,\n\n /**\n * L\n */\n L: 76,\n\n /**\n * M\n */\n M: 77,\n\n /**\n * N\n */\n N: 78,\n\n /**\n * O\n */\n O: 79,\n\n /**\n * P\n */\n P: 80,\n\n /**\n * Q\n */\n Q: 81,\n\n /**\n * R\n */\n R: 82,\n\n /**\n * S\n */\n S: 83,\n\n /**\n * T\n */\n T: 84,\n\n /**\n * U\n */\n U: 85,\n\n /**\n * V\n */\n V: 86,\n\n /**\n * W\n */\n W: 87,\n\n /**\n * X\n */\n X: 88,\n\n /**\n * Y\n */\n Y: 89,\n\n /**\n * Z\n */\n Z: 90,\n\n /**\n * META\n */\n META: 91,\n\n /**\n * WIN_KEY_RIGHT\n */\n WIN_KEY_RIGHT: 92,\n\n /**\n * CONTEXT_MENU\n */\n CONTEXT_MENU: 93,\n\n /**\n * NUM_ZERO\n */\n NUM_ZERO: 96,\n\n /**\n * NUM_ONE\n */\n NUM_ONE: 97,\n\n /**\n * NUM_TWO\n */\n NUM_TWO: 98,\n\n /**\n * NUM_THREE\n */\n NUM_THREE: 99,\n\n /**\n * NUM_FOUR\n */\n NUM_FOUR: 100,\n\n /**\n * NUM_FIVE\n */\n NUM_FIVE: 101,\n\n /**\n * NUM_SIX\n */\n NUM_SIX: 102,\n\n /**\n * NUM_SEVEN\n */\n NUM_SEVEN: 103,\n\n /**\n * NUM_EIGHT\n */\n NUM_EIGHT: 104,\n\n /**\n * NUM_NINE\n */\n NUM_NINE: 105,\n\n /**\n * NUM_MULTIPLY\n */\n NUM_MULTIPLY: 106,\n\n /**\n * NUM_PLUS\n */\n NUM_PLUS: 107,\n\n /**\n * NUM_MINUS\n */\n NUM_MINUS: 109,\n\n /**\n * NUM_PERIOD\n */\n NUM_PERIOD: 110,\n\n /**\n * NUM_DIVISION\n */\n NUM_DIVISION: 111,\n\n /**\n * F1\n */\n F1: 112,\n\n /**\n * F2\n */\n F2: 113,\n\n /**\n * F3\n */\n F3: 114,\n\n /**\n * F4\n */\n F4: 115,\n\n /**\n * F5\n */\n F5: 116,\n\n /**\n * F6\n */\n F6: 117,\n\n /**\n * F7\n */\n F7: 118,\n\n /**\n * F8\n */\n F8: 119,\n\n /**\n * F9\n */\n F9: 120,\n\n /**\n * F10\n */\n F10: 121,\n\n /**\n * F11\n */\n F11: 122,\n\n /**\n * F12\n */\n F12: 123,\n\n /**\n * NUMLOCK\n */\n NUMLOCK: 144,\n\n /**\n * SEMICOLON\n */\n SEMICOLON: 186,\n\n /**\n * DASH\n */\n DASH: 189,\n\n /**\n * EQUALS\n */\n EQUALS: 187,\n\n /**\n * COMMA\n */\n COMMA: 188,\n\n /**\n * PERIOD\n */\n PERIOD: 190,\n\n /**\n * SLASH\n */\n SLASH: 191,\n\n /**\n * APOSTROPHE\n */\n APOSTROPHE: 192,\n\n /**\n * SINGLE_QUOTE\n */\n SINGLE_QUOTE: 222,\n\n /**\n * OPEN_SQUARE_BRACKET\n */\n OPEN_SQUARE_BRACKET: 219,\n\n /**\n * BACKSLASH\n */\n BACKSLASH: 220,\n\n /**\n * CLOSE_SQUARE_BRACKET\n */\n CLOSE_SQUARE_BRACKET: 221,\n\n /**\n * WIN_KEY\n */\n WIN_KEY: 224,\n\n /**\n * MAC_FF_META\n */\n MAC_FF_META: 224,\n\n /**\n * WIN_IME\n */\n WIN_IME: 229,\n // ======================== Function ========================\n\n /**\n * whether text and modified key is entered at the same time.\n */\n isTextModifyingKeyEvent: function isTextModifyingKeyEvent(e) {\n var keyCode = e.keyCode;\n\n if (e.altKey && !e.ctrlKey || e.metaKey || // Function keys don't generate text\n keyCode >= KeyCode.F1 && keyCode <= KeyCode.F12) {\n return false;\n } // The following keys are quite harmless, even in combination with\n // CTRL, ALT or SHIFT.\n\n\n switch (keyCode) {\n case KeyCode.ALT:\n case KeyCode.CAPS_LOCK:\n case KeyCode.CONTEXT_MENU:\n case KeyCode.CTRL:\n case KeyCode.DOWN:\n case KeyCode.END:\n case KeyCode.ESC:\n case KeyCode.HOME:\n case KeyCode.INSERT:\n case KeyCode.LEFT:\n case KeyCode.MAC_FF_META:\n case KeyCode.META:\n case KeyCode.NUMLOCK:\n case KeyCode.NUM_CENTER:\n case KeyCode.PAGE_DOWN:\n case KeyCode.PAGE_UP:\n case KeyCode.PAUSE:\n case KeyCode.PRINT_SCREEN:\n case KeyCode.RIGHT:\n case KeyCode.SHIFT:\n case KeyCode.UP:\n case KeyCode.WIN_KEY:\n case KeyCode.WIN_KEY_RIGHT:\n return false;\n\n default:\n return true;\n }\n },\n\n /**\n * whether character is entered.\n */\n isCharacterKey: function isCharacterKey(keyCode) {\n if (keyCode >= KeyCode.ZERO && keyCode <= KeyCode.NINE) {\n return true;\n }\n\n if (keyCode >= KeyCode.NUM_ZERO && keyCode <= KeyCode.NUM_MULTIPLY) {\n return true;\n }\n\n if (keyCode >= KeyCode.A && keyCode <= KeyCode.Z) {\n return true;\n } // Safari sends zero key code for non-latin characters.\n\n\n if (window.navigator.userAgent.indexOf('WebKit') !== -1 && keyCode === 0) {\n return true;\n }\n\n switch (keyCode) {\n case KeyCode.SPACE:\n case KeyCode.QUESTION_MARK:\n case KeyCode.NUM_PLUS:\n case KeyCode.NUM_MINUS:\n case KeyCode.NUM_PERIOD:\n case KeyCode.NUM_DIVISION:\n case KeyCode.SEMICOLON:\n case KeyCode.DASH:\n case KeyCode.EQUALS:\n case KeyCode.COMMA:\n case KeyCode.PERIOD:\n case KeyCode.SLASH:\n case KeyCode.APOSTROPHE:\n case KeyCode.SINGLE_QUOTE:\n case KeyCode.OPEN_SQUARE_BRACKET:\n case KeyCode.BACKSLASH:\n case KeyCode.CLOSE_SQUARE_BRACKET:\n return true;\n\n default:\n return false;\n }\n }\n};\nexport default KeyCode;","export default function chainPropTypes(propType1, propType2) {\n if (process.env.NODE_ENV === 'production') {\n return function () {\n return null;\n };\n }\n\n return function validate() {\n return propType1.apply(void 0, arguments) || propType2.apply(void 0, arguments);\n };\n}","import PropTypes from 'prop-types';\nimport chainPropTypes from './chainPropTypes';\n\nfunction isClassComponent(elementType) {\n // elementType.prototype?.isReactComponent\n var _elementType$prototyp = elementType.prototype,\n prototype = _elementType$prototyp === void 0 ? {} : _elementType$prototyp;\n return Boolean(prototype.isReactComponent);\n}\n\nfunction acceptingRef(props, propName, componentName, location, propFullName) {\n var element = props[propName];\n var safePropName = propFullName || propName;\n\n if (element == null) {\n return null;\n }\n\n var warningHint;\n var elementType = element.type;\n /**\n * Blacklisting instead of whitelisting\n *\n * Blacklisting will miss some components, such as React.Fragment. Those will at least\n * trigger a warning in React.\n * We can't whitelist because there is no safe way to detect React.forwardRef\n * or class components. \"Safe\" means there's no public API.\n *\n */\n\n if (typeof elementType === 'function' && !isClassComponent(elementType)) {\n warningHint = 'Did you accidentally use a plain function component for an element instead?';\n }\n\n if (warningHint !== undefined) {\n return new Error(\"Invalid \".concat(location, \" `\").concat(safePropName, \"` supplied to `\").concat(componentName, \"`. \") + \"Expected an element that can hold a ref. \".concat(warningHint, \" \") + 'For more information see https://material-ui.com/r/caveat-with-refs-guide');\n }\n\n return null;\n}\n\nvar elementAcceptingRef = chainPropTypes(PropTypes.element, acceptingRef);\nelementAcceptingRef.isRequired = chainPropTypes(PropTypes.element.isRequired, acceptingRef);\nexport default elementAcceptingRef;","import * as PropTypes from 'prop-types';\nimport chainPropTypes from './chainPropTypes';\n\nfunction isClassComponent(elementType) {\n // elementType.prototype?.isReactComponent\n var _elementType$prototyp = elementType.prototype,\n prototype = _elementType$prototyp === void 0 ? {} : _elementType$prototyp;\n return Boolean(prototype.isReactComponent);\n}\n\nfunction elementTypeAcceptingRef(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n var safePropName = propFullName || propName;\n\n if (propValue == null) {\n return null;\n }\n\n var warningHint;\n /**\n * Blacklisting instead of whitelisting\n *\n * Blacklisting will miss some components, such as React.Fragment. Those will at least\n * trigger a warning in React.\n * We can't whitelist because there is no safe way to detect React.forwardRef\n * or class components. \"Safe\" means there's no public API.\n *\n */\n\n if (typeof propValue === 'function' && !isClassComponent(propValue)) {\n warningHint = 'Did you accidentally provide a plain function component instead?';\n }\n\n if (warningHint !== undefined) {\n return new Error(\"Invalid \".concat(location, \" `\").concat(safePropName, \"` supplied to `\").concat(componentName, \"`. \") + \"Expected an element type that can hold a ref. \".concat(warningHint, \" \") + 'For more information see https://material-ui.com/r/caveat-with-refs-guide');\n }\n\n return null;\n}\n\nexport default chainPropTypes(PropTypes.elementType, elementTypeAcceptingRef);","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\n// This module is based on https://github.com/airbnb/prop-types-exact repository.\n// However, in order to reduce the number of dependencies and to remove some extra safe checks\n// the module was forked.\n// Only exported for test purposes.\nexport var specialProperty = \"exact-prop: \\u200B\";\nexport default function exactProp(propTypes) {\n if (process.env.NODE_ENV === 'production') {\n return propTypes;\n }\n\n return _extends({}, propTypes, _defineProperty({}, specialProperty, function (props) {\n var unsupportedProps = Object.keys(props).filter(function (prop) {\n return !propTypes.hasOwnProperty(prop);\n });\n\n if (unsupportedProps.length > 0) {\n return new Error(\"The following props are not supported: \".concat(unsupportedProps.map(function (prop) {\n return \"`\".concat(prop, \"`\");\n }).join(', '), \". Please remove them.\"));\n }\n\n return null;\n }));\n}","import _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport { ForwardRef, Memo } from 'react-is'; // Simplified polyfill for IE 11 support\n// https://github.com/JamesMGreene/Function.name/blob/58b314d4a983110c3682f1228f845d39ccca1817/Function.name.js#L3\n\nvar fnNameMatchRegex = /^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^(\\s/]*)\\s*/;\nexport function getFunctionName(fn) {\n var match = \"\".concat(fn).match(fnNameMatchRegex);\n var name = match && match[1];\n return name || '';\n}\n/**\n * @param {function} Component\n * @param {string} fallback\n * @returns {string | undefined}\n */\n\nfunction getFunctionComponentName(Component) {\n var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n return Component.displayName || Component.name || getFunctionName(Component) || fallback;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var functionName = getFunctionComponentName(innerType);\n return outerType.displayName || (functionName !== '' ? \"\".concat(wrapperName, \"(\").concat(functionName, \")\") : wrapperName);\n}\n/**\n * cherry-pick from\n * https://github.com/facebook/react/blob/769b1f270e1251d9dbdce0fcbd9e92e502d059b8/packages/shared/getComponentName.js\n * originally forked from recompose/getDisplayName with added IE 11 support\n *\n * @param {React.ReactType} Component\n * @returns {string | undefined}\n */\n\n\nexport default function getDisplayName(Component) {\n if (Component == null) {\n return undefined;\n }\n\n if (typeof Component === 'string') {\n return Component;\n }\n\n if (typeof Component === 'function') {\n return getFunctionComponentName(Component, 'Component');\n }\n\n if (_typeof(Component) === 'object') {\n switch (Component.$$typeof) {\n case ForwardRef:\n return getWrappedName(Component, Component.render, 'ForwardRef');\n\n case Memo:\n return getWrappedName(Component, Component.type, 'memo');\n\n default:\n return undefined;\n }\n }\n\n return undefined;\n}","export default function HTMLElementType(props, propName, componentName, location, propFullName) {\n if (process.env.NODE_ENV === 'production') {\n return null;\n }\n\n var propValue = props[propName];\n var safePropName = propFullName || propName;\n\n if (propValue == null) {\n return null;\n }\n\n if (propValue && propValue.nodeType !== 1) {\n return new Error(\"Invalid \".concat(location, \" `\").concat(safePropName, \"` supplied to `\").concat(componentName, \"`. \") + \"Expected an HTMLElement.\");\n }\n\n return null;\n}","/* eslint-disable */\n// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nexport default typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();","import PropTypes from 'prop-types';\nvar refType = PropTypes.oneOfType([PropTypes.func, PropTypes.object]);\nexport default refType;","import * as React from 'react';\nimport {\n Plugin, Getter, Template, TemplatePlaceholder,\n} from '@devexpress/dx-react-core';\nimport { appointments, formatDateTimeGetter } from '@devexpress/dx-scheduler-core';\nimport { SchedulerProps } from '../types';\nimport { memoize } from '@devexpress/dx-core';\n\nclass SchedulerCoreBase extends React.PureComponent {\n formatDateTimeGetter = memoize(locale => formatDateTimeGetter(locale));\n\n render() {\n const {\n data,\n rootComponent: Root,\n locale,\n height,\n firstDayOfWeek,\n } = this.props;\n\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n );\n }\n}\n\n/***\n * The Scheduler is a root container component designed to process\n * and display the specified data. The Scheduler's functionality\n * (data visualization and processing) is implemented in several plugins\n * specified as child components.\n * */\nexport const SchedulerCore: React.ComponentType = SchedulerCoreBase;\n","import * as React from 'react';\nimport { PluginHost } from '@devexpress/dx-react-core';\nimport { SchedulerCore } from './plugins/scheduler-core';\nimport { SchedulerProps } from './types';\n\nconst SchedulerBase: React.SFC = ({\n data,\n rootComponent,\n children,\n locale,\n height,\n firstDayOfWeek,\n}) => (\n \n \n {children}\n \n);\n\nSchedulerBase.defaultProps = {\n data: [],\n locale: 'en-US',\n height: 'auto',\n firstDayOfWeek: 0,\n};\n\n// tslint:disable: max-line-length\n/***\n * The Scheduler is a root container component designed to process\n * and display the specified data. The Scheduler’s functionality\n * (data visualization and processing) is implemented in several plugins specified as child components.\n * */\nexport const Scheduler: React.ComponentType = SchedulerBase;\n","import * as React from 'react';\nimport {\n Template,\n Plugin,\n Getter,\n TemplateConnector,\n TemplatePlaceholder,\n ComputedFn,\n} from '@devexpress/dx-react-core';\nimport {\n computed,\n startViewDate as startViewDateCore,\n endViewDate as endViewDateCore,\n availableViews as availableViewsCore,\n HORIZONTAL_GROUP_ORIENTATION,\n VERTICAL_GROUP_ORIENTATION,\n} from '@devexpress/dx-scheduler-core';\nimport { memoize } from '@devexpress/dx-core';\nimport { BasicViewProps, BasicViewState, ScrollingStrategy } from '../types';\n\nconst CellPlaceholder = params => ;\nconst TimeTableAppointmentLayer = () => ;\n\nconst startViewDateBaseComputed = ({ viewCellsData }) => startViewDateCore(viewCellsData);\nconst endViewDateBaseComputed = ({ viewCellsData }) => endViewDateCore(viewCellsData);\n\nconst TimeTablePlaceholder = () => ;\nconst DayScalePlaceholder = () => ;\nconst DayScaleEmptyCellPlaceholder = () => ;\n\nconst GroupingPanelPlaceholder = () => ;\n\nclass BasicViewBase extends React.PureComponent {\n state = {\n timeTableElementsMeta: {},\n scrollingStrategy: {\n topBoundary: 0,\n bottomBoundary: 0,\n leftBoundary: 0,\n rightBoundary: 0,\n changeVerticalScroll: () => undefined,\n changeHorizontalScroll: () => undefined,\n },\n previousTimeTableCell: null,\n // The key has to be generated every time the TimeTableCell is updated to rerender TimeTable\n // and, consequently, update timeTableElementsMeta\n timeTableLayoutKey: 0,\n };\n\n static getDerivedStateFromProps(\n props: BasicViewProps, state: BasicViewState,\n ): BasicViewState | null {\n\n if (props.timeTableCellComponent !== state.previousTimeTableCell) {\n return {\n ...state,\n previousTimeTableCell: props.timeTableCellComponent,\n timeTableLayoutKey: Math.random(),\n };\n }\n return null;\n }\n\n scrollingStrategyComputed = memoize((viewName, scrollingStrategy) => getters =>\n computed(getters, viewName!, () => scrollingStrategy, getters.scrollingStrategy));\n\n timeTableElementsMetaComputed = memoize((viewName, timeTableElementsMeta) => getters =>\n computed(getters, viewName!, () => timeTableElementsMeta, getters.timeTableElementsMeta));\n\n intervalCountComputed = memoize((viewName, intervalCount) => getters =>\n computed(getters, viewName!, () => intervalCount, getters.intervalCount));\n\n cellDurationComputed = memoize((viewName, cellDuration) => getters =>\n computed(getters, viewName, () => cellDuration, getters.cellDuration));\n\n excludedDaysComputed = memoize((viewName, excludedDays) => getters => computed(\n getters, viewName!, () => excludedDays, getters.excludedDays,\n ));\n\n availableViewsComputed = memoize((viewName, viewDisplayName) => ({ availableViews }) =>\n availableViewsCore(availableViews, viewName!, viewDisplayName));\n\n currentViewComputed = memoize((viewName, viewDisplayName, type) => ({ currentView }) => (\n currentView && currentView.name !== viewName\n ? currentView\n : { name: viewName, type, displayName: viewDisplayName }\n ));\n\n endViewDateComputed: ComputedFn = (getters) => {\n const { name: viewName } = this.props;\n return computed(\n getters, viewName!, endViewDateBaseComputed, getters.endViewDate,\n );\n }\n\n startViewDateComputed: ComputedFn = (getters) => {\n const { name: viewName } = this.props;\n return computed(\n getters, viewName!, startViewDateBaseComputed, getters.startViewDate,\n );\n }\n\n viewCellsDataComputed = memoize((\n viewName, cellDuration, startDayHour, endDayHour, viewCellsDataBaseComputed,\n ) => getters => computed(\n getters,\n viewName,\n viewCellsDataBaseComputed(cellDuration, startDayHour, endDayHour),\n getters.viewCellsData,\n ));\n\n timeTableAppointmentsComputed = memoize((\n viewName, cellDuration, calculateAppointmentsIntervals,\n ) => getters => computed(\n getters,\n viewName,\n calculateAppointmentsIntervals(cellDuration),\n getters.timeTableAppointments,\n ));\n\n updateCellElementsMeta = memoize((cellElementsMeta) => {\n this.setState({ timeTableElementsMeta: cellElementsMeta });\n });\n\n setScrollingStrategy = (scrollingStrategy: ScrollingStrategy) => {\n this.setState({ scrollingStrategy });\n }\n\n render() {\n const {\n name: viewName,\n intervalCount,\n displayName,\n type,\n excludedDays,\n cellDuration,\n startDayHour,\n endDayHour,\n viewCellsDataComputed,\n calculateAppointmentsIntervals,\n dayScaleCellComponent,\n dayScaleRowComponent,\n dayScaleLayoutComponent: DayScale,\n timeTableCellComponent: TimeTableCell,\n timeTableLayoutComponent: TimeTableLayout,\n timeTableRowComponent,\n appointmentLayerComponent: AppointmentLayer,\n dayScaleEmptyCellComponent: DayScaleEmptyCell,\n layoutProps,\n layoutComponent: Layout,\n } = this.props;\n const { timeTableElementsMeta, scrollingStrategy, timeTableLayoutKey } = this.state;\n const viewDisplayName = displayName || viewName;\n\n return (\n \n \n \n \n \n \n \n \n \n\n \n \n\n \n\n \n \n {({ currentView, groupOrientation, groups }) => {\n if (currentView.name !== viewName) return ;\n const isVerticalGrouping = groupOrientation?.(viewName)\n === VERTICAL_GROUP_ORIENTATION;\n return (\n \n );\n }}\n \n \n\n \n \n {({ currentView, viewCellsData, formatDate, groupByDate, groupOrientation }) => {\n if (currentView.name !== viewName) return ;\n const groupByDateEnabled = groupByDate?.(viewName);\n const isHorizontalGrouping = groupOrientation?.(viewName)\n === HORIZONTAL_GROUP_ORIENTATION;\n return (\n \n );\n }}\n \n \n\n \n {params => (\n \n {({ currentView }) => {\n if (currentView.name !== viewName) return ;\n return (\n \n );\n }}\n \n )}\n \n\n \n {(params: any) => (\n \n {({ formatDate, currentView, viewCellsData }) => {\n if (currentView.name !== viewName) return ;\n return (\n <>\n \n \n \n \n >\n );\n }}\n \n )}\n \n\n \n \n {({ currentView }) => {\n if (currentView.name !== viewName || !DayScaleEmptyCell) {\n return ;\n }\n return (\n \n );\n }}\n \n \n \n );\n }\n}\nexport const BasicView: React.ComponentType = BasicViewBase;\n","import * as React from 'react';\nimport {\n Template,\n Plugin,\n TemplateConnector,\n TemplatePlaceholder,\n Getter,\n} from '@devexpress/dx-react-core';\nimport {\n calculateWeekDateIntervals,\n getTimeTableHeight,\n timeCellsData as timeCellsDataCore,\n computed,\n} from '@devexpress/dx-scheduler-core';\nimport { BasicView } from './basic-view';\nimport { CommonVerticalViewProps } from '../types';\nimport { memoize } from '@devexpress/dx-core';\n\nconst calculateAppointmentsIntervalsBaseComputed = cellDuration => ({\n appointments, startViewDate, endViewDate, excludedDays,\n}) => calculateWeekDateIntervals(\n appointments, startViewDate, endViewDate, excludedDays, cellDuration,\n);\nconst timeCellsDataComputed = (startDayHour, endDayHour) => ({\n viewCellsData, cellDuration,\n}) => timeCellsDataCore(viewCellsData, startDayHour, endDayHour, cellDuration, Date.now());\n\nconst TimeScalePlaceholder = () => ;\n\nclass VericalViewBase extends React.PureComponent {\n timeCellsDataComputed = memoize((viewName, startDayHour, endDayHour) => getters => computed(\n getters,\n viewName,\n timeCellsDataComputed(startDayHour, endDayHour),\n getters.timeCellsData,\n ));\n\n render() {\n const {\n layoutComponent,\n dayScaleEmptyCellComponent,\n timeScaleLayoutComponent: TimeScale,\n timeScaleLabelComponent: TimeScaleLabel,\n timeScaleTickCellComponent,\n timeScaleTicksRowComponent,\n dayScaleLayoutComponent,\n dayScaleCellComponent,\n dayScaleRowComponent,\n timeTableLayoutComponent,\n timeTableRowComponent,\n timeTableCellComponent,\n cellDuration,\n excludedDays,\n name: viewName,\n appointmentLayerComponent,\n intervalCount,\n displayName,\n startDayHour,\n endDayHour,\n viewCellsDataComputed,\n type,\n } = this.props;\n\n return (\n \n \n\n \n\n \n {(params: any) => (\n \n {({\n currentView, timeCellsData, groups, formatDate,\n groupOrientation: getGroupOrientation,\n timeTableElementsMeta,\n }) => {\n if (currentView.name !== viewName) return ;\n const groupOrientation = getGroupOrientation?.(viewName);\n\n return (\n \n );\n }}\n \n )}\n \n \n );\n }\n}\n\nexport const VerticalView: React.ComponentType = VericalViewBase;\n","import * as React from 'react';\nimport {\n Plugin,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport {\n viewCellsData as viewCellsDataCore,\n VIEW_TYPES,\n} from '@devexpress/dx-scheduler-core';\nimport { VerticalViewProps } from '../types';\nimport { VerticalView } from './vertical-view';\n\nconst viewCellsDataBaseComputed = (\n cellDuration, startDayHour, endDayHour,\n) => ({ currentDate, intervalCount }) => {\n return viewCellsDataCore(\n currentDate, undefined,\n intervalCount, [],\n startDayHour!, endDayHour!, cellDuration!,\n Date.now(),\n );\n};\n\nclass DayViewBase extends React.PureComponent {\n static defaultProps: Partial = {\n name: 'Day',\n startDayHour: 0,\n endDayHour: 24,\n cellDuration: 30,\n intervalCount: 1,\n };\n\n static components: PluginComponents = {\n layoutComponent: 'Layout',\n layoutContainer: 'LayoutContainer',\n appointmentLayerComponent: 'AppointmentLayer',\n dayScaleEmptyCellComponent: 'DayScaleEmptyCell',\n timeScaleLayoutComponent: 'TimeScaleLayout',\n timeScaleLabelComponent: 'TimeScaleLabel',\n timeScaleTickCellComponent: 'TimeScaleTickCell',\n timeScaleTicksRowComponent: 'TimeScaleTicksRow',\n dayScaleLayoutComponent: 'DayScaleLayout',\n dayScaleCellComponent: 'DayScaleCell',\n dayScaleRowComponent: 'DayScaleRow',\n timeTableContainerComponent: 'TimeTableContainer',\n timeTableLayoutComponent: 'TimeTableLayout',\n timeTableCellComponent: 'TimeTableCell',\n timeTableRowComponent: 'TimeTableRow',\n };\n\n render() {\n const {\n layoutComponent,\n dayScaleEmptyCellComponent: DayScaleEmptyCell,\n timeScaleLayoutComponent,\n timeScaleLabelComponent,\n timeScaleTickCellComponent,\n timeScaleTicksRowComponent,\n dayScaleLayoutComponent,\n dayScaleCellComponent,\n dayScaleRowComponent,\n timeTableLayoutComponent,\n timeTableRowComponent,\n timeTableCellComponent,\n appointmentLayerComponent,\n cellDuration,\n name: viewName,\n intervalCount,\n displayName,\n startDayHour,\n endDayHour,\n } = this.props;\n\n return (\n \n \n \n );\n }\n}\n\n// tslint:disable-next-line: max-line-length\n/*** A plugin that renders Scheduler data for a day. This plugin arranges appointments from top to bottom.\n * If their time intervals overlap, their width is decreased and they are placed next to each other.\n * */\nexport const DayView: React.ComponentType = DayViewBase;\n","import * as React from 'react';\nimport {\n Plugin,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport {\n viewCellsData as viewCellsDataCore,\n VIEW_TYPES,\n} from '@devexpress/dx-scheduler-core';\nimport { WeekViewProps } from '../types';\nimport { VerticalView } from './vertical-view';\n\nconst DAYS_IN_WEEK = 7;\nconst viewCellsDataBaseComputed = (\n cellDuration, startDayHour, endDayHour,\n) => ({ firstDayOfWeek, intervalCount, excludedDays, currentDate }) => {\n return viewCellsDataCore(\n currentDate, firstDayOfWeek,\n intervalCount! * DAYS_IN_WEEK, excludedDays!,\n startDayHour!, endDayHour!, cellDuration!,\n Date.now(),\n );\n};\n\nclass WeekViewBase extends React.PureComponent {\n static defaultProps: Partial = {\n startDayHour: 0,\n endDayHour: 24,\n cellDuration: 30,\n intervalCount: 1,\n excludedDays: [],\n name: 'Week',\n };\n\n static components: PluginComponents = {\n layoutComponent: 'Layout',\n layoutContainerComponent: 'LayoutContainer',\n appointmentLayerComponent: 'AppointmentLayer',\n dayScaleEmptyCellComponent: 'DayScaleEmptyCell',\n timeScaleLayoutComponent: 'TimeScaleLayout',\n timeScaleLabelComponent: 'TimeScaleLabel',\n timeScaleTickCellComponent: 'TimeScaleTickCell',\n timeScaleTicksRowComponent: 'TimeScaleTicksRow',\n dayScaleLayoutComponent: 'DayScaleLayout',\n dayScaleCellComponent: 'DayScaleCell',\n dayScaleRowComponent: 'DayScaleRow',\n timeTableContainerComponent: 'TimeTableContainer',\n timeTableLayoutComponent: 'TimeTableLayout',\n timeTableCellComponent: 'TimeTableCell',\n timeTableRowComponent: 'TimeTableRow',\n };\n\n render() {\n const {\n layoutComponent,\n dayScaleEmptyCellComponent,\n timeScaleLayoutComponent,\n timeScaleLabelComponent,\n timeScaleTickCellComponent,\n timeScaleTicksRowComponent,\n dayScaleLayoutComponent,\n dayScaleCellComponent,\n dayScaleRowComponent,\n timeTableLayoutComponent,\n timeTableRowComponent,\n timeTableCellComponent,\n cellDuration,\n excludedDays,\n name: viewName,\n appointmentLayerComponent,\n intervalCount,\n displayName,\n startDayHour,\n endDayHour,\n } = this.props;\n\n return (\n \n \n \n );\n }\n}\n\n// tslint:disable: max-line-length\n/***\n * A plugin that renders the Scheduler's week view. This plugin arranges appointments from top to bottom.\n * If their time intervals overlap, their width is decreased and they are placed next to each other.\n * */\nexport const WeekView: React.ComponentType = WeekViewBase;\n","import * as React from 'react';\nimport { Plugin, PluginComponents } from '@devexpress/dx-react-core';\nimport { monthCellsData, calculateMonthDateIntervals, VIEW_TYPES } from '@devexpress/dx-scheduler-core';\nimport { BasicView } from './basic-view';\nimport { MonthViewProps } from '../types';\n\nconst viewCellsDataBaseComputed = (\n cellDuration, startDayHour, endDayHour,\n) => ({ currentDate, firstDayOfWeek, intervalCount }) => monthCellsData(\n currentDate, firstDayOfWeek, intervalCount!, Date.now(),\n);\nconst calculateAppointmentsIntervalsBaseComputed = cellDuration => ({\n appointments, startViewDate, endViewDate, excludedDays,\n}) => calculateMonthDateIntervals(\n appointments, startViewDate, endViewDate,\n);\n\nclass MonthViewBase extends React.PureComponent {\n static defaultProps: Partial = {\n intervalCount: 1,\n name: 'Month',\n };\n\n static components: PluginComponents = {\n layoutComponent: 'Layout',\n appointmentLayerComponent: 'AppointmentLayer',\n dayScaleEmptyCellComponent: 'DayScaleEmptyCell',\n dayScaleLayoutComponent: 'DayScaleLayout',\n dayScaleCellComponent: 'DayScaleCell',\n dayScaleRowComponent: 'DayScaleRow',\n timeTableContainerComponent: 'TimeTableContainer',\n timeTableLayoutComponent: 'TimeTableLayout',\n timeTableCellComponent: 'TimeTableCell',\n timeTableRowComponent: 'TimeTableRow',\n };\n\n render() {\n const {\n layoutComponent,\n dayScaleEmptyCellComponent,\n dayScaleLayoutComponent,\n dayScaleCellComponent,\n dayScaleRowComponent,\n timeTableLayoutComponent,\n timeTableRowComponent,\n timeTableCellComponent,\n appointmentLayerComponent,\n name: viewName,\n intervalCount,\n displayName,\n } = this.props;\n\n return (\n \n \n \n );\n }\n}\n\n// tslint:disable: max-line-length\n/***\n * A plugin that renders Scheduler data for a month. This plugin arranges appointments from left to right.\n * An appointment's size depends on its duration in days.\n * However, it occupies the entire day cell if an appointment lasts only for several hours or minutes.\n * The time scale and all-day panel are not available in this view.\n * */\nexport const MonthView: React.ComponentType = MonthViewBase;\n","import * as React from 'react';\nimport {\n Template,\n Plugin,\n TemplatePlaceholder,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport { ToolbarProps } from '../types';\n\nclass ToolbarBase extends React.PureComponent {\n static components: PluginComponents = {\n rootComponent: 'Root',\n flexibleSpaceComponent: 'FlexibleSpace',\n };\n render() {\n const {\n rootComponent: Root,\n flexibleSpaceComponent: FlexibleSpaceComponent,\n } = this.props;\n return (\n \n \n \n \n \n \n \n \n \n \n \n );\n }\n}\n\n/** A plugin that renders the Scheduler's toolbar. */\nexport const Toolbar: React.ComponentType = ToolbarBase;\n","import * as React from 'react';\nimport {\n Plugin,\n Template,\n TemplatePlaceholder,\n TemplateConnector,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport {\n monthCellsData,\n viewBoundText,\n} from '@devexpress/dx-scheduler-core';\nimport { memoize } from '@devexpress/dx-core';\n\nimport { DateNavigatorProps, DateNavigatorState } from '../types';\n\nconst pluginDependencies = [\n { name: 'Toolbar' },\n { name: 'ViewState' },\n];\n\nconst navigate = (action, currentView, intervalCount) => (direction, nextDate) => action({\n direction,\n nextDate,\n amount: intervalCount,\n step: currentView.type,\n});\n\nclass DateNavigatorBase extends React.PureComponent {\n target!: React.ReactInstance;\n\n state = {\n visible: false,\n };\n static components: PluginComponents = {\n rootComponent: 'Root',\n overlayComponent: 'Overlay',\n openButtonComponent: 'OpenButton',\n navigationButtonComponent: 'NavigationButton',\n calendarComponent: 'Calendar',\n calendarRowComponent: 'CalendarRow',\n calendarCellComponent: 'CalendarCell',\n calendarHeaderRowComponent: 'CalendarHeaderRow',\n calendarHeaderCellComponent: 'CalendarHeaderCell',\n calendarTextComponent: 'CalendarText',\n calendarNavigatorComponent: 'CalendarNavigator',\n calendarNavigationButtonComponent: 'CalendarNavigationButton',\n };\n\n setRootRef = (target: React.ReactInstance) => {\n this.target = target;\n }\n\n handleVisibilityToggle = () => {\n this.setState(prevState => ({ visible: !prevState.visible }));\n }\n\n handleHide = () => {\n this.setState({ visible: false });\n }\n\n navigateAction = memoize((changeCurrentDate, currentView, intervalCount, navigateAction) =>\n navigateAction(changeCurrentDate, currentView, intervalCount));\n\n render() {\n const {\n rootComponent: Root,\n overlayComponent: Overlay,\n openButtonComponent: OpenButton,\n navigationButtonComponent: NavigationButton,\n calendarComponent: Calendar,\n calendarRowComponent: CalendarRow,\n calendarCellComponent: CalendarCell,\n calendarHeaderRowComponent: CalendarHeaderRow,\n calendarHeaderCellComponent: CalendarHeaderCell,\n calendarTextComponent: CalendarText,\n calendarNavigationButtonComponent: CalendarNavigationButton,\n calendarNavigatorComponent: CalendarNavigator,\n } = this.props;\n\n const { visible } = this.state;\n return (\n \n \n \n {({\n currentDate,\n startViewDate,\n endViewDate,\n firstDayOfWeek,\n currentView,\n intervalCount,\n formatDate,\n }, {\n changeCurrentDate,\n }) => {\n const navigateAction = this.navigateAction(\n changeCurrentDate, currentView, intervalCount, navigate,\n );\n const calendarDateChanged = (nextDate) => {\n navigateAction(undefined, nextDate);\n this.handleHide();\n };\n const navigatorText = viewBoundText(\n startViewDate,\n endViewDate,\n currentView.type,\n currentDate,\n intervalCount,\n formatDate,\n );\n return (\n \n \n \n \n \n \n );\n }}\n \n \n \n \n );\n }\n}\n\n/** A plugin that renders the Scheduler’s date navigator. */\nexport const DateNavigator: React.ComponentType = DateNavigatorBase;\n","import * as React from 'react';\nimport {\n Plugin,\n Template,\n TemplatePlaceholder,\n TemplateConnector,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport { ViewSwitcherProps } from '../types/view-switcher';\n\nconst pluginDependencies = [\n { name: 'Toolbar' },\n { name: 'ViewState' },\n];\n\nclass ViewSwitcherBase extends React.PureComponent {\n static components: PluginComponents = {\n switcherComponent: 'Switcher',\n };\n\n render() {\n const { switcherComponent: Switcher } = this.props;\n\n return (\n \n \n \n \n {({\n currentView,\n availableViews,\n }, {\n setCurrentViewName,\n }) => (\n \n )}\n \n \n \n );\n }\n}\n\n/** A plugin that renders the Scheduler's view switcher. */\nexport const ViewSwitcher: React.ComponentType = ViewSwitcherBase;\n","import * as React from 'react';\nimport {\n Plugin, Template, TemplatePlaceholder, TemplateConnector, PluginComponents,\n} from '@devexpress/dx-react-core';\nimport { createClickHandlers, memoize } from '@devexpress/dx-core';\nimport {\n POSITION_START, POSITION_END, VERTICAL_TYPE,\n getVerticalRectByAppointmentData, calculateRectByDateAndGroupIntervals,\n getAppointmentStyle, HORIZONTAL_TYPE, getHorizontalRectByAppointmentData,\n isAllDayElementsMetaActual, isTimeTableElementsMetaActual,\n HORIZONTAL_GROUP_ORIENTATION, VIEW_TYPES, getGroupsLastRow, Rect,\n} from '@devexpress/dx-scheduler-core';\n\nimport { AppointmentsProps } from '../types';\n\nconst AppointmentPlaceholder = params => ;\n\nconst renderAppointments = rects => rects.map(({\n dataItem, type: rectType, fromPrev, toNext,\n durationType, resources, key, ...geometry\n}) => (\n \n));\n\nconst pluginDependencies = [\n { name: 'DayView', optional: true },\n { name: 'WeekView', optional: true },\n { name: 'MonthView', optional: true },\n];\n\nclass AppointmentsBase extends React.PureComponent {\n static components: PluginComponents = {\n splitIndicatorComponent: 'SplitIndicator',\n containerComponent: 'Container',\n appointmentComponent: 'Appointment',\n appointmentContentComponent: 'AppointmentContent',\n recurringIconComponent: 'RecurringIcon',\n };\n static defaultProps: Partial = {\n placeAppointmentsNextToEachOther: false,\n };\n\n updateTimeTableAppointments = memoize((\n timeTableAppointments, viewCellsData, timeTableElementsMeta, currentView,\n startViewDate, endViewDate, cellDuration, groups, getGroupOrientation, groupByDate,\n placeAppointmentsNextToEachOther,\n ) => {\n if (!isTimeTableElementsMetaActual(viewCellsData, timeTableElementsMeta)) return null;\n\n const groupOrientation = getGroupOrientation\n ? getGroupOrientation(currentView?.name)\n : HORIZONTAL_GROUP_ORIENTATION;\n const groupCount = groups ? getGroupsLastRow(groups).length : 1;\n\n let appointmentType = { growDirection: VERTICAL_TYPE, multiline: false };\n let getRects = getVerticalRectByAppointmentData as any;\n if (currentView.type === VIEW_TYPES.MONTH) {\n appointmentType = { growDirection: HORIZONTAL_TYPE, multiline: true };\n getRects = getHorizontalRectByAppointmentData;\n }\n\n return renderAppointments(calculateRectByDateAndGroupIntervals(\n appointmentType, timeTableAppointments, getRects,\n {\n startViewDate, endViewDate, cellDuration,\n viewCellsData, cellElementsMeta: timeTableElementsMeta,\n placeAppointmentsNextToEachOther,\n },\n {\n groupOrientation,\n groupedByDate: groupByDate?.(currentView?.name),\n groupCount,\n },\n ));\n });\n\n updateAllDayAppointments = memoize((\n allDayAppointments, viewCellsData, allDayElementsMeta, currentView,\n startViewDate, endViewDate, groups, getGroupOrientation, groupByDate,\n ) => {\n const groupOrientation = getGroupOrientation\n ? getGroupOrientation(currentView?.name)\n : HORIZONTAL_GROUP_ORIENTATION;\n const groupCount = groups ? getGroupsLastRow(groups).length : 1;\n\n if (!isAllDayElementsMetaActual(\n viewCellsData, allDayElementsMeta, groupOrientation, groupCount,\n )) {\n return null;\n }\n\n return renderAppointments(calculateRectByDateAndGroupIntervals(\n { growDirection: HORIZONTAL_TYPE, multiline: false },\n allDayAppointments,\n getHorizontalRectByAppointmentData,\n {\n startViewDate, endViewDate,\n viewCellsData, cellElementsMeta: allDayElementsMeta,\n },\n {\n groupOrientation,\n groupedByDate: groupByDate?.(currentView?.name),\n groupCount,\n },\n ));\n });\n\n render() {\n const {\n splitIndicatorComponent: SplitIndicator,\n appointmentComponent: Appointment,\n appointmentContentComponent: AppointmentContent,\n containerComponent: Container,\n recurringIconComponent,\n placeAppointmentsNextToEachOther,\n } = this.props;\n\n return (\n \n \n \n {({\n timeTableAppointments, viewCellsData, timeTableElementsMeta, currentView,\n startViewDate, endViewDate, cellDuration, groupOrientation, groups, groupByDate,\n }) => this.updateTimeTableAppointments(\n timeTableAppointments, viewCellsData, timeTableElementsMeta, currentView,\n startViewDate, endViewDate, cellDuration, groups, groupOrientation, groupByDate,\n placeAppointmentsNextToEachOther,\n )}\n \n \n \n \n {({\n allDayAppointments, viewCellsData, allDayElementsMeta,\n startViewDate, endViewDate, groupOrientation, currentView, groups, groupByDate,\n }) => this.updateAllDayAppointments(\n allDayAppointments, viewCellsData, allDayElementsMeta, currentView,\n startViewDate, endViewDate, groups, groupOrientation, groupByDate,\n )}\n \n \n \n {({ style, ...params }: any) => (\n \n {({ formatDate }) => (\n \n \n \n \n \n )}\n \n )}\n \n\n \n {({\n onClick, onDoubleClick, formatDate,\n data, type, fromPrev, toNext,\n durationType, resources,\n ...restParams\n }: any) => (\n \n {fromPrev && }\n \n {toNext && }\n \n )}\n \n \n );\n }\n}\n\n/** A plugin that renders appointments. */\nexport const Appointments: React.ComponentType = AppointmentsBase;\n","import * as React from 'react';\nimport { getMessagesFormatter, memoize } from '@devexpress/dx-core';\nimport {\n Getter,\n Plugin,\n Template,\n TemplatePlaceholder,\n TemplateConnector,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport {\n allDayCells, calculateAllDayDateIntervals,\n VERTICAL_GROUP_ORIENTATION, VIEW_TYPES,\n} from '@devexpress/dx-scheduler-core';\nimport moment from 'moment';\n\nimport { AllDayPanelProps, AllDayPanelState } from '../types';\n\nconst isMonthView = currentView => currentView.type === VIEW_TYPES.MONTH;\nconst isVerticalGrouping = (\n currentView, groupOrientation,\n) => groupOrientation?.(currentView.name) === VERTICAL_GROUP_ORIENTATION;\n\nconst pluginDependencies = [\n { name: 'DayView', optional: true },\n { name: 'WeekView', optional: true },\n];\nconst defaultMessages = {\n allDay: 'All Day',\n};\nconst AllDayAppointmentLayerPlaceholder = () =>\n ;\nconst AllDayPanelPlaceholder = params => ;\nconst CellPlaceholder = params => ;\nconst AllDayTitlePlaceholder = params => ;\n\nclass AllDayPanelBase extends React.PureComponent {\n state: AllDayPanelState = {\n elementsMeta: {},\n previousCell: null,\n // The key has to be generated every time the Cell component is updated to rerender the Layout\n // and, consequently, update allDayElementsMeta\n layoutKey: 0,\n };\n static defaultProps: Partial = {\n messages: {},\n };\n static components: PluginComponents = {\n appointmentLayerComponent: 'AppointmentLayer',\n layoutComponent: 'Layout',\n layoutContainerComponent: 'LayoutContainer',\n cellComponent: 'Cell',\n rowComponent: 'Row',\n titleCellComponent: 'TitleCell',\n containerComponent: 'Container',\n };\n\n static getDerivedStateFromProps(\n props: AllDayPanelProps, state: AllDayPanelState,\n ): AllDayPanelState | null {\n if (props.cellComponent !== state.previousCell) {\n return {\n ...state,\n previousCell: props.cellComponent,\n layoutKey: Math.random(),\n };\n }\n return null;\n }\n\n allDayCellsDataComputed = memoize(({ viewCellsData }) => allDayCells(viewCellsData));\n\n updateCellElementsMeta = memoize((cellElementsMeta) => {\n this.setState({ elementsMeta: cellElementsMeta });\n });\n\n allDayAppointmentsComputed = memoize(({\n appointments, startViewDate, endViewDate, excludedDays,\n }) => {\n const allDayLeftBound = moment(startViewDate).hours(0).minutes(0).toDate();\n const allDayRightBound = moment(endViewDate).hours(23).minutes(59).toDate();\n return calculateAllDayDateIntervals(\n appointments, allDayLeftBound, allDayRightBound, excludedDays,\n );\n });\n\n allDayPanelExistsComputed = memoize(({\n currentView,\n }) => !isMonthView(currentView));\n\n getMessageFormatter = memoize((messages, allDayPanelDefaultMessages) =>\n getMessagesFormatter({ ...allDayPanelDefaultMessages, ...messages }));\n\n render() {\n const {\n appointmentLayerComponent: AppointmentLayer,\n layoutComponent: Layout,\n cellComponent: Cell,\n rowComponent,\n titleCellComponent: TitleCell,\n containerComponent: Container,\n messages,\n } = this.props;\n const { elementsMeta, layoutKey } = this.state;\n const getMessage = this.getMessageFormatter(messages, defaultMessages);\n\n return (\n \n \n \n \n \n\n \n {(params: any) => (\n \n {({ currentView, groupOrientation, allDayCellsData }) => {\n if (isMonthView(currentView)\n || !isVerticalGrouping(currentView, groupOrientation)) {\n return ;\n }\n return (\n <>\n \n \n \n \n >\n );\n }}\n \n )}\n \n\n \n \n {({ currentView, groupOrientation }) => {\n if (isMonthView(currentView) || isVerticalGrouping(currentView, groupOrientation)) {\n return ;\n }\n\n return (\n \n );\n }}\n \n \n\n \n {(params: any) => (\n \n {({ currentView, groupOrientation }) => {\n if (isMonthView(currentView)\n || !isVerticalGrouping(currentView, groupOrientation)) {\n return ;\n }\n\n return (\n \n );\n }}\n \n )}\n \n\n \n \n \n {({ currentView, groupOrientation }) => {\n if (isMonthView(currentView) || isVerticalGrouping(currentView, groupOrientation)) {\n return null;\n }\n\n return (\n \n \n \n );\n }}\n \n \n\n \n \n \n {({\n currentView, formatDate, allDayCellsData,\n }) => {\n if (currentView.type === VIEW_TYPES.MONTH) return null;\n\n return (\n \n \n \n \n \n \n );\n }}\n \n \n\n \n {(params: any) => }\n \n \n {(params: any) => | }\n \n \n );\n }\n}\n\n/** A plugin that renders the All Day Panel. */\nexport const AllDayPanel: React.ComponentType = AllDayPanelBase;\n","import * as React from 'react';\nimport {\n Getter,\n Action,\n Plugin,\n createStateHelper,\n StateHelper,\n ActionFn,\n} from '@devexpress/dx-react-core';\nimport {\n changeCurrentDate,\n setCurrentViewName,\n ChangeCurrentDatePayload,\n} from '@devexpress/dx-scheduler-core';\nimport { ViewStateProps, ViewStateState } from '../types';\nimport { memoize } from '@devexpress/dx-core';\n\nclass ViewStateBase extends React.PureComponent {\n changeCurrentDate: ActionFn;\n setCurrentViewName: ActionFn;\n\n static defaultProps: Partial = {\n defaultCurrentDate: new Date(),\n };\n\n constructor(props) {\n super(props);\n\n this.state = {\n currentDate: props.currentDate || props.defaultCurrentDate,\n currentViewName: props.currentViewName || props.defaultCurrentViewName,\n };\n\n const stateHelper: StateHelper = createStateHelper(\n this,\n {\n currentDate: () => {\n const { onCurrentDateChange } = this.props;\n return onCurrentDateChange;\n },\n currentViewName: () => {\n const { onCurrentViewNameChange } = this.props;\n return onCurrentViewNameChange;\n },\n },\n );\n\n this.changeCurrentDate = stateHelper.applyFieldReducer\n .bind(stateHelper, 'currentDate', changeCurrentDate);\n this.setCurrentViewName = stateHelper.applyFieldReducer\n .bind(stateHelper, 'currentViewName', setCurrentViewName);\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n const {\n currentDate = prevState.currentDate,\n currentViewName = prevState.currentViewName,\n } = nextProps;\n\n return {\n currentDate,\n currentViewName,\n };\n }\n\n getCurrentViewComputed = memoize(currentViewName => () => (\n currentViewName\n ? { name: currentViewName }\n : undefined\n ));\n\n render() {\n const { currentDate, currentViewName: stateCurrentViewName } = this.state;\n return (\n \n \n \n \n \n \n );\n }\n}\n\n/** A plugin that manages the view state. It specifies the current date and the displayed view. */\nexport const ViewState: React.ComponentType = ViewStateBase;\n","import * as React from 'react';\nimport {\n Action, Plugin, Getter, createStateHelper, StateHelper, ComputedFn, ActionFn,\n} from '@devexpress/dx-react-core';\nimport {\n addAppointment,\n cancelAddedAppointment,\n startEditAppointment,\n stopEditAppointment,\n changeAppointment,\n cancelChanges,\n changedAppointmentById,\n RECURRENCE_EDIT_SCOPE,\n preCommitChanges as preCommitChangesBase,\n} from '@devexpress/dx-scheduler-core';\nimport { EditingStateProps, EditingStateState } from '../types';\n\nclass EditingStateBase extends React.PureComponent {\n startEditAppointment: ComputedFn;\n stopEditAppointment: (payload?: any) => void;\n changeAppointment: ComputedFn;\n cancelChangedAppointment: (payload?: any) => void;\n commitChangedAppointment: ActionFn;\n addAppointment: ComputedFn;\n changeAddedAppointment: ComputedFn;\n cancelAddedAppointment: (payload?: any) => void;\n commitAddedAppointment: ComputedFn;\n commitDeletedAppointment: ActionFn;\n\n static defaultProps: Partial = {\n defaultEditingAppointment: undefined,\n defaultAppointmentChanges: {},\n defaultAddedAppointment: {},\n preCommitChanges: preCommitChangesBase,\n };\n\n constructor(props) {\n super(props);\n\n this.state = {\n editingAppointment: props.editingAppointment || props.defaultEditingAppointment,\n addedAppointment: props.addedAppointment || props.defaultAddedAppointment,\n appointmentChanges: props.appointmentChanges || props.defaultAppointmentChanges,\n };\n\n const stateHelper: StateHelper = createStateHelper(\n this,\n {\n editingAppointment: () => {\n const { onEditingAppointmentChange } = this.props;\n return onEditingAppointmentChange;\n },\n addedAppointment: () => {\n const { onAddedAppointmentChange } = this.props;\n return onAddedAppointmentChange;\n },\n appointmentChanges: () => {\n const { onAppointmentChangesChange } = this.props;\n return onAppointmentChangesChange;\n },\n },\n );\n\n this.startEditAppointment = stateHelper.applyFieldReducer\n .bind(stateHelper, 'editingAppointment', startEditAppointment);\n this.stopEditAppointment = stateHelper.applyFieldReducer\n .bind(stateHelper, 'editingAppointment', stopEditAppointment);\n\n this.changeAppointment = stateHelper.applyFieldReducer\n .bind(stateHelper, 'appointmentChanges', changeAppointment);\n this.cancelChangedAppointment = stateHelper.applyFieldReducer\n .bind(stateHelper, 'appointmentChanges', cancelChanges);\n\n this.commitChangedAppointment = (type = RECURRENCE_EDIT_SCOPE.CURRENT) => {\n const { appointmentChanges, editingAppointment } = this.state;\n const { onCommitChanges, preCommitChanges } = this.props;\n\n if (!editingAppointment) return;\n const changes = !editingAppointment.rRule\n ? { changed: changedAppointmentById(appointmentChanges, editingAppointment.id!) }\n : preCommitChanges!(appointmentChanges, editingAppointment, type);\n\n onCommitChanges(changes);\n this.cancelChangedAppointment();\n this.stopEditAppointment();\n };\n\n this.addAppointment = stateHelper.applyFieldReducer\n .bind(stateHelper, 'addedAppointment', addAppointment);\n this.changeAddedAppointment = stateHelper.applyFieldReducer\n .bind(stateHelper, 'addedAppointment', changeAppointment);\n this.cancelAddedAppointment = stateHelper.applyFieldReducer\n .bind(stateHelper, 'addedAppointment', cancelAddedAppointment);\n this.commitAddedAppointment = () => {\n const { onCommitChanges } = this.props;\n const { addedAppointment: stateAddedAppointment } = this.state;\n onCommitChanges({\n added: stateAddedAppointment,\n });\n };\n\n this.commitDeletedAppointment = ({ deletedAppointmentData, type = 'current' }) => {\n const { onCommitChanges, preCommitChanges } = this.props;\n\n const changes = deletedAppointmentData.rRule\n ? preCommitChanges!(null, deletedAppointmentData, type)\n : { deleted: deletedAppointmentData.id };\n onCommitChanges(changes);\n };\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n const {\n editingAppointment = prevState.editingAppointment,\n appointmentChanges = prevState.appointmentChanges,\n addedAppointment = prevState.addedAppointment,\n } = nextProps;\n\n return {\n editingAppointment,\n appointmentChanges,\n addedAppointment,\n };\n }\n\n render() {\n const { addedAppointment, editingAppointment, appointmentChanges } = this.state;\n\n return (\n \n \n \n \n\n \n \n \n \n\n \n \n \n \n \n\n \n \n );\n }\n}\n\n/** A plugin that manages the scheduler appointment editing state. */\nexport const EditingState: React.ComponentType = EditingStateBase;\n","import * as React from 'react';\nimport {\n Plugin,\n Template,\n TemplatePlaceholder,\n TemplateConnector,\n createStateHelper,\n StateHelper,\n PluginComponents,\n Action,\n} from '@devexpress/dx-react-core';\nimport {\n OPEN_COMMAND_BUTTON,\n CLOSE_COMMAND_BUTTON,\n DELETE_COMMAND_BUTTON,\n setAppointmentMeta,\n AppointmentMeta,\n TOGGLE_APPOINTMENT_TOOLTIP_VISIBILITY,\n getAppointmentResources,\n} from '@devexpress/dx-scheduler-core';\n\nimport { AppointmentTooltipProps, AppointmentTooltipState, Appointments } from '../types';\n\nconst pluginDependencies = [\n { name: 'Appointments' },\n { name: 'EditingState', optional: true },\n { name: 'EditRecurrenceMenu', optional: true },\n { name: 'IntegratedEditing', optional: true },\n];\n\nconst commandButtonIds = {\n open: OPEN_COMMAND_BUTTON,\n close: CLOSE_COMMAND_BUTTON,\n delete: DELETE_COMMAND_BUTTON,\n};\n\nclass AppointmentTooltipBase extends React.PureComponent<\n AppointmentTooltipProps, AppointmentTooltipState\n> {\n toggleVisibility: (payload?: any) => void;\n setAppointmentMeta: (appointmentMeta: AppointmentMeta) => void;\n onAppointmentClick: (appointmentMeta: AppointmentMeta) => void;\n\n static defaultProps: Partial = {\n showOpenButton: false,\n showDeleteButton: false,\n showCloseButton: false,\n };\n static components: PluginComponents = {\n layoutComponent: 'Layout',\n headerComponent: 'Header',\n contentComponent: 'Content',\n commandButtonComponent: 'CommandButton',\n recurringIconComponent: 'RecurringIcon',\n };\n\n constructor(props) {\n super(props);\n\n this.state = {\n visible: props.visible,\n appointmentMeta: props.appointmentMeta,\n };\n\n const stateHelper: StateHelper = createStateHelper(\n this,\n {\n visible: () => {\n const { onVisibilityChange } = this.props;\n return onVisibilityChange;\n },\n appointmentMeta: () => {\n const { onAppointmentMetaChange } = this.props;\n return onAppointmentMetaChange;\n },\n },\n );\n\n const toggleVisibility = () => {\n const { visible: isOpen } = this.state;\n return !isOpen;\n };\n this.toggleVisibility = stateHelper.applyFieldReducer\n .bind(stateHelper, 'visible', toggleVisibility);\n this.setAppointmentMeta = stateHelper.applyFieldReducer\n .bind(stateHelper, 'appointmentMeta', setAppointmentMeta);\n this.onAppointmentClick = ({ target, data }) => {\n this.setAppointmentMeta({ target, data });\n this.toggleVisibility();\n };\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n const {\n visible = prevState.visible,\n appointmentMeta = prevState.appointmentMeta,\n } = nextProps;\n return {\n appointmentMeta,\n visible,\n };\n }\n\n render() {\n const {\n showOpenButton,\n showDeleteButton,\n showCloseButton,\n layoutComponent: Layout,\n headerComponent,\n contentComponent,\n commandButtonComponent,\n recurringIconComponent,\n } = this.props;\n const { visible, appointmentMeta } = this.state;\n\n return (\n \n \n\n \n \n \n {({\n formatDate, resources, plainResources,\n }, {\n finishDeleteAppointment, openDeleteConfirmationDialog,\n }) => {\n const onDeleteButtonClick = () => {\n if (openDeleteConfirmationDialog) {\n openDeleteConfirmationDialog({\n hideActionName: TOGGLE_APPOINTMENT_TOOLTIP_VISIBILITY,\n appointmentData: appointmentMeta.data,\n });\n } else {\n this.toggleVisibility();\n finishDeleteAppointment(appointmentMeta.data);\n }\n };\n return (\n \n );\n }}\n \n \n\n \n {(params: any) => }\n \n\n \n {(params: Appointments.AppointmentProps) => (\n \n this.onAppointmentClick({ target, data }),\n }}\n />\n )}\n \n \n );\n }\n}\n\n// tslint:disable: max-line-length\n/** The AppointmentTooltip plugin allows you to display information about an appointment in a tooltip. */\nexport const AppointmentTooltip: React.ComponentType = AppointmentTooltipBase;\n","import * as React from 'react';\nimport { getMessagesFormatter, memoize } from '@devexpress/dx-core';\nimport {\n Plugin,\n Template,\n createStateHelper,\n StateHelper,\n TemplateConnector,\n TemplatePlaceholder,\n PluginComponents,\n Action,\n} from '@devexpress/dx-react-core';\nimport {\n setAppointmentData,\n isAllDayCell,\n callActionIfExists,\n AppointmentModel,\n TOGGLE_APPOINTMENT_FORM_VISIBILITY,\n getAppointmentResources,\n ValidResourceInstance,\n checkMultipleResourceFields,\n} from '@devexpress/dx-scheduler-core';\n\nimport {\n AppointmentFormProps, AppointmentFormState, AppointmentTooltip, Appointments,\n} from '../types';\n\nconst addDoubleClickToCell = (\n title, startDate, endDate, groupingInfo, resources,\n allDay, openFormHandler, addAppointment, params,\n) => {\n const resourceFields = !!groupingInfo\n ? groupingInfo.reduce((acc, currentGroup) => (\n { ...acc, [currentGroup.fieldName]: currentGroup.id }\n ), {}) : {};\n const validResourceFields = resources\n ? checkMultipleResourceFields(resourceFields, resources)\n : resourceFields;\n\n const newAppointmentData = {\n title,\n startDate,\n endDate,\n allDay,\n ...validResourceFields,\n };\n\n return (\n {\n openFormHandler(newAppointmentData);\n callActionIfExists(addAppointment,\n { appointmentData: newAppointmentData });\n },\n }}\n />\n );\n};\n\nconst defaultMessages = {\n allDayLabel: 'All Day',\n titleLabel: 'Title',\n commitCommand: 'Save',\n detailsLabel: 'Details',\n moreInformationLabel: 'More Information',\n repeatLabel: 'Repeat',\n notesLabel: 'Notes',\n never: 'Never',\n daily: 'Daily',\n weekly: 'Weekly',\n monthly: 'Monthly',\n yearly: 'Yearly',\n repeatEveryLabel: 'Repeat every',\n daysLabel: 'day(s)',\n endRepeatLabel: 'End repeat',\n onLabel: 'On',\n afterLabel: 'After',\n occurrencesLabel: 'occurrence(s)',\n weeksOnLabel: 'week(s) on:',\n monthsLabel: 'month(s)',\n ofEveryMonthLabel: 'of every month',\n theLabel: 'The',\n firstLabel: 'First',\n secondLabel: 'Second',\n thirdLabel: 'Third',\n fourthLabel: 'Fourth',\n lastLabel: 'Last',\n yearsLabel: 'year(s)',\n ofLabel: 'of ',\n everyLabel: 'Every',\n};\n\nconst CommandLayoutPlaceholder = () => ;\nconst BasicLayoutPlaceholder = () => ;\nconst RecurrenceLayoutPlaceholder = () => ;\n\nconst pluginDependencies = [\n { name: 'EditingState', optional: true },\n { name: 'Appointments', optional: true },\n { name: 'AppointmentTooltip', optional: true },\n { name: 'EditRecurrenceMenu', optional: true },\n { name: 'IntegratedEditing', optional: true },\n];\n\nconst prepareChanges = (\n appointmentData, editingAppointment,\n addedAppointment, appointmentChanges,\n resources, plainResources,\n) => {\n const isNew = !editingAppointment;\n const changedAppointment = {\n ...appointmentData,\n ...appointmentChanges,\n ...isNew && addedAppointment,\n };\n const appointmentResources = getAppointmentResources(\n changedAppointment, resources, plainResources,\n );\n const isFormEdited = isNew || Object.getOwnPropertyNames(appointmentChanges).length !== 0;\n return { changedAppointment, appointmentResources, isNew, isFormEdited };\n};\n\nconst isFormFullSize = (\n isFormVisible, changedAppointmentRRule, previousAppointmentRRule,\n) => !!changedAppointmentRRule || (!isFormVisible && !!previousAppointmentRRule);\n\nclass AppointmentFormBase extends React.PureComponent {\n toggleVisibility: (payload?: any) => void;\n setAppointmentData: (payload: any) => void;\n openFormHandler: (payload: AppointmentModel) => void;\n container = React.createRef();\n\n static defaultProps: Partial = {\n messages: {},\n readOnly: false,\n onVisibilityChange: () => undefined,\n onAppointmentDataChange: () => undefined,\n };\n static components: PluginComponents = {\n overlayComponent: 'Overlay',\n layoutComponent: 'Layout',\n commandLayoutComponent: 'CommandLayout',\n commandButtonComponent: 'CommandButton',\n basicLayoutComponent: 'BasicLayout',\n textEditorComponent: 'TextEditor',\n labelComponent: 'Label',\n dateEditorComponent: 'DateEditor',\n booleanEditorComponent: 'BooleanEditor',\n selectComponent: 'Select',\n recurrenceLayoutComponent: 'RecurrenceLayout',\n radioGroupComponent: 'RadioGroup',\n weeklyRecurrenceSelectorComponent: 'WeeklyRecurrenceSelector',\n resourceEditorComponent: 'ResourceEditor',\n containerComponent: 'Container',\n };\n\n constructor(props) {\n super(props);\n\n this.state = {\n visible: props.visible,\n appointmentData: props.appointmentData || {},\n previousAppointment: props.appointmentData || {},\n };\n\n const stateHelper: StateHelper = createStateHelper(\n this,\n {\n visible: () => {\n const { onVisibilityChange } = this.props;\n return onVisibilityChange;\n },\n appointmentData: () => {\n const { onAppointmentDataChange } = this.props;\n return onAppointmentDataChange;\n },\n },\n );\n\n const toggleVisibility = () => {\n const { visible: isOpen } = this.state;\n return !isOpen;\n };\n this.toggleVisibility = stateHelper.applyFieldReducer\n .bind(stateHelper, 'visible', toggleVisibility);\n this.setAppointmentData = stateHelper.applyFieldReducer\n .bind(stateHelper, 'appointmentData', setAppointmentData);\n\n this.openFormHandler = (appointmentData) => {\n this.setAppointmentData({ appointmentData });\n this.toggleVisibility();\n };\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n const {\n visible = prevState.visible,\n appointmentData = prevState.appointmentData,\n } = nextProps;\n return {\n appointmentData,\n visible,\n };\n }\n\n commitChanges = memoize((\n finishCommitAppointment, commitAddedAppointment, isNew, changedAppointment,\n ) => () => {\n this.toggleVisibility();\n if (isNew) {\n callActionIfExists(commitAddedAppointment, changedAppointment);\n } else if (finishCommitAppointment) {\n finishCommitAppointment();\n }\n this.setState({ previousAppointment: changedAppointment });\n });\n\n cancelChanges = memoize((\n openCancelConfirmationDialog, isNew, stopEditAppointment, appointmentChanges,\n changedAppointment, cancelAddedAppointment, cancelChangedAppointment,\n ) => () => {\n if (openCancelConfirmationDialog && Object.keys(appointmentChanges).length !== 0) {\n openCancelConfirmationDialog(TOGGLE_APPOINTMENT_FORM_VISIBILITY);\n } else {\n if (isNew) {\n callActionIfExists(cancelAddedAppointment, appointmentChanges);\n } else {\n callActionIfExists(stopEditAppointment, appointmentChanges);\n callActionIfExists(cancelChangedAppointment, appointmentChanges);\n }\n this.toggleVisibility();\n }\n this.setState({ previousAppointment: changedAppointment });\n });\n\n deleteAppointment = memoize((\n finishDeleteAppointment, appointmentData, openDeleteConfirmationDialog,\n changedAppointment, cancelAddedAppointment, cancelChangedAppointment,\n stopEditAppointment, isNew,\n ) => () => {\n if (openDeleteConfirmationDialog) {\n openDeleteConfirmationDialog({\n hideActionName: TOGGLE_APPOINTMENT_FORM_VISIBILITY, appointmentData: changedAppointment,\n });\n } else {\n callActionIfExists(finishDeleteAppointment, appointmentData);\n if (isNew) {\n callActionIfExists(cancelAddedAppointment, appointmentData);\n } else {\n callActionIfExists(cancelChangedAppointment, appointmentData);\n callActionIfExists(stopEditAppointment, appointmentData);\n }\n this.toggleVisibility();\n }\n this.setState({ previousAppointment: changedAppointment });\n });\n\n changeAppointmentField = memoize((isNew, changeAddedAppointment, changeAppointment) =>\n (change) => {\n if (change && change.rRule) {\n this.setState({ previousAppointment: {\n ...this.state.previousAppointment, rRule: change.rRule,\n }});\n }\n if (isNew) {\n callActionIfExists(changeAddedAppointment, { change });\n } else {\n callActionIfExists(changeAppointment, { change });\n }\n },\n );\n\n getMessage = memoize((menuMessages, messages) =>\n getMessagesFormatter({ ...menuMessages, ...messages }));\n\n render() {\n const {\n containerComponent: Container,\n overlayComponent: Overlay,\n layoutComponent: Layout,\n commandLayoutComponent: CommandLayout,\n basicLayoutComponent: BasicLayout,\n recurrenceLayoutComponent: RecurrenceLayout,\n commandButtonComponent,\n textEditorComponent,\n labelComponent,\n dateEditorComponent,\n booleanEditorComponent,\n selectComponent,\n radioGroupComponent,\n weeklyRecurrenceSelectorComponent,\n resourceEditorComponent,\n readOnly,\n messages,\n } = this.props;\n const { visible, appointmentData, previousAppointment } = this.state;\n const getMessage = this.getMessage(defaultMessages, messages);\n return (\n \n \n\n \n \n {({\n editingAppointment,\n addedAppointment,\n appointmentChanges,\n\n resources,\n plainResources,\n }, {\n openCancelConfirmationDialog,\n\n stopEditAppointment,\n cancelAddedAppointment,\n cancelChangedAppointment,\n }) => {\n const { changedAppointment, isNew } = prepareChanges(\n appointmentData, editingAppointment,\n addedAppointment, appointmentChanges,\n resources, plainResources,\n );\n const fullSize = isFormFullSize(\n visible, changedAppointment.rRule, previousAppointment.rRule,\n );\n const onHideAction = () => visible && this.cancelChanges(\n openCancelConfirmationDialog, isNew, stopEditAppointment,\n { ...appointmentChanges, ...addedAppointment }, changedAppointment,\n cancelAddedAppointment, cancelChangedAppointment,\n )();\n\n return (\n \n \n \n \n \n \n );\n }}\n \n \n \n \n {({\n editingAppointment,\n addedAppointment,\n appointmentChanges,\n\n resources,\n plainResources,\n }, {\n commitAddedAppointment,\n finishCommitAppointment,\n finishDeleteAppointment,\n\n stopEditAppointment,\n cancelAddedAppointment,\n cancelChangedAppointment,\n\n openCancelConfirmationDialog,\n openDeleteConfirmationDialog,\n }) => {\n const { isNew, changedAppointment, isFormEdited } = prepareChanges(\n appointmentData, editingAppointment,\n addedAppointment, appointmentChanges,\n resources, plainResources,\n );\n const isRecurrence = isFormFullSize(\n visible, changedAppointment.rRule, previousAppointment.rRule,\n );\n return (\n \n );\n }}\n \n \n \n \n {({\n editingAppointment,\n addedAppointment,\n appointmentChanges,\n locale,\n\n resources,\n plainResources,\n }, {\n changeAppointment,\n changeAddedAppointment,\n }) => {\n const { isNew, changedAppointment, appointmentResources } = prepareChanges(\n appointmentData, editingAppointment,\n addedAppointment, appointmentChanges,\n resources, plainResources,\n );\n return (\n }\n />\n );\n }}\n \n \n\n \n \n {({\n editingAppointment,\n addedAppointment,\n appointmentChanges,\n formatDate,\n locale,\n firstDayOfWeek,\n }, {\n changeAddedAppointment,\n changeAppointment,\n }) => {\n const { isNew, changedAppointment } = prepareChanges(\n appointmentData, editingAppointment,\n addedAppointment, appointmentChanges,\n undefined, undefined,\n );\n const isRecurrenceLayoutVisible = isFormFullSize(\n visible, changedAppointment.rRule, previousAppointment.rRule,\n );\n const correctedAppointment = !changedAppointment.rRule\n ? { ...changedAppointment, rRule: previousAppointment.rRule } : changedAppointment;\n\n return (\n \n );\n }}\n \n \n\n \n {(params: AppointmentTooltip.LayoutProps) => (\n \n {(getters, { startEditAppointment }) => (\n {\n this.openFormHandler(params.appointmentMeta!.data);\n callActionIfExists(startEditAppointment, params.appointmentMeta!.data);\n },\n }}\n />\n )}\n \n )}\n \n\n \n {(params: Appointments.AppointmentProps) => (\n \n {(getters, { startEditAppointment }) => (\n {\n this.openFormHandler(params.data);\n callActionIfExists(startEditAppointment, params.data);\n },\n }}\n />\n )}\n \n )}\n \n\n \n {(params: any) => (\n \n {({ resources }, { addAppointment }) => addDoubleClickToCell(\n undefined, params.startDate, params.endDate, params.groupingInfo, resources,\n isAllDayCell(params.startDate, params.endDate),\n this.openFormHandler, addAppointment, params,\n )}\n \n )}\n \n\n \n {(params: any) => (\n \n {({ resources }, { addAppointment }) => addDoubleClickToCell(\n undefined, params.startDate, params.endDate, params.groupingInfo, resources,\n true, this.openFormHandler, addAppointment, params,\n )}\n \n )}\n \n \n );\n }\n}\n\n// tslint:disable-next-line: max-line-length\n/** The AppointmentForm plugin renders a form that visualizes appointment’s data and allows a user to modify this data. */\nexport const AppointmentForm: React.ComponentType = AppointmentFormBase;\n","import * as React from 'react';\nimport {\n Plugin, Template, TemplatePlaceholder,\n TemplateConnector, DropTarget, DragSource,\n DragDropProvider as DragDropProviderCore,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport {\n cellIndex, cellData, cellType, getAppointmentStyle, intervalDuration, autoScroll,\n calculateAppointmentTimeBoundaries, calculateInsidePart, RESIZE_TOP, RESIZE_BOTTOM,\n POSITION_START, POSITION_END, getAppointmentResources, calculateAppointmentGroups,\n appointmentDragged, calculateDraftAppointments,\n HORIZONTAL_GROUP_ORIENTATION, VERTICAL_GROUP_ORIENTATION, SCROLL_SPEED_PX,\n} from '@devexpress/dx-scheduler-core';\nimport { DragDropProviderProps, DragDropProviderState } from '../types';\n\nconst renderAppointmentItems = (items, Wrapper, draftData) => (\n items.length > 0 ? (\n \n {items.map((draftAppointment, index) => (\n \n ))}\n \n ) : (\n null\n )\n);\n\nconst pluginDependencies = [\n { name: 'EditingState' },\n { name: 'Appointments' },\n { name: 'EditRecurrenceMenu', optional: true },\n { name: 'IntegratedEditing', optional: true },\n { name: 'DayView', optional: true },\n { name: 'WeekView', optional: true },\n { name: 'MonthView', optional: true },\n { name: 'AllDayPanel', optional: true },\n];\n\nclass DragDropProviderBase extends React.PureComponent<\n DragDropProviderProps, DragDropProviderState\n> {\n timeTableDraftAppointments: any = [];\n allDayDraftAppointments: any = [];\n offsetTimeTop: number | null = null;\n appointmentStartTime: any = null;\n appointmentEndTime: any = null;\n appointmentGroupingInfo: any = {};\n\n state: DragDropProviderState = {\n startTime: null,\n endTime: null,\n appointmentGroupingInfo: null,\n payload: null,\n isOutside: false,\n allowDrag: () => true,\n allowResize: () => true,\n appointmentContentTemplateKey: 0,\n appointmentTopTemplateKey: 0,\n appointmentBottomTemplateKey: 0,\n };\n static components: PluginComponents = {\n containerComponent: 'Container',\n draftAppointmentComponent: 'DraftAppointment',\n sourceAppointmentComponent: 'SourceAppointment',\n resizeComponent: 'Resize',\n };\n static defaultProps: Partial = {\n allowDrag: () => true,\n allowResize: () => true,\n scrollSpeed: SCROLL_SPEED_PX,\n };\n static getDerivedStateFromProps(\n props: DragDropProviderProps, state: DragDropProviderState,\n ): DragDropProviderState | null {\n const isAllowDragSame = props.allowDrag === state.allowDrag;\n const isAllowResizeSame = props.allowResize === state.allowResize;\n\n if (isAllowDragSame && isAllowResizeSame) {\n return null;\n }\n\n return {\n ...state,\n appointmentContentTemplateKey:\n isAllowDragSame ? state.appointmentContentTemplateKey : Math.random(),\n appointmentTopTemplateKey:\n isAllowResizeSame ? state.appointmentTopTemplateKey : Math.random(),\n appointmentBottomTemplateKey:\n isAllowResizeSame ? state.appointmentBottomTemplateKey : Math.random(),\n allowDrag: props.allowDrag,\n allowResize: props.allowResize,\n };\n\n }\n\n onPayloadChange(actions) {\n return args => this.handlePayloadChange(args, actions);\n }\n\n calculateNextBoundaries(getters, actions, scrollSpeed) {\n return args => this.calculateBoundaries(args, getters, actions, scrollSpeed);\n }\n\n resetCache() {\n this.timeTableDraftAppointments = [];\n this.allDayDraftAppointments = [];\n this.offsetTimeTop = null;\n this.appointmentStartTime = null;\n this.appointmentEndTime = null;\n this.appointmentGroupingInfo = {};\n\n this.setState({\n payload: null,\n startTime: null,\n endTime: null,\n isOutside: false,\n });\n }\n\n applyChanges(\n startTime, endTime, payload, startEditAppointment, changeAppointment, appointmentGroupingInfo,\n ) {\n startEditAppointment(payload);\n changeAppointment({\n change: {\n startDate: startTime,\n endDate: endTime,\n ...payload.allDay && { allDay: undefined },\n ...this.appointmentGroupingInfo,\n },\n });\n this.setState({ startTime, endTime, payload, isOutside: false, appointmentGroupingInfo });\n }\n\n handlePayloadChange({ payload }, { finishCommitAppointment }) {\n const { isOutside } = this.state;\n if (payload || !isOutside) return;\n\n finishCommitAppointment();\n this.resetCache();\n }\n\n calculateBoundaries(\n { payload, clientOffset },\n {\n viewCellsData, allDayCellsData, startViewDate, endViewDate, excludedDays, currentView,\n timeTableElementsMeta, allDayElementsMeta, scrollingStrategy,\n grouping, resources, groups, groupOrientation: getGroupOrientation, groupByDate,\n },\n { changeAppointment, startEditAppointment },\n scrollSpeed,\n ) {\n if (clientOffset) {\n autoScroll(clientOffset, scrollingStrategy, scrollSpeed);\n }\n\n const tableCellElementsMeta = timeTableElementsMeta;\n const groupOrientation = getGroupOrientation\n ? getGroupOrientation(currentView?.name)\n : HORIZONTAL_GROUP_ORIENTATION;\n\n // AllDayPanel doesn't always exist\n const allDayCellsElementsMeta = allDayElementsMeta && allDayElementsMeta.getCellRects\n ? allDayElementsMeta\n : { getCellRects: [] };\n const timeTableIndex = cellIndex(tableCellElementsMeta.getCellRects, clientOffset);\n const allDayIndex = cellIndex(allDayCellsElementsMeta.getCellRects, clientOffset);\n\n if (allDayIndex === -1 && timeTableIndex === -1) return;\n\n const targetData = cellData(\n timeTableIndex, allDayIndex, viewCellsData, allDayCellsData,\n );\n const targetType = cellType(targetData);\n const insidePart = calculateInsidePart(\n clientOffset.y, tableCellElementsMeta.getCellRects, timeTableIndex,\n );\n const cellDurationMinutes = intervalDuration(targetData, 'minutes');\n\n const {\n appointmentStartTime, appointmentEndTime, offsetTimeTop,\n } = calculateAppointmentTimeBoundaries(\n payload, targetData, targetType, cellDurationMinutes,\n insidePart, this.offsetTimeTop!,\n );\n\n const appointmentGroups = calculateAppointmentGroups(\n targetData.groupingInfo, resources, payload,\n );\n\n this.appointmentStartTime = appointmentStartTime || this.appointmentStartTime;\n this.appointmentEndTime = appointmentEndTime || this.appointmentEndTime;\n this.appointmentGroupingInfo = appointmentGroups || this.appointmentGroupingInfo;\n this.offsetTimeTop = offsetTimeTop!;\n\n const { startTime, endTime, appointmentGroupingInfo } = this.state;\n if (!appointmentDragged(\n this.appointmentStartTime, startTime!,\n this.appointmentEndTime, endTime!,\n this.appointmentGroupingInfo, appointmentGroupingInfo,\n )) {\n return;\n }\n\n const draftAppointments = [{\n dataItem: {\n ...payload,\n startDate: this.appointmentStartTime,\n endDate: this.appointmentEndTime,\n ...this.appointmentGroupingInfo,\n },\n start: this.appointmentStartTime,\n end: this.appointmentEndTime,\n }];\n\n const {\n allDayDraftAppointments,\n timeTableDraftAppointments,\n } = calculateDraftAppointments(\n allDayIndex, draftAppointments, startViewDate,\n endViewDate, excludedDays, viewCellsData, allDayCellsElementsMeta,\n targetType, cellDurationMinutes, tableCellElementsMeta, grouping, resources, groups,\n groupOrientation, groupByDate?.(currentView?.name),\n );\n\n this.allDayDraftAppointments = allDayDraftAppointments;\n this.timeTableDraftAppointments = timeTableDraftAppointments;\n\n this.applyChanges(\n this.appointmentStartTime, this.appointmentEndTime,\n payload, startEditAppointment, changeAppointment,\n this.appointmentGroupingInfo,\n );\n }\n\n handleDrop = ({ finishCommitAppointment }) => () => {\n finishCommitAppointment();\n this.resetCache();\n }\n\n handleLeave = () => {\n this.setState({ isOutside: true });\n }\n\n render() {\n const {\n payload, appointmentContentTemplateKey,\n appointmentBottomTemplateKey, appointmentTopTemplateKey,\n } = this.state;\n const {\n containerComponent: Container,\n draftAppointmentComponent: DraftAppointment,\n sourceAppointmentComponent: SourceAppointment,\n resizeComponent: Resize,\n allowDrag,\n allowResize,\n scrollSpeed,\n } = this.props;\n\n const draftData = {\n ...payload, startDate: this.appointmentStartTime, endDate: this.appointmentEndTime,\n };\n\n return (\n \n \n \n {({\n viewCellsData, allDayCellsData, startViewDate, endViewDate, excludedDays,\n timeTableElementsMeta, allDayElementsMeta, scrollingStrategy,\n grouping, resources, groups, currentView, groupByDate, groupOrientation,\n }, {\n changeAppointment, startEditAppointment, finishCommitAppointment,\n }) => {\n const calculateBoundariesByMove = this.calculateNextBoundaries({\n viewCellsData, allDayCellsData, currentView,\n startViewDate, endViewDate, excludedDays,\n timeTableElementsMeta, allDayElementsMeta, scrollingStrategy,\n resources, grouping, groups, groupByDate, groupOrientation,\n }, { changeAppointment, startEditAppointment }, scrollSpeed);\n return (\n \n \n \n \n \n );\n }}\n \n \n\n allowDrag!(data)}\n key={appointmentContentTemplateKey}\n >\n {({ styles, ...params }: any) => (\n \n {payload && params.data.id === payload.id ? (\n \n ) : (\n \n )}\n \n )}\n \n\n !params.slice && allowResize!(params.data)}\n key={appointmentTopTemplateKey}\n >\n {({ data, type }: any) => (\n \n \n \n )}\n \n\n !params.slice && allowResize!(params.data)}\n key={appointmentBottomTemplateKey}\n >\n {({ data, type }: any) => (\n \n \n \n )}\n \n\n \n \n {({ currentView, groupOrientation }) => (\n <>\n \n {groupOrientation?.(currentView.name) !== VERTICAL_GROUP_ORIENTATION\n ? renderAppointmentItems(this.allDayDraftAppointments, Container, draftData)\n : null}\n >\n )}\n \n \n\n \n \n {({ currentView, groupOrientation }) => (\n <>\n \n {renderAppointmentItems(this.timeTableDraftAppointments, Container, draftData)}\n {groupOrientation?.(currentView.name) === VERTICAL_GROUP_ORIENTATION\n ? renderAppointmentItems(this.allDayDraftAppointments, Container, draftData)\n : null}\n >\n )}\n \n \n\n \n {({ data, draftAppointment, ...restParams }: any) => (\n \n {({ formatDate, resources, plainResources }) => {\n const {\n dataItem, type, fromPrev, toNext, durationType, ...geometry\n } = draftAppointment;\n return (\n \n );\n }}\n \n )}\n \n \n );\n }\n}\n\n/** A plugin that enables users to edit appointments via drag-and-drop. */\nexport const DragDropProvider: React.ComponentType = DragDropProviderBase;\n","import * as React from 'react';\nimport { getMessagesFormatter } from '@devexpress/dx-core';\nimport {\n Plugin,\n Template,\n TemplatePlaceholder,\n TemplateConnector,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport { TodayButtonProps } from '../types';\n\nconst pluginDependencies = [\n { name: 'Toolbar' },\n { name: 'ViewState' },\n];\n\nconst defaultMessages = {\n today: 'Today',\n};\n\nclass TodayButtonBase extends React.PureComponent {\n static components: PluginComponents = {\n buttonComponent: 'Button',\n };\n render() {\n const {\n buttonComponent: Button,\n messages,\n } = this.props;\n const getMessage = getMessagesFormatter({ ...defaultMessages, ...messages });\n\n return (\n \n \n \n {(getters, {\n changeCurrentDate,\n }) => {\n const setCurrentDate = nextDate => changeCurrentDate({\n nextDate,\n });\n return (\n \n );\n }}\n \n \n \n \n );\n }\n}\n\n/** A plugin that renders the Scheduler's button which sets the current date to today's date. */\nexport const TodayButton: React.ComponentType = TodayButtonBase;\n","import * as React from 'react';\nimport { memoize, getMessagesFormatter } from '@devexpress/dx-core';\nimport {\n Plugin, Template, TemplatePlaceholder, TemplateConnector, Action, Getters, Actions,\n} from '@devexpress/dx-react-core';\nimport { RECURRENCE_EDIT_SCOPE } from '@devexpress/dx-scheduler-core';\nimport { EditRecurrenceMenuProps, EditRecurrenceMenuState } from '../types';\n\nconst pluginDependencies = [\n { name: 'EditingState' },\n];\n\nconst defaultAvailableOperations = [\n { value: RECURRENCE_EDIT_SCOPE.CURRENT },\n { value: RECURRENCE_EDIT_SCOPE.CURRENT_AND_FOLLOWING },\n { value: RECURRENCE_EDIT_SCOPE.ALL },\n];\n\nconst defaultMessages = {\n [RECURRENCE_EDIT_SCOPE.CURRENT]: 'This appointment',\n [RECURRENCE_EDIT_SCOPE.CURRENT_AND_FOLLOWING]: 'This and following appointments',\n [RECURRENCE_EDIT_SCOPE.ALL]: 'All appointments',\n menuEditingTitle: 'Edit recurring appointment',\n menuDeletingTitle: 'Delete recurring appointment',\n cancelButton: 'Cancel',\n commitButton: 'OK',\n};\n\nclass EditRecurrenceMenuBase extends React.PureComponent<\n EditRecurrenceMenuProps, EditRecurrenceMenuState\n> {\n static components = {\n layoutComponent: 'Layout',\n overlayComponent: 'Overlay',\n buttonComponent: 'Button',\n containerComponent: 'Container',\n };\n\n modalContainer = React.createRef();\n\n state = {\n isOpen: false,\n deletedAppointmentData: null,\n };\n\n finishCommitAppointment = (\n payload,\n { editingAppointment }: Getters,\n { commitChangedAppointment }: Actions,\n ) => {\n if (editingAppointment && !editingAppointment.rRule) {\n commitChangedAppointment();\n } else {\n this.setState({\n isOpen: true, deletedAppointmentData: null,\n });\n }\n }\n\n finishDeleteAppointment = (\n payload,\n getters,\n { commitDeletedAppointment }: Actions,\n ) => {\n if (payload && !payload.rRule) {\n commitDeletedAppointment({ deletedAppointmentData: payload });\n } else {\n this.setState({\n isOpen: true, deletedAppointmentData: payload,\n });\n }\n }\n\n commit = memoize((editAction, deleteAction, payload) => (type) => {\n if (payload) {\n deleteAction({ deletedAppointmentData: payload, type });\n } else {\n editAction(type);\n }\n this.closeMenu();\n });\n\n closeMenu = () => {\n this.setState({ isOpen: false, deletedAppointmentData: null });\n }\n\n cancelEditing = memoize((cancelAction, stopEditAction) => () => {\n stopEditAction();\n cancelAction();\n this.closeMenu();\n });\n\n availableOperations = memoize((getMessage, menuAvailableOperations) =>\n menuAvailableOperations.map(({ value }) => ({\n value,\n title: getMessage([value]),\n })));\n\n getMessage = memoize((messages, menuMessages) =>\n getMessagesFormatter({ ...menuMessages, ...messages }));\n\n render() {\n const { isOpen, deletedAppointmentData } = this.state;\n const {\n layoutComponent: Layout,\n overlayComponent: Overlay,\n containerComponent: Container,\n buttonComponent,\n messages,\n } = this.props;\n\n const getMessage = this.getMessage(messages, defaultMessages);\n const availableOperations = this.availableOperations(getMessage, defaultAvailableOperations);\n\n return (\n \n \n \n\n \n \n \n \n \n\n \n \n {(getters, {\n commitChangedAppointment, commitDeletedAppointment,\n cancelChangedAppointment, stopEditAppointment,\n }) => {\n const commit = this.commit(\n commitChangedAppointment, commitDeletedAppointment, deletedAppointmentData,\n );\n const cancelEditing = this.cancelEditing(\n cancelChangedAppointment, stopEditAppointment,\n );\n\n return (\n \n \n \n );\n }}\n \n \n \n );\n }\n}\n\n/**\n * A plugin that renders the Scheduler's edit menu.\n * Should not be used with the `IntegratedEditing` plugin.\n */\nexport const EditRecurrenceMenu: React.ComponentType<\n EditRecurrenceMenuProps\n> = EditRecurrenceMenuBase;\n","import * as React from 'react';\nimport { Action, Plugin, Actions } from '@devexpress/dx-react-core';\nimport { IntegratedEditingProps } from '../types';\n\nconst pluginDependencies = [\n { name: 'EditingState' },\n];\n\nclass IntegratedEditingBase extends React.PureComponent {\n static defaultProps = {\n totalCount: 0,\n };\n\n finishCommitAppointment = (payload, getters, { commitChangedAppointment }: Actions) => {\n commitChangedAppointment();\n }\n\n finishDeleteAppointment = (payload, getters, { commitDeletedAppointment }: Actions) => {\n commitDeletedAppointment({ deletedAppointmentData: payload });\n }\n\n render() {\n return (\n \n \n \n \n );\n }\n}\n\n/** A plugin that allows implementing a editing calculation logic. */\nexport const IntegratedEditing: React.ComponentType = IntegratedEditingBase;\n","import * as React from 'react';\nimport { Plugin, Getter, Getters } from '@devexpress/dx-react-core';\nimport {\n convertResourcesToPlain, validateResources, addResourcesToAppointments,\n} from '@devexpress/dx-scheduler-core';\nimport { ResourcesProps } from '../types/resources/resources.types';\n\nconst pluginDependencies = [\n { name: 'Appointments' },\n];\n\nconst addResourcesToTimeTableAppointments = ({\n timeTableAppointments, resources, plainResources,\n}: Getters) => timeTableAppointments\n && addResourcesToAppointments(timeTableAppointments[0], resources, plainResources);\nconst addResourcesToAllDayAppointments = ({\n allDayAppointments, resources, plainResources,\n }: Getters) => allDayAppointments\n && addResourcesToAppointments(allDayAppointments[0], resources, plainResources);\n\nconst ResourcesBase: React.SFC = React.memo(({\n data, mainResourceName, palette,\n}) => {\n const convertResources = ({ resources }: Getters) =>\n convertResourcesToPlain(resources);\n\n return (\n \n \n \n \n \n \n );\n});\n\n/** A plugin that manages schedule's resources. */\nexport const Resources: React.ComponentType = ResourcesBase;\n","import * as React from 'react';\nimport { getMessagesFormatter } from '@devexpress/dx-core';\nimport {\n Plugin,\n Template,\n TemplatePlaceholder,\n TemplateConnector,\n Action,\n} from '@devexpress/dx-react-core';\nimport { ConfirmationDialogProps } from '../types/editing/confirmation-dialog.types';\nimport { AppointmentModel } from '@devexpress/dx-scheduler-core';\n\nconst defaultMessages = {\n discardButton: 'Discard',\n deleteButton: 'Delete',\n cancelButton: 'Cancel',\n confirmDeleteMessage: 'Are you sure you want to delete this appointment?',\n confirmCancelMessage: 'Discard unsaved changes?',\n};\n\nconst pluginDependencies = [\n { name: 'EditingState' },\n { name: 'EditRecurrenceMenu', optional: true },\n { name: 'IntegratedEditing', optional: true },\n];\n\nconst ACTION_TYPES = {\n CANCEL: 'cancel',\n DELETE: 'delete',\n};\n\nconst ConfirmationDialogBase: React.SFC & {components: {\n overlayComponent: string, containerComponent: string,\n layoutComponent: string, buttonComponent: string,\n}} = ({\n messages, overlayComponent: Overlay, layoutComponent: Layout, containerComponent: Container,\n buttonComponent, ignoreDelete, ignoreCancel,\n}) => {\n const getMessage = getMessagesFormatter({ ...defaultMessages, ...messages });\n const modalContainer = React.useRef();\n\n const [visible, setVisible] = React.useState(false);\n const [actionType, setActionType] = React.useState('');\n const [hideActionName, setHideActionName] = React.useState('');\n const [appointmentData, setAppointmentData] = React.useState({});\n\n const toggleVisibility = React.useCallback(() => {\n setVisible(!visible);\n }, [visible, setVisible]);\n\n const confirmCancelChanges = React.useCallback((hideAction) => {\n toggleVisibility();\n setHideActionName(hideAction);\n setActionType(ACTION_TYPES.CANCEL);\n }, [toggleVisibility, setHideActionName, setActionType]);\n\n const confirmDelete = React.useCallback(({\n hideActionName: hideAction, appointmentData: changedAppointment,\n }) => {\n toggleVisibility();\n setHideActionName(hideAction);\n setActionType(ACTION_TYPES.DELETE);\n setAppointmentData(changedAppointment);\n }, [toggleVisibility, setHideActionName, setActionType, setAppointmentData]);\n\n const confirmAction = React.useCallback((\n isNewAppointment, hideEditor, stopEditAppointment, finishDeleteAppointment,\n cancelAddedAppointment, cancelChangedAppointment,\n ) => () => {\n hideEditor();\n toggleVisibility();\n if (isNewAppointment) {\n cancelAddedAppointment();\n } else {\n stopEditAppointment();\n cancelChangedAppointment();\n }\n if (actionType === ACTION_TYPES.DELETE) {\n finishDeleteAppointment(appointmentData);\n }\n }, [toggleVisibility, actionType, appointmentData]);\n\n return (\n \n {!ignoreCancel &&\n \n }\n {!ignoreDelete &&\n \n }\n\n \n \n \n \n \n\n \n \n {({\n editingAppointment,\n }, actions) => {\n const handleConfirm = confirmAction(\n !editingAppointment, actions[hideActionName], actions.stopEditAppointment,\n actions.finishDeleteAppointment, actions.cancelAddedAppointment,\n actions.cancelChangedAppointment,\n );\n\n return (\n \n \n \n );\n }}\n \n \n \n );\n};\n\nConfirmationDialogBase.components = {\n overlayComponent: 'Overlay',\n containerComponent: 'Container',\n layoutComponent: 'Layout',\n buttonComponent: 'Button',\n};\n\nConfirmationDialogBase.defaultProps = {\n ignoreCancel: false,\n ignoreDelete: false,\n};\n\n// tslint:disable-next-line: max-line-length\n/** A plugin that renders the dialog which allows users to confirm or to discard delete and cancel appointment actions. */\nexport const ConfirmationDialog: React.ComponentType<\n ConfirmationDialogProps\n> = ConfirmationDialogBase;\n","import * as React from 'react';\nimport {\n Plugin,\n Template,\n TemplateConnector,\n PluginComponents,\n} from '@devexpress/dx-react-core';\nimport { GroupingPanelProps } from '../types';\nimport {\n VERTICAL_VIEW_LEFT_OFFSET, HORIZONTAL_VIEW_LEFT_OFFSET,\n HORIZONTAL_GROUP_ORIENTATION, VIEW_TYPES,\n} from '@devexpress/dx-scheduler-core';\n\nconst pluginDependencies = [\n { name: 'GroupingState' },\n { name: 'IntegratedGrouping' },\n { name: 'DayView', optional: true },\n { name: 'MonthView', optional: true },\n { name: 'WeekView', optional: true },\n { name: 'ViewState', optional: true },\n];\n\nclass GroupingPanelBase extends React.PureComponent {\n static components: PluginComponents = {\n horizontalLayoutComponent: 'HorizontalLayout',\n verticalLayoutComponent: 'VerticalLayout',\n rowComponent: 'Row',\n cellComponent: 'Cell',\n };\n\n render() {\n const {\n horizontalLayoutComponent: HorizontalLayout,\n verticalLayoutComponent: VerticalLayout,\n rowComponent,\n cellComponent,\n } = this.props;\n\n return (\n \n \n \n {({\n viewCellsData, currentView, scrollingStrategy, allDayPanelExists,\n groupByDate, groupOrientation: getGroupOrientation, groups,\n }) => {\n const groupOrientation = getGroupOrientation(currentView?.name);\n return groupOrientation === HORIZONTAL_GROUP_ORIENTATION ? (\n \n ) : (\n \n );\n }}\n \n \n \n );\n }\n}\n\n/** A plugin that renders the grouping panel used to display group names. */\nexport const GroupingPanel: React.ComponentType = GroupingPanelBase;\n","import * as React from 'react';\nimport {\n Action, Plugin, Getter, StateHelper, ActionFn, createStateHelper,\n} from '@devexpress/dx-react-core';\nimport {\n ToggleGroupPayload, toggleExpandedGroups, HORIZONTAL_GROUP_ORIENTATION,\n} from '@devexpress/dx-scheduler-core';\nimport { GroupingStateProps, GroupingStateState } from '../types';\n\nclass GroupingStateBase extends React.PureComponent {\n static defaultProps = {\n defaultExpandedGroups: [],\n groupByDate: () => false,\n groupOrientation: () => HORIZONTAL_GROUP_ORIENTATION,\n };\n stateHelper: StateHelper;\n toggleGroupExpanded: ActionFn;\n\n constructor(props) {\n super(props);\n\n this.state = {\n grouping: props.grouping,\n expandedGroups: props.expandedGroups || props.defaultExpandedGroups,\n };\n this.stateHelper = createStateHelper(\n this,\n {\n expandedGroups: () => {\n const { onExpandedGroupsChange } = this.props;\n return onExpandedGroupsChange;\n },\n },\n );\n this.toggleGroupExpanded = this.stateHelper.applyReducer\n .bind(this.stateHelper, toggleExpandedGroups);\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n const {\n grouping = prevState.grouping,\n expandedGroups = prevState.expandedGroups,\n } = nextProps;\n\n return { grouping, expandedGroups };\n }\n\n render() {\n const { grouping, expandedGroups } = this.state;\n const { groupByDate, groupOrientation } = this.props;\n\n return (\n \n \n \n \n\n \n \n \n );\n }\n}\n\n/** A plugin that manages the grouping state. */\nexport const GroupingState: React.ComponentType = GroupingStateBase;\n","import * as React from 'react';\nimport {\n Plugin,\n Template,\n TemplatePlaceholder,\n} from '@devexpress/dx-react-core';\nimport {\n isMonthCell, isShadedAppointment,\n isCellShaded, getCurrentTimeIndicatorTop,\n} from '@devexpress/dx-scheduler-core';\nimport { CurrentTimeIndicatorProps, Appointments } from '../types';\n\nconst pluginDependencies = [\n { name: 'DayView', optional: true },\n { name: 'WeekView', optional: true },\n { name: 'MonthView', optional: true },\n { name: 'DragDropProvider', optional: true },\n { name: 'Appointments', optional: true },\n];\n\nconst CurrentTimeIndicatorBase: React.SFC & {components: {\n indicatorComponent: string,\n}} = ({\n indicatorComponent, shadePreviousAppointments, shadePreviousCells, updateInterval,\n}) => {\n const [currentTime, setCurrentTime] = React.useState(Date.now);\n\n React.useEffect(() => {\n const tick = () => setCurrentTime(Date.now());\n const intervalId = (updateInterval\n ? window.setInterval(tick, updateInterval)\n : undefined\n );\n return () => window.clearInterval(intervalId);\n }, [updateInterval]);\n\n return (\n \n !isMonthCell(otherMonth)}\n >\n {(params: any) => (\n \n )}\n \n \n {(params: any) => (\n \n )}\n \n \n {(params: Appointments.AppointmentProps) => (\n \n )}\n \n \n {(params: Appointments.AppointmentProps) => (\n \n )}\n \n \n );\n};\n\nCurrentTimeIndicatorBase.defaultProps = {\n updateInterval: 60000,\n shadePreviousCells: false,\n shadePreviousAppointments: false,\n};\n\nCurrentTimeIndicatorBase.components = {\n indicatorComponent: 'Indicator',\n};\n\n// tslint:disable-next-line: max-line-length\n/** A plugin that renders the current time indicator and the shading that covers appointments and timetable cells up to the current time. */\nexport const CurrentTimeIndicator: React.ComponentType<\n CurrentTimeIndicatorProps\n> = CurrentTimeIndicatorBase;\n","import * as React from 'react';\nimport { Plugin, Getter, Getters } from '@devexpress/dx-react-core';\nimport {\n getGroupsFromResources, expandViewCellsDataWithGroups,\n sortFilteredResources, filterResourcesByGrouping, updateGroupingWithMainResource,\n expandGroups, VERTICAL_GROUP_ORIENTATION, VIEW_TYPES,\n updateTimeTableCellElementsMeta, updateAllDayCellElementsMeta, updateTimeCellsData,\n} from '@devexpress/dx-scheduler-core';\nimport { IntegratedGroupingProps } from '../types';\n\nconst pluginDependencies = [\n { name: 'Resources' },\n { name: 'GroupingState' },\n { name: 'DayView', optional: true },\n { name: 'MonthView', optional: true },\n { name: 'WeekView', optional: true },\n];\n\nconst getViewCellsDataComputed = ({\n viewCellsData, groups, resourcesToGroupBy, groupByDate, currentView, groupOrientation,\n}: Getters) => expandViewCellsDataWithGroups(\n viewCellsData, groups, resourcesToGroupBy,\n groupByDate(currentView.name), groupOrientation(currentView.name),\n);\nconst getAllDayCellsDataComputed = ({\n allDayCellsData, groups, resourcesToGroupBy, groupByDate, currentView, groupOrientation,\n}: Getters) => allDayCellsData && expandViewCellsDataWithGroups(\n allDayCellsData, groups, resourcesToGroupBy,\n groupByDate(currentView.name), groupOrientation(currentView.name),\n);\n\nconst getGroupsComputed = (\n { resourcesToGroupBy }: Getters,\n) => getGroupsFromResources(resourcesToGroupBy);\n\nconst getResourcesToGroupByComputed = (\n { resources, grouping }: Getters,\n) => sortFilteredResources(filterResourcesByGrouping(resources, grouping), grouping);\n\nconst getGroupingComputed = (\n { grouping, resources }: Getters,\n) => updateGroupingWithMainResource(grouping, resources);\n\nconst getTimeTableAppointmentsComputed = ({\n timeTableAppointments, grouping, resourcesToGroupBy,\n groups, groupByDate, currentView, excludedDays,\n}: Getters) => timeTableAppointments\n && expandGroups(\n timeTableAppointments, grouping, resourcesToGroupBy, groups,\n excludedDays, groupByDate(currentView?.name) && currentView?.type === VIEW_TYPES.MONTH,\n );\n\nconst getAllDayAppointmentsComputed = ({\n allDayAppointments, grouping, resourcesToGroupBy,\n groups, groupByDate, currentView, excludedDays,\n }: Getters) => allDayAppointments &&\n expandGroups(\n allDayAppointments, grouping, resourcesToGroupBy,\n groups, excludedDays, groupByDate(currentView?.name),\n );\n\nconst getGroupByDateComputed = ({\n currentView, groupByDate, groupOrientation,\n}: Getters) => groupOrientation(currentView?.name) === VERTICAL_GROUP_ORIENTATION\n ? () => false : groupByDate;\n\nconst getTimeTableElementsMetaComputed = ({\n timeTableElementsMeta, groupOrientation, groups, allDayPanelExists, viewCellsData, currentView,\n}: Getters) => updateTimeTableCellElementsMeta(\n timeTableElementsMeta, groupOrientation, groups, allDayPanelExists, viewCellsData, currentView,\n);\n\nconst getAllDayElementsMetaComputed = ({\n allDayElementsMeta, timeTableElementsMeta, groupOrientation, groups,\n allDayPanelExists, viewCellsData, currentView,\n}: Getters) => updateAllDayCellElementsMeta(\n allDayElementsMeta, timeTableElementsMeta, groupOrientation, groups,\n allDayPanelExists, viewCellsData, currentView,\n);\n\nconst getTimeCellsDataComputed = ({\n viewCellsData, timeCellsData, currentView,\n groups, resourcesToGroupBy, groupOrientation,\n}: Getters) => timeCellsData\n && updateTimeCellsData(\n viewCellsData,\n timeCellsData,\n groups,\n resourcesToGroupBy,\n groupOrientation(currentView.name),\n );\n\nconst IntegratedGroupingBase: React.SFC = React.memo(() => (\n \n \n \n \n \n\n \n \n \n\n \n \n\n \n \n \n));\n\n/** A plugin that implements grouping. */\nexport const IntegratedGrouping: React.ComponentType<\n IntegratedGroupingProps\n> = IntegratedGroupingBase;\n","import * as React from 'react';\nimport setRef from './setRef';\nexport default function useForkRef(refA, refB) {\n /**\n * This will create a new function if the ref props change and are defined.\n * This means react will call the old forkRef with `null` and the new forkRef\n * with the ref. Cleanup naturally emerges from this behavior\n */\n return React.useMemo(function () {\n if (refA == null && refB == null) {\n return null;\n }\n\n return function (refValue) {\n setRef(refA, refValue);\n setRef(refB, refValue);\n };\n }, [refA, refB]);\n}","module.exports = require(\"regenerator-runtime\");\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nexport default function _superPropBase(object, property) {\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = getPrototypeOf(object);\n if (object === null) break;\n }\n\n return object;\n}","import superPropBase from \"./superPropBase.js\";\nexport default function _get() {\n if (typeof Reflect !== \"undefined\" && Reflect.get) {\n _get = Reflect.get;\n } else {\n _get = function _get(target, property, receiver) {\n var base = superPropBase(target, property);\n if (!base) return;\n var desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.get) {\n return desc.get.call(arguments.length < 3 ? target : receiver);\n }\n\n return desc.value;\n };\n }\n\n return _get.apply(this, arguments);\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n Object.defineProperty(subClass, \"prototype\", {\n writable: false\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import _typeof from \"./typeof.js\";\nimport assertThisInitialized from \"./assertThisInitialized.js\";\nexport default function _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n\n return assertThisInitialized(self);\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nimport possibleConstructorReturn from \"./possibleConstructorReturn.js\";\nexport default function _createSuper(Derived) {\n var hasNativeReflectConstruct = isNativeReflectConstruct();\n return function _createSuperInternal() {\n var Super = getPrototypeOf(Derived),\n result;\n\n if (hasNativeReflectConstruct) {\n var NewTarget = getPrototypeOf(this).constructor;\n result = Reflect.construct(Super, arguments, NewTarget);\n } else {\n result = Super.apply(this, arguments);\n }\n\n return possibleConstructorReturn(this, result);\n };\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","/*!\n * Chart.js v3.7.1\n * https://www.chartjs.org\n * (c) 2022 Chart.js Contributors\n * Released under the MIT License\n */\nimport { r as requestAnimFrame, a as resolve, e as effects, c as color, d as defaults, i as isObject, b as isArray, v as valueOrDefault, u as unlistenArrayEvents, l as listenArrayEvents, f as resolveObjectKey, g as isNumberFinite, h as createContext, j as defined, s as sign, k as isNullOrUndef, _ as _arrayUnique, t as toRadians, m as toPercentage, n as toDimension, T as TAU, o as formatNumber, p as _angleBetween, H as HALF_PI, P as PI, q as isNumber, w as _limitValue, x as _lookupByKey, y as getRelativePosition$1, z as _isPointInArea, A as _rlookupByKey, B as getAngleFromPoint, C as toPadding, D as each, E as getMaximumSize, F as _getParentNode, G as readUsedSize, I as throttled, J as supportsEventListenerOptions, K as _isDomSupported, L as log10, M as _factorize, N as finiteOrDefault, O as callback, Q as _addGrace, R as toDegrees, S as _measureText, U as _int16Range, V as _alignPixel, W as clipArea, X as renderText, Y as unclipArea, Z as toFont, $ as _toLeftRightCenter, a0 as _alignStartEnd, a1 as overrides, a2 as merge, a3 as _capitalize, a4 as descriptors, a5 as isFunction, a6 as _attachContext, a7 as _createResolver, a8 as _descriptors, a9 as mergeIf, aa as uid, ab as debounce, ac as retinaScale, ad as clearCanvas, ae as setsEqual, af as _elementsEqual, ag as _isClickEvent, ah as _isBetween, ai as _readValueToProps, aj as _updateBezierControlPoints, ak as _computeSegments, al as _boundSegments, am as _steppedInterpolation, an as _bezierInterpolation, ao as _pointInLine, ap as _steppedLineTo, aq as _bezierCurveTo, ar as drawPoint, as as addRoundedRectPath, at as toTRBL, au as toTRBLCorners, av as _boundSegment, aw as _normalizeAngle, ax as getRtlAdapter, ay as overrideTextDirection, az as _textX, aA as restoreTextDirection, aB as noop, aC as distanceBetweenPoints, aD as _setMinAndMaxByKey, aE as niceNum, aF as almostWhole, aG as almostEquals, aH as _decimalPlaces, aI as _longestText, aJ as _filterBetween, aK as _lookup } from './chunks/helpers.segment.js';\nexport { d as defaults } from './chunks/helpers.segment.js';\n\nclass Animator {\n constructor() {\n this._request = null;\n this._charts = new Map();\n this._running = false;\n this._lastDate = undefined;\n }\n _notify(chart, anims, date, type) {\n const callbacks = anims.listeners[type];\n const numSteps = anims.duration;\n callbacks.forEach(fn => fn({\n chart,\n initial: anims.initial,\n numSteps,\n currentStep: Math.min(date - anims.start, numSteps)\n }));\n }\n _refresh() {\n if (this._request) {\n return;\n }\n this._running = true;\n this._request = requestAnimFrame.call(window, () => {\n this._update();\n this._request = null;\n if (this._running) {\n this._refresh();\n }\n });\n }\n _update(date = Date.now()) {\n let remaining = 0;\n this._charts.forEach((anims, chart) => {\n if (!anims.running || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n let draw = false;\n let item;\n for (; i >= 0; --i) {\n item = items[i];\n if (item._active) {\n if (item._total > anims.duration) {\n anims.duration = item._total;\n }\n item.tick(date);\n draw = true;\n } else {\n items[i] = items[items.length - 1];\n items.pop();\n }\n }\n if (draw) {\n chart.draw();\n this._notify(chart, anims, date, 'progress');\n }\n if (!items.length) {\n anims.running = false;\n this._notify(chart, anims, date, 'complete');\n anims.initial = false;\n }\n remaining += items.length;\n });\n this._lastDate = date;\n if (remaining === 0) {\n this._running = false;\n }\n }\n _getAnims(chart) {\n const charts = this._charts;\n let anims = charts.get(chart);\n if (!anims) {\n anims = {\n running: false,\n initial: true,\n items: [],\n listeners: {\n complete: [],\n progress: []\n }\n };\n charts.set(chart, anims);\n }\n return anims;\n }\n listen(chart, event, cb) {\n this._getAnims(chart).listeners[event].push(cb);\n }\n add(chart, items) {\n if (!items || !items.length) {\n return;\n }\n this._getAnims(chart).items.push(...items);\n }\n has(chart) {\n return this._getAnims(chart).items.length > 0;\n }\n start(chart) {\n const anims = this._charts.get(chart);\n if (!anims) {\n return;\n }\n anims.running = true;\n anims.start = Date.now();\n anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);\n this._refresh();\n }\n running(chart) {\n if (!this._running) {\n return false;\n }\n const anims = this._charts.get(chart);\n if (!anims || !anims.running || !anims.items.length) {\n return false;\n }\n return true;\n }\n stop(chart) {\n const anims = this._charts.get(chart);\n if (!anims || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n for (; i >= 0; --i) {\n items[i].cancel();\n }\n anims.items = [];\n this._notify(chart, anims, Date.now(), 'complete');\n }\n remove(chart) {\n return this._charts.delete(chart);\n }\n}\nvar animator = new Animator();\n\nconst transparent = 'transparent';\nconst interpolators = {\n boolean(from, to, factor) {\n return factor > 0.5 ? to : from;\n },\n color(from, to, factor) {\n const c0 = color(from || transparent);\n const c1 = c0.valid && color(to || transparent);\n return c1 && c1.valid\n ? c1.mix(c0, factor).hexString()\n : to;\n },\n number(from, to, factor) {\n return from + (to - from) * factor;\n }\n};\nclass Animation {\n constructor(cfg, target, prop, to) {\n const currentValue = target[prop];\n to = resolve([cfg.to, to, currentValue, cfg.from]);\n const from = resolve([cfg.from, currentValue, to]);\n this._active = true;\n this._fn = cfg.fn || interpolators[cfg.type || typeof from];\n this._easing = effects[cfg.easing] || effects.linear;\n this._start = Math.floor(Date.now() + (cfg.delay || 0));\n this._duration = this._total = Math.floor(cfg.duration);\n this._loop = !!cfg.loop;\n this._target = target;\n this._prop = prop;\n this._from = from;\n this._to = to;\n this._promises = undefined;\n }\n active() {\n return this._active;\n }\n update(cfg, to, date) {\n if (this._active) {\n this._notify(false);\n const currentValue = this._target[this._prop];\n const elapsed = date - this._start;\n const remain = this._duration - elapsed;\n this._start = date;\n this._duration = Math.floor(Math.max(remain, cfg.duration));\n this._total += elapsed;\n this._loop = !!cfg.loop;\n this._to = resolve([cfg.to, to, currentValue, cfg.from]);\n this._from = resolve([cfg.from, currentValue, to]);\n }\n }\n cancel() {\n if (this._active) {\n this.tick(Date.now());\n this._active = false;\n this._notify(false);\n }\n }\n tick(date) {\n const elapsed = date - this._start;\n const duration = this._duration;\n const prop = this._prop;\n const from = this._from;\n const loop = this._loop;\n const to = this._to;\n let factor;\n this._active = from !== to && (loop || (elapsed < duration));\n if (!this._active) {\n this._target[prop] = to;\n this._notify(true);\n return;\n }\n if (elapsed < 0) {\n this._target[prop] = from;\n return;\n }\n factor = (elapsed / duration) % 2;\n factor = loop && factor > 1 ? 2 - factor : factor;\n factor = this._easing(Math.min(1, Math.max(0, factor)));\n this._target[prop] = this._fn(from, to, factor);\n }\n wait() {\n const promises = this._promises || (this._promises = []);\n return new Promise((res, rej) => {\n promises.push({res, rej});\n });\n }\n _notify(resolved) {\n const method = resolved ? 'res' : 'rej';\n const promises = this._promises || [];\n for (let i = 0; i < promises.length; i++) {\n promises[i][method]();\n }\n }\n}\n\nconst numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];\nconst colors = ['color', 'borderColor', 'backgroundColor'];\ndefaults.set('animation', {\n delay: undefined,\n duration: 1000,\n easing: 'easeOutQuart',\n fn: undefined,\n from: undefined,\n loop: undefined,\n to: undefined,\n type: undefined,\n});\nconst animationOptions = Object.keys(defaults.animation);\ndefaults.describe('animation', {\n _fallback: false,\n _indexable: false,\n _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',\n});\ndefaults.set('animations', {\n colors: {\n type: 'color',\n properties: colors\n },\n numbers: {\n type: 'number',\n properties: numbers\n },\n});\ndefaults.describe('animations', {\n _fallback: 'animation',\n});\ndefaults.set('transitions', {\n active: {\n animation: {\n duration: 400\n }\n },\n resize: {\n animation: {\n duration: 0\n }\n },\n show: {\n animations: {\n colors: {\n from: 'transparent'\n },\n visible: {\n type: 'boolean',\n duration: 0\n },\n }\n },\n hide: {\n animations: {\n colors: {\n to: 'transparent'\n },\n visible: {\n type: 'boolean',\n easing: 'linear',\n fn: v => v | 0\n },\n }\n }\n});\nclass Animations {\n constructor(chart, config) {\n this._chart = chart;\n this._properties = new Map();\n this.configure(config);\n }\n configure(config) {\n if (!isObject(config)) {\n return;\n }\n const animatedProps = this._properties;\n Object.getOwnPropertyNames(config).forEach(key => {\n const cfg = config[key];\n if (!isObject(cfg)) {\n return;\n }\n const resolved = {};\n for (const option of animationOptions) {\n resolved[option] = cfg[option];\n }\n (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {\n if (prop === key || !animatedProps.has(prop)) {\n animatedProps.set(prop, resolved);\n }\n });\n });\n }\n _animateOptions(target, values) {\n const newOptions = values.options;\n const options = resolveTargetOptions(target, newOptions);\n if (!options) {\n return [];\n }\n const animations = this._createAnimations(options, newOptions);\n if (newOptions.$shared) {\n awaitAll(target.options.$animations, newOptions).then(() => {\n target.options = newOptions;\n }, () => {\n });\n }\n return animations;\n }\n _createAnimations(target, values) {\n const animatedProps = this._properties;\n const animations = [];\n const running = target.$animations || (target.$animations = {});\n const props = Object.keys(values);\n const date = Date.now();\n let i;\n for (i = props.length - 1; i >= 0; --i) {\n const prop = props[i];\n if (prop.charAt(0) === '$') {\n continue;\n }\n if (prop === 'options') {\n animations.push(...this._animateOptions(target, values));\n continue;\n }\n const value = values[prop];\n let animation = running[prop];\n const cfg = animatedProps.get(prop);\n if (animation) {\n if (cfg && animation.active()) {\n animation.update(cfg, value, date);\n continue;\n } else {\n animation.cancel();\n }\n }\n if (!cfg || !cfg.duration) {\n target[prop] = value;\n continue;\n }\n running[prop] = animation = new Animation(cfg, target, prop, value);\n animations.push(animation);\n }\n return animations;\n }\n update(target, values) {\n if (this._properties.size === 0) {\n Object.assign(target, values);\n return;\n }\n const animations = this._createAnimations(target, values);\n if (animations.length) {\n animator.add(this._chart, animations);\n return true;\n }\n }\n}\nfunction awaitAll(animations, properties) {\n const running = [];\n const keys = Object.keys(properties);\n for (let i = 0; i < keys.length; i++) {\n const anim = animations[keys[i]];\n if (anim && anim.active()) {\n running.push(anim.wait());\n }\n }\n return Promise.all(running);\n}\nfunction resolveTargetOptions(target, newOptions) {\n if (!newOptions) {\n return;\n }\n let options = target.options;\n if (!options) {\n target.options = newOptions;\n return;\n }\n if (options.$shared) {\n target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});\n }\n return options;\n}\n\nfunction scaleClip(scale, allowedOverflow) {\n const opts = scale && scale.options || {};\n const reverse = opts.reverse;\n const min = opts.min === undefined ? allowedOverflow : 0;\n const max = opts.max === undefined ? allowedOverflow : 0;\n return {\n start: reverse ? max : min,\n end: reverse ? min : max\n };\n}\nfunction defaultClip(xScale, yScale, allowedOverflow) {\n if (allowedOverflow === false) {\n return false;\n }\n const x = scaleClip(xScale, allowedOverflow);\n const y = scaleClip(yScale, allowedOverflow);\n return {\n top: y.end,\n right: x.end,\n bottom: y.start,\n left: x.start\n };\n}\nfunction toClip(value) {\n let t, r, b, l;\n if (isObject(value)) {\n t = value.top;\n r = value.right;\n b = value.bottom;\n l = value.left;\n } else {\n t = r = b = l = value;\n }\n return {\n top: t,\n right: r,\n bottom: b,\n left: l,\n disabled: value === false\n };\n}\nfunction getSortedDatasetIndices(chart, filterVisible) {\n const keys = [];\n const metasets = chart._getSortedDatasetMetas(filterVisible);\n let i, ilen;\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n keys.push(metasets[i].index);\n }\n return keys;\n}\nfunction applyStack(stack, value, dsIndex, options = {}) {\n const keys = stack.keys;\n const singleMode = options.mode === 'single';\n let i, ilen, datasetIndex, otherValue;\n if (value === null) {\n return;\n }\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n datasetIndex = +keys[i];\n if (datasetIndex === dsIndex) {\n if (options.all) {\n continue;\n }\n break;\n }\n otherValue = stack.values[datasetIndex];\n if (isNumberFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {\n value += otherValue;\n }\n }\n return value;\n}\nfunction convertObjectDataToArray(data) {\n const keys = Object.keys(data);\n const adata = new Array(keys.length);\n let i, ilen, key;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n key = keys[i];\n adata[i] = {\n x: key,\n y: data[key]\n };\n }\n return adata;\n}\nfunction isStacked(scale, meta) {\n const stacked = scale && scale.options.stacked;\n return stacked || (stacked === undefined && meta.stack !== undefined);\n}\nfunction getStackKey(indexScale, valueScale, meta) {\n return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;\n}\nfunction getUserBounds(scale) {\n const {min, max, minDefined, maxDefined} = scale.getUserBounds();\n return {\n min: minDefined ? min : Number.NEGATIVE_INFINITY,\n max: maxDefined ? max : Number.POSITIVE_INFINITY\n };\n}\nfunction getOrCreateStack(stacks, stackKey, indexValue) {\n const subStack = stacks[stackKey] || (stacks[stackKey] = {});\n return subStack[indexValue] || (subStack[indexValue] = {});\n}\nfunction getLastIndexInStack(stack, vScale, positive, type) {\n for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) {\n const value = stack[meta.index];\n if ((positive && value > 0) || (!positive && value < 0)) {\n return meta.index;\n }\n }\n return null;\n}\nfunction updateStacks(controller, parsed) {\n const {chart, _cachedMeta: meta} = controller;\n const stacks = chart._stacks || (chart._stacks = {});\n const {iScale, vScale, index: datasetIndex} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const key = getStackKey(iScale, vScale, meta);\n const ilen = parsed.length;\n let stack;\n for (let i = 0; i < ilen; ++i) {\n const item = parsed[i];\n const {[iAxis]: index, [vAxis]: value} = item;\n const itemStacks = item._stacks || (item._stacks = {});\n stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);\n stack[datasetIndex] = value;\n stack._top = getLastIndexInStack(stack, vScale, true, meta.type);\n stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);\n }\n}\nfunction getFirstScaleId(chart, axis) {\n const scales = chart.scales;\n return Object.keys(scales).filter(key => scales[key].axis === axis).shift();\n}\nfunction createDatasetContext(parent, index) {\n return createContext(parent,\n {\n active: false,\n dataset: undefined,\n datasetIndex: index,\n index,\n mode: 'default',\n type: 'dataset'\n }\n );\n}\nfunction createDataContext(parent, index, element) {\n return createContext(parent, {\n active: false,\n dataIndex: index,\n parsed: undefined,\n raw: undefined,\n element,\n index,\n mode: 'default',\n type: 'data'\n });\n}\nfunction clearStacks(meta, items) {\n const datasetIndex = meta.controller.index;\n const axis = meta.vScale && meta.vScale.axis;\n if (!axis) {\n return;\n }\n items = items || meta._parsed;\n for (const parsed of items) {\n const stacks = parsed._stacks;\n if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {\n return;\n }\n delete stacks[axis][datasetIndex];\n }\n}\nconst isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';\nconst cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);\nconst createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked\n && {keys: getSortedDatasetIndices(chart, true), values: null};\nclass DatasetController {\n constructor(chart, datasetIndex) {\n this.chart = chart;\n this._ctx = chart.ctx;\n this.index = datasetIndex;\n this._cachedDataOpts = {};\n this._cachedMeta = this.getMeta();\n this._type = this._cachedMeta.type;\n this.options = undefined;\n this._parsing = false;\n this._data = undefined;\n this._objectData = undefined;\n this._sharedOptions = undefined;\n this._drawStart = undefined;\n this._drawCount = undefined;\n this.enableOptionSharing = false;\n this.$context = undefined;\n this._syncList = [];\n this.initialize();\n }\n initialize() {\n const meta = this._cachedMeta;\n this.configure();\n this.linkScales();\n meta._stacked = isStacked(meta.vScale, meta);\n this.addElements();\n }\n updateIndex(datasetIndex) {\n if (this.index !== datasetIndex) {\n clearStacks(this._cachedMeta);\n }\n this.index = datasetIndex;\n }\n linkScales() {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;\n const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));\n const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));\n const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));\n const indexAxis = meta.indexAxis;\n const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);\n const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);\n meta.xScale = this.getScaleForId(xid);\n meta.yScale = this.getScaleForId(yid);\n meta.rScale = this.getScaleForId(rid);\n meta.iScale = this.getScaleForId(iid);\n meta.vScale = this.getScaleForId(vid);\n }\n getDataset() {\n return this.chart.data.datasets[this.index];\n }\n getMeta() {\n return this.chart.getDatasetMeta(this.index);\n }\n getScaleForId(scaleID) {\n return this.chart.scales[scaleID];\n }\n _getOtherScale(scale) {\n const meta = this._cachedMeta;\n return scale === meta.iScale\n ? meta.vScale\n : meta.iScale;\n }\n reset() {\n this._update('reset');\n }\n _destroy() {\n const meta = this._cachedMeta;\n if (this._data) {\n unlistenArrayEvents(this._data, this);\n }\n if (meta._stacked) {\n clearStacks(meta);\n }\n }\n _dataCheck() {\n const dataset = this.getDataset();\n const data = dataset.data || (dataset.data = []);\n const _data = this._data;\n if (isObject(data)) {\n this._data = convertObjectDataToArray(data);\n } else if (_data !== data) {\n if (_data) {\n unlistenArrayEvents(_data, this);\n const meta = this._cachedMeta;\n clearStacks(meta);\n meta._parsed = [];\n }\n if (data && Object.isExtensible(data)) {\n listenArrayEvents(data, this);\n }\n this._syncList = [];\n this._data = data;\n }\n }\n addElements() {\n const meta = this._cachedMeta;\n this._dataCheck();\n if (this.datasetElementType) {\n meta.dataset = new this.datasetElementType();\n }\n }\n buildOrUpdateElements(resetNewElements) {\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n let stackChanged = false;\n this._dataCheck();\n const oldStacked = meta._stacked;\n meta._stacked = isStacked(meta.vScale, meta);\n if (meta.stack !== dataset.stack) {\n stackChanged = true;\n clearStacks(meta);\n meta.stack = dataset.stack;\n }\n this._resyncElements(resetNewElements);\n if (stackChanged || oldStacked !== meta._stacked) {\n updateStacks(this, meta._parsed);\n }\n }\n configure() {\n const config = this.chart.config;\n const scopeKeys = config.datasetScopeKeys(this._type);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);\n this.options = config.createResolver(scopes, this.getContext());\n this._parsing = this.options.parsing;\n this._cachedDataOpts = {};\n }\n parse(start, count) {\n const {_cachedMeta: meta, _data: data} = this;\n const {iScale, _stacked} = meta;\n const iAxis = iScale.axis;\n let sorted = start === 0 && count === data.length ? true : meta._sorted;\n let prev = start > 0 && meta._parsed[start - 1];\n let i, cur, parsed;\n if (this._parsing === false) {\n meta._parsed = data;\n meta._sorted = true;\n parsed = data;\n } else {\n if (isArray(data[start])) {\n parsed = this.parseArrayData(meta, data, start, count);\n } else if (isObject(data[start])) {\n parsed = this.parseObjectData(meta, data, start, count);\n } else {\n parsed = this.parsePrimitiveData(meta, data, start, count);\n }\n const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);\n for (i = 0; i < count; ++i) {\n meta._parsed[i + start] = cur = parsed[i];\n if (sorted) {\n if (isNotInOrderComparedToPrev()) {\n sorted = false;\n }\n prev = cur;\n }\n }\n meta._sorted = sorted;\n }\n if (_stacked) {\n updateStacks(this, parsed);\n }\n }\n parsePrimitiveData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = new Array(count);\n let i, ilen, index;\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n parsed[i] = {\n [iAxis]: singleScale || iScale.parse(labels[index], index),\n [vAxis]: vScale.parse(data[index], index)\n };\n }\n return parsed;\n }\n parseArrayData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const parsed = new Array(count);\n let i, ilen, index, item;\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(item[0], index),\n y: yScale.parse(item[1], index)\n };\n }\n return parsed;\n }\n parseObjectData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const parsed = new Array(count);\n let i, ilen, index, item;\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(resolveObjectKey(item, xAxisKey), index),\n y: yScale.parse(resolveObjectKey(item, yAxisKey), index)\n };\n }\n return parsed;\n }\n getParsed(index) {\n return this._cachedMeta._parsed[index];\n }\n getDataElement(index) {\n return this._cachedMeta.data[index];\n }\n applyStack(scale, parsed, mode) {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const value = parsed[scale.axis];\n const stack = {\n keys: getSortedDatasetIndices(chart, true),\n values: parsed._stacks[scale.axis]\n };\n return applyStack(stack, value, meta.index, {mode});\n }\n updateRangeFromParsed(range, scale, parsed, stack) {\n const parsedValue = parsed[scale.axis];\n let value = parsedValue === null ? NaN : parsedValue;\n const values = stack && parsed._stacks[scale.axis];\n if (stack && values) {\n stack.values = values;\n value = applyStack(stack, parsedValue, this._cachedMeta.index);\n }\n range.min = Math.min(range.min, value);\n range.max = Math.max(range.max, value);\n }\n getMinMax(scale, canStack) {\n const meta = this._cachedMeta;\n const _parsed = meta._parsed;\n const sorted = meta._sorted && scale === meta.iScale;\n const ilen = _parsed.length;\n const otherScale = this._getOtherScale(scale);\n const stack = createStack(canStack, meta, this.chart);\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n const {min: otherMin, max: otherMax} = getUserBounds(otherScale);\n let i, parsed;\n function _skip() {\n parsed = _parsed[i];\n const otherValue = parsed[otherScale.axis];\n return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;\n }\n for (i = 0; i < ilen; ++i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n if (sorted) {\n break;\n }\n }\n if (sorted) {\n for (i = ilen - 1; i >= 0; --i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n break;\n }\n }\n return range;\n }\n getAllParsedValues(scale) {\n const parsed = this._cachedMeta._parsed;\n const values = [];\n let i, ilen, value;\n for (i = 0, ilen = parsed.length; i < ilen; ++i) {\n value = parsed[i][scale.axis];\n if (isNumberFinite(value)) {\n values.push(value);\n }\n }\n return values;\n }\n getMaxOverflow() {\n return false;\n }\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const parsed = this.getParsed(index);\n return {\n label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',\n value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''\n };\n }\n _update(mode) {\n const meta = this._cachedMeta;\n this.update(mode || 'default');\n meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));\n }\n update(mode) {}\n draw() {\n const ctx = this._ctx;\n const chart = this.chart;\n const meta = this._cachedMeta;\n const elements = meta.data || [];\n const area = chart.chartArea;\n const active = [];\n const start = this._drawStart || 0;\n const count = this._drawCount || (elements.length - start);\n const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;\n let i;\n if (meta.dataset) {\n meta.dataset.draw(ctx, area, start, count);\n }\n for (i = start; i < start + count; ++i) {\n const element = elements[i];\n if (element.hidden) {\n continue;\n }\n if (element.active && drawActiveElementsOnTop) {\n active.push(element);\n } else {\n element.draw(ctx, area);\n }\n }\n for (i = 0; i < active.length; ++i) {\n active[i].draw(ctx, area);\n }\n }\n getStyle(index, active) {\n const mode = active ? 'active' : 'default';\n return index === undefined && this._cachedMeta.dataset\n ? this.resolveDatasetElementOptions(mode)\n : this.resolveDataElementOptions(index || 0, mode);\n }\n getContext(index, active, mode) {\n const dataset = this.getDataset();\n let context;\n if (index >= 0 && index < this._cachedMeta.data.length) {\n const element = this._cachedMeta.data[index];\n context = element.$context ||\n (element.$context = createDataContext(this.getContext(), index, element));\n context.parsed = this.getParsed(index);\n context.raw = dataset.data[index];\n context.index = context.dataIndex = index;\n } else {\n context = this.$context ||\n (this.$context = createDatasetContext(this.chart.getContext(), this.index));\n context.dataset = dataset;\n context.index = context.datasetIndex = this.index;\n }\n context.active = !!active;\n context.mode = mode;\n return context;\n }\n resolveDatasetElementOptions(mode) {\n return this._resolveElementOptions(this.datasetElementType.id, mode);\n }\n resolveDataElementOptions(index, mode) {\n return this._resolveElementOptions(this.dataElementType.id, mode, index);\n }\n _resolveElementOptions(elementType, mode = 'default', index) {\n const active = mode === 'active';\n const cache = this._cachedDataOpts;\n const cacheKey = elementType + '-' + mode;\n const cached = cache[cacheKey];\n const sharing = this.enableOptionSharing && defined(index);\n if (cached) {\n return cloneIfNotShared(cached, sharing);\n }\n const config = this.chart.config;\n const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);\n const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n const names = Object.keys(defaults.elements[elementType]);\n const context = () => this.getContext(index, active);\n const values = config.resolveNamedOptions(scopes, names, context, prefixes);\n if (values.$shared) {\n values.$shared = sharing;\n cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));\n }\n return values;\n }\n _resolveAnimations(index, transition, active) {\n const chart = this.chart;\n const cache = this._cachedDataOpts;\n const cacheKey = `animation-${transition}`;\n const cached = cache[cacheKey];\n if (cached) {\n return cached;\n }\n let options;\n if (chart.options.animation !== false) {\n const config = this.chart.config;\n const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n options = config.createResolver(scopes, this.getContext(index, active, transition));\n }\n const animations = new Animations(chart, options && options.animations);\n if (options && options._cacheable) {\n cache[cacheKey] = Object.freeze(animations);\n }\n return animations;\n }\n getSharedOptions(options) {\n if (!options.$shared) {\n return;\n }\n return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));\n }\n includeOptions(mode, sharedOptions) {\n return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;\n }\n updateElement(element, index, properties, mode) {\n if (isDirectUpdateMode(mode)) {\n Object.assign(element, properties);\n } else {\n this._resolveAnimations(index, mode).update(element, properties);\n }\n }\n updateSharedOptions(sharedOptions, mode, newOptions) {\n if (sharedOptions && !isDirectUpdateMode(mode)) {\n this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);\n }\n }\n _setStyle(element, index, mode, active) {\n element.active = active;\n const options = this.getStyle(index, active);\n this._resolveAnimations(index, mode, active).update(element, {\n options: (!active && this.getSharedOptions(options)) || options\n });\n }\n removeHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', false);\n }\n setHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', true);\n }\n _removeDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n if (element) {\n this._setStyle(element, undefined, 'active', false);\n }\n }\n _setDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n if (element) {\n this._setStyle(element, undefined, 'active', true);\n }\n }\n _resyncElements(resetNewElements) {\n const data = this._data;\n const elements = this._cachedMeta.data;\n for (const [method, arg1, arg2] of this._syncList) {\n this[method](arg1, arg2);\n }\n this._syncList = [];\n const numMeta = elements.length;\n const numData = data.length;\n const count = Math.min(numData, numMeta);\n if (count) {\n this.parse(0, count);\n }\n if (numData > numMeta) {\n this._insertElements(numMeta, numData - numMeta, resetNewElements);\n } else if (numData < numMeta) {\n this._removeElements(numData, numMeta - numData);\n }\n }\n _insertElements(start, count, resetNewElements = true) {\n const meta = this._cachedMeta;\n const data = meta.data;\n const end = start + count;\n let i;\n const move = (arr) => {\n arr.length += count;\n for (i = arr.length - 1; i >= end; i--) {\n arr[i] = arr[i - count];\n }\n };\n move(data);\n for (i = start; i < end; ++i) {\n data[i] = new this.dataElementType();\n }\n if (this._parsing) {\n move(meta._parsed);\n }\n this.parse(start, count);\n if (resetNewElements) {\n this.updateElements(data, start, count, 'reset');\n }\n }\n updateElements(element, start, count, mode) {}\n _removeElements(start, count) {\n const meta = this._cachedMeta;\n if (this._parsing) {\n const removed = meta._parsed.splice(start, count);\n if (meta._stacked) {\n clearStacks(meta, removed);\n }\n }\n meta.data.splice(start, count);\n }\n _sync(args) {\n if (this._parsing) {\n this._syncList.push(args);\n } else {\n const [method, arg1, arg2] = args;\n this[method](arg1, arg2);\n }\n this.chart._dataChanges.push([this.index, ...args]);\n }\n _onDataPush() {\n const count = arguments.length;\n this._sync(['_insertElements', this.getDataset().data.length - count, count]);\n }\n _onDataPop() {\n this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]);\n }\n _onDataShift() {\n this._sync(['_removeElements', 0, 1]);\n }\n _onDataSplice(start, count) {\n if (count) {\n this._sync(['_removeElements', start, count]);\n }\n const newCount = arguments.length - 2;\n if (newCount) {\n this._sync(['_insertElements', start, newCount]);\n }\n }\n _onDataUnshift() {\n this._sync(['_insertElements', 0, arguments.length]);\n }\n}\nDatasetController.defaults = {};\nDatasetController.prototype.datasetElementType = null;\nDatasetController.prototype.dataElementType = null;\n\nfunction getAllScaleValues(scale, type) {\n if (!scale._cache.$bar) {\n const visibleMetas = scale.getMatchingVisibleMetas(type);\n let values = [];\n for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) {\n values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));\n }\n scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));\n }\n return scale._cache.$bar;\n}\nfunction computeMinSampleSize(meta) {\n const scale = meta.iScale;\n const values = getAllScaleValues(scale, meta.type);\n let min = scale._length;\n let i, ilen, curr, prev;\n const updateMinAndPrev = () => {\n if (curr === 32767 || curr === -32768) {\n return;\n }\n if (defined(prev)) {\n min = Math.min(min, Math.abs(curr - prev) || min);\n }\n prev = curr;\n };\n for (i = 0, ilen = values.length; i < ilen; ++i) {\n curr = scale.getPixelForValue(values[i]);\n updateMinAndPrev();\n }\n prev = undefined;\n for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {\n curr = scale.getPixelForTick(i);\n updateMinAndPrev();\n }\n return min;\n}\nfunction computeFitCategoryTraits(index, ruler, options, stackCount) {\n const thickness = options.barThickness;\n let size, ratio;\n if (isNullOrUndef(thickness)) {\n size = ruler.min * options.categoryPercentage;\n ratio = options.barPercentage;\n } else {\n size = thickness * stackCount;\n ratio = 1;\n }\n return {\n chunk: size / stackCount,\n ratio,\n start: ruler.pixels[index] - (size / 2)\n };\n}\nfunction computeFlexCategoryTraits(index, ruler, options, stackCount) {\n const pixels = ruler.pixels;\n const curr = pixels[index];\n let prev = index > 0 ? pixels[index - 1] : null;\n let next = index < pixels.length - 1 ? pixels[index + 1] : null;\n const percent = options.categoryPercentage;\n if (prev === null) {\n prev = curr - (next === null ? ruler.end - ruler.start : next - curr);\n }\n if (next === null) {\n next = curr + curr - prev;\n }\n const start = curr - (curr - Math.min(prev, next)) / 2 * percent;\n const size = Math.abs(next - prev) / 2 * percent;\n return {\n chunk: size / stackCount,\n ratio: options.barPercentage,\n start\n };\n}\nfunction parseFloatBar(entry, item, vScale, i) {\n const startValue = vScale.parse(entry[0], i);\n const endValue = vScale.parse(entry[1], i);\n const min = Math.min(startValue, endValue);\n const max = Math.max(startValue, endValue);\n let barStart = min;\n let barEnd = max;\n if (Math.abs(min) > Math.abs(max)) {\n barStart = max;\n barEnd = min;\n }\n item[vScale.axis] = barEnd;\n item._custom = {\n barStart,\n barEnd,\n start: startValue,\n end: endValue,\n min,\n max\n };\n}\nfunction parseValue(entry, item, vScale, i) {\n if (isArray(entry)) {\n parseFloatBar(entry, item, vScale, i);\n } else {\n item[vScale.axis] = vScale.parse(entry, i);\n }\n return item;\n}\nfunction parseArrayOrPrimitive(meta, data, start, count) {\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = [];\n let i, ilen, item, entry;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n entry = data[i];\n item = {};\n item[iScale.axis] = singleScale || iScale.parse(labels[i], i);\n parsed.push(parseValue(entry, item, vScale, i));\n }\n return parsed;\n}\nfunction isFloatBar(custom) {\n return custom && custom.barStart !== undefined && custom.barEnd !== undefined;\n}\nfunction barSign(size, vScale, actualBase) {\n if (size !== 0) {\n return sign(size);\n }\n return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);\n}\nfunction borderProps(properties) {\n let reverse, start, end, top, bottom;\n if (properties.horizontal) {\n reverse = properties.base > properties.x;\n start = 'left';\n end = 'right';\n } else {\n reverse = properties.base < properties.y;\n start = 'bottom';\n end = 'top';\n }\n if (reverse) {\n top = 'end';\n bottom = 'start';\n } else {\n top = 'start';\n bottom = 'end';\n }\n return {start, end, reverse, top, bottom};\n}\nfunction setBorderSkipped(properties, options, stack, index) {\n let edge = options.borderSkipped;\n const res = {};\n if (!edge) {\n properties.borderSkipped = res;\n return;\n }\n const {start, end, reverse, top, bottom} = borderProps(properties);\n if (edge === 'middle' && stack) {\n properties.enableBorderRadius = true;\n if ((stack._top || 0) === index) {\n edge = top;\n } else if ((stack._bottom || 0) === index) {\n edge = bottom;\n } else {\n res[parseEdge(bottom, start, end, reverse)] = true;\n edge = top;\n }\n }\n res[parseEdge(edge, start, end, reverse)] = true;\n properties.borderSkipped = res;\n}\nfunction parseEdge(edge, a, b, reverse) {\n if (reverse) {\n edge = swap(edge, a, b);\n edge = startEnd(edge, b, a);\n } else {\n edge = startEnd(edge, a, b);\n }\n return edge;\n}\nfunction swap(orig, v1, v2) {\n return orig === v1 ? v2 : orig === v2 ? v1 : orig;\n}\nfunction startEnd(v, start, end) {\n return v === 'start' ? start : v === 'end' ? end : v;\n}\nfunction setInflateAmount(properties, {inflateAmount}, ratio) {\n properties.inflateAmount = inflateAmount === 'auto'\n ? ratio === 1 ? 0.33 : 0\n : inflateAmount;\n}\nclass BarController extends DatasetController {\n parsePrimitiveData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n parseArrayData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n parseObjectData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;\n const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;\n const parsed = [];\n let i, ilen, item, obj;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n obj = data[i];\n item = {};\n item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);\n parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));\n }\n return parsed;\n }\n updateRangeFromParsed(range, scale, parsed, stack) {\n super.updateRangeFromParsed(range, scale, parsed, stack);\n const custom = parsed._custom;\n if (custom && scale === this._cachedMeta.vScale) {\n range.min = Math.min(range.min, custom.min);\n range.max = Math.max(range.max, custom.max);\n }\n }\n getMaxOverflow() {\n return 0;\n }\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const {iScale, vScale} = meta;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const value = isFloatBar(custom)\n ? '[' + custom.start + ', ' + custom.end + ']'\n : '' + vScale.getLabelForValue(parsed[vScale.axis]);\n return {\n label: '' + iScale.getLabelForValue(parsed[iScale.axis]),\n value\n };\n }\n initialize() {\n this.enableOptionSharing = true;\n super.initialize();\n const meta = this._cachedMeta;\n meta.stack = this.getDataset().stack;\n }\n update(mode) {\n const meta = this._cachedMeta;\n this.updateElements(meta.data, 0, meta.data.length, mode);\n }\n updateElements(bars, start, count, mode) {\n const reset = mode === 'reset';\n const {index, _cachedMeta: {vScale}} = this;\n const base = vScale.getBasePixel();\n const horizontal = vScale.isHorizontal();\n const ruler = this._getRuler();\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n for (let i = start; i < start + count; i++) {\n const parsed = this.getParsed(i);\n const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i);\n const ipixels = this._calculateBarIndexPixels(i, ruler);\n const stack = (parsed._stacks || {})[vScale.axis];\n const properties = {\n horizontal,\n base: vpixels.base,\n enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),\n x: horizontal ? vpixels.head : ipixels.center,\n y: horizontal ? ipixels.center : vpixels.head,\n height: horizontal ? ipixels.size : Math.abs(vpixels.size),\n width: horizontal ? Math.abs(vpixels.size) : ipixels.size\n };\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);\n }\n const options = properties.options || bars[i].options;\n setBorderSkipped(properties, options, stack, index);\n setInflateAmount(properties, options, ruler.ratio);\n this.updateElement(bars[i], i, properties, mode);\n }\n }\n _getStacks(last, dataIndex) {\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const metasets = iScale.getMatchingVisibleMetas(this._type);\n const stacked = iScale.options.stacked;\n const ilen = metasets.length;\n const stacks = [];\n let i, item;\n for (i = 0; i < ilen; ++i) {\n item = metasets[i];\n if (!item.controller.options.grouped) {\n continue;\n }\n if (typeof dataIndex !== 'undefined') {\n const val = item.controller.getParsed(dataIndex)[\n item.controller._cachedMeta.vScale.axis\n ];\n if (isNullOrUndef(val) || isNaN(val)) {\n continue;\n }\n }\n if (stacked === false || stacks.indexOf(item.stack) === -1 ||\n\t\t\t\t(stacked === undefined && item.stack === undefined)) {\n stacks.push(item.stack);\n }\n if (item.index === last) {\n break;\n }\n }\n if (!stacks.length) {\n stacks.push(undefined);\n }\n return stacks;\n }\n _getStackCount(index) {\n return this._getStacks(undefined, index).length;\n }\n _getStackIndex(datasetIndex, name, dataIndex) {\n const stacks = this._getStacks(datasetIndex, dataIndex);\n const index = (name !== undefined)\n ? stacks.indexOf(name)\n : -1;\n return (index === -1)\n ? stacks.length - 1\n : index;\n }\n _getRuler() {\n const opts = this.options;\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const pixels = [];\n let i, ilen;\n for (i = 0, ilen = meta.data.length; i < ilen; ++i) {\n pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));\n }\n const barThickness = opts.barThickness;\n const min = barThickness || computeMinSampleSize(meta);\n return {\n min,\n pixels,\n start: iScale._startPixel,\n end: iScale._endPixel,\n stackCount: this._getStackCount(),\n scale: iScale,\n grouped: opts.grouped,\n ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage\n };\n }\n _calculateBarValuePixels(index) {\n const {_cachedMeta: {vScale, _stacked}, options: {base: baseValue, minBarLength}} = this;\n const actualBase = baseValue || 0;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const floating = isFloatBar(custom);\n let value = parsed[vScale.axis];\n let start = 0;\n let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;\n let head, size;\n if (length !== value) {\n start = length - value;\n length = value;\n }\n if (floating) {\n value = custom.barStart;\n length = custom.barEnd - custom.barStart;\n if (value !== 0 && sign(value) !== sign(custom.barEnd)) {\n start = 0;\n }\n start += value;\n }\n const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;\n let base = vScale.getPixelForValue(startValue);\n if (this.chart.getDataVisibility(index)) {\n head = vScale.getPixelForValue(start + length);\n } else {\n head = base;\n }\n size = head - base;\n if (Math.abs(size) < minBarLength) {\n size = barSign(size, vScale, actualBase) * minBarLength;\n if (value === actualBase) {\n base -= size / 2;\n }\n head = base + size;\n }\n if (base === vScale.getPixelForValue(actualBase)) {\n const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;\n base += halfGrid;\n size -= halfGrid;\n }\n return {\n size,\n base,\n head,\n center: head + size / 2\n };\n }\n _calculateBarIndexPixels(index, ruler) {\n const scale = ruler.scale;\n const options = this.options;\n const skipNull = options.skipNull;\n const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);\n let center, size;\n if (ruler.grouped) {\n const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;\n const range = options.barThickness === 'flex'\n ? computeFlexCategoryTraits(index, ruler, options, stackCount)\n : computeFitCategoryTraits(index, ruler, options, stackCount);\n const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined);\n center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);\n size = Math.min(maxBarThickness, range.chunk * range.ratio);\n } else {\n center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);\n size = Math.min(maxBarThickness, ruler.min * ruler.ratio);\n }\n return {\n base: center - size / 2,\n head: center + size / 2,\n center,\n size\n };\n }\n draw() {\n const meta = this._cachedMeta;\n const vScale = meta.vScale;\n const rects = meta.data;\n const ilen = rects.length;\n let i = 0;\n for (; i < ilen; ++i) {\n if (this.getParsed(i)[vScale.axis] !== null) {\n rects[i].draw(this._ctx);\n }\n }\n }\n}\nBarController.id = 'bar';\nBarController.defaults = {\n datasetElementType: false,\n dataElementType: 'bar',\n categoryPercentage: 0.8,\n barPercentage: 0.9,\n grouped: true,\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'base', 'width', 'height']\n }\n }\n};\nBarController.overrides = {\n scales: {\n _index_: {\n type: 'category',\n offset: true,\n grid: {\n offset: true\n }\n },\n _value_: {\n type: 'linear',\n beginAtZero: true,\n }\n }\n};\n\nclass BubbleController extends DatasetController {\n initialize() {\n this.enableOptionSharing = true;\n super.initialize();\n }\n parsePrimitiveData(meta, data, start, count) {\n const parsed = super.parsePrimitiveData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;\n }\n return parsed;\n }\n parseArrayData(meta, data, start, count) {\n const parsed = super.parseArrayData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n parseObjectData(meta, data, start, count) {\n const parsed = super.parseObjectData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n getMaxOverflow() {\n const data = this._cachedMeta.data;\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n const r = parsed._custom;\n return {\n label: meta.label,\n value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'\n };\n }\n update(mode) {\n const points = this._cachedMeta.data;\n this.updateElements(points, 0, points.length, mode);\n }\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale} = this._cachedMeta;\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const parsed = !reset && this.getParsed(i);\n const properties = {};\n const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);\n const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);\n properties.skip = isNaN(iPixel) || isNaN(vPixel);\n if (includeOptions) {\n properties.options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n if (reset) {\n properties.options.radius = 0;\n }\n }\n this.updateElement(point, i, properties, mode);\n }\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n }\n resolveDataElementOptions(index, mode) {\n const parsed = this.getParsed(index);\n let values = super.resolveDataElementOptions(index, mode);\n if (values.$shared) {\n values = Object.assign({}, values, {$shared: false});\n }\n const radius = values.radius;\n if (mode !== 'active') {\n values.radius = 0;\n }\n values.radius += valueOrDefault(parsed && parsed._custom, radius);\n return values;\n }\n}\nBubbleController.id = 'bubble';\nBubbleController.defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'borderWidth', 'radius']\n }\n }\n};\nBubbleController.overrides = {\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n },\n plugins: {\n tooltip: {\n callbacks: {\n title() {\n return '';\n }\n }\n }\n }\n};\n\nfunction getRatioAndOffset(rotation, circumference, cutout) {\n let ratioX = 1;\n let ratioY = 1;\n let offsetX = 0;\n let offsetY = 0;\n if (circumference < TAU) {\n const startAngle = rotation;\n const endAngle = startAngle + circumference;\n const startX = Math.cos(startAngle);\n const startY = Math.sin(startAngle);\n const endX = Math.cos(endAngle);\n const endY = Math.sin(endAngle);\n const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);\n const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);\n const maxX = calcMax(0, startX, endX);\n const maxY = calcMax(HALF_PI, startY, endY);\n const minX = calcMin(PI, startX, endX);\n const minY = calcMin(PI + HALF_PI, startY, endY);\n ratioX = (maxX - minX) / 2;\n ratioY = (maxY - minY) / 2;\n offsetX = -(maxX + minX) / 2;\n offsetY = -(maxY + minY) / 2;\n }\n return {ratioX, ratioY, offsetX, offsetY};\n}\nclass DoughnutController extends DatasetController {\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n this.enableOptionSharing = true;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.offsetX = undefined;\n this.offsetY = undefined;\n }\n linkScales() {}\n parse(start, count) {\n const data = this.getDataset().data;\n const meta = this._cachedMeta;\n if (this._parsing === false) {\n meta._parsed = data;\n } else {\n let getter = (i) => +data[i];\n if (isObject(data[start])) {\n const {key = 'value'} = this._parsing;\n getter = (i) => +resolveObjectKey(data[i], key);\n }\n let i, ilen;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n meta._parsed[i] = getter(i);\n }\n }\n }\n _getRotation() {\n return toRadians(this.options.rotation - 90);\n }\n _getCircumference() {\n return toRadians(this.options.circumference);\n }\n _getRotationExtents() {\n let min = TAU;\n let max = -TAU;\n for (let i = 0; i < this.chart.data.datasets.length; ++i) {\n if (this.chart.isDatasetVisible(i)) {\n const controller = this.chart.getDatasetMeta(i).controller;\n const rotation = controller._getRotation();\n const circumference = controller._getCircumference();\n min = Math.min(min, rotation);\n max = Math.max(max, rotation + circumference);\n }\n }\n return {\n rotation: min,\n circumference: max - min,\n };\n }\n update(mode) {\n const chart = this.chart;\n const {chartArea} = chart;\n const meta = this._cachedMeta;\n const arcs = meta.data;\n const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;\n const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);\n const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);\n const chartWeight = this._getRingWeight(this.index);\n const {circumference, rotation} = this._getRotationExtents();\n const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);\n const maxWidth = (chartArea.width - spacing) / ratioX;\n const maxHeight = (chartArea.height - spacing) / ratioY;\n const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);\n const outerRadius = toDimension(this.options.radius, maxRadius);\n const innerRadius = Math.max(outerRadius * cutout, 0);\n const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();\n this.offsetX = offsetX * outerRadius;\n this.offsetY = offsetY * outerRadius;\n meta.total = this.calculateTotal();\n this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);\n this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n _circumference(i, reset) {\n const opts = this.options;\n const meta = this._cachedMeta;\n const circumference = this._getCircumference();\n if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {\n return 0;\n }\n return this.calculateCircumference(meta._parsed[i] * circumference / TAU);\n }\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const centerX = (chartArea.left + chartArea.right) / 2;\n const centerY = (chartArea.top + chartArea.bottom) / 2;\n const animateScale = reset && animationOpts.animateScale;\n const innerRadius = animateScale ? 0 : this.innerRadius;\n const outerRadius = animateScale ? 0 : this.outerRadius;\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n let startAngle = this._getRotation();\n let i;\n for (i = 0; i < start; ++i) {\n startAngle += this._circumference(i, reset);\n }\n for (i = start; i < start + count; ++i) {\n const circumference = this._circumference(i, reset);\n const arc = arcs[i];\n const properties = {\n x: centerX + this.offsetX,\n y: centerY + this.offsetY,\n startAngle,\n endAngle: startAngle + circumference,\n circumference,\n outerRadius,\n innerRadius\n };\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);\n }\n startAngle += circumference;\n this.updateElement(arc, i, properties, mode);\n }\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n }\n calculateTotal() {\n const meta = this._cachedMeta;\n const metaData = meta.data;\n let total = 0;\n let i;\n for (i = 0; i < metaData.length; i++) {\n const value = meta._parsed[i];\n if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {\n total += Math.abs(value);\n }\n }\n return total;\n }\n calculateCircumference(value) {\n const total = this._cachedMeta.total;\n if (total > 0 && !isNaN(value)) {\n return TAU * (Math.abs(value) / total);\n }\n return 0;\n }\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index], chart.options.locale);\n return {\n label: labels[index] || '',\n value,\n };\n }\n getMaxBorderWidth(arcs) {\n let max = 0;\n const chart = this.chart;\n let i, ilen, meta, controller, options;\n if (!arcs) {\n for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {\n if (chart.isDatasetVisible(i)) {\n meta = chart.getDatasetMeta(i);\n arcs = meta.data;\n controller = meta.controller;\n break;\n }\n }\n }\n if (!arcs) {\n return 0;\n }\n for (i = 0, ilen = arcs.length; i < ilen; ++i) {\n options = controller.resolveDataElementOptions(i);\n if (options.borderAlign !== 'inner') {\n max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);\n }\n }\n return max;\n }\n getMaxOffset(arcs) {\n let max = 0;\n for (let i = 0, ilen = arcs.length; i < ilen; ++i) {\n const options = this.resolveDataElementOptions(i);\n max = Math.max(max, options.offset || 0, options.hoverOffset || 0);\n }\n return max;\n }\n _getRingWeightOffset(datasetIndex) {\n let ringWeightOffset = 0;\n for (let i = 0; i < datasetIndex; ++i) {\n if (this.chart.isDatasetVisible(i)) {\n ringWeightOffset += this._getRingWeight(i);\n }\n }\n return ringWeightOffset;\n }\n _getRingWeight(datasetIndex) {\n return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);\n }\n _getVisibleDatasetWeightTotal() {\n return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;\n }\n}\nDoughnutController.id = 'doughnut';\nDoughnutController.defaults = {\n datasetElementType: false,\n dataElementType: 'arc',\n animation: {\n animateRotate: true,\n animateScale: false\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']\n },\n },\n cutout: '50%',\n rotation: 0,\n circumference: 360,\n radius: '100%',\n spacing: 0,\n indexAxis: 'r',\n};\nDoughnutController.descriptors = {\n _scriptable: (name) => name !== 'spacing',\n _indexable: (name) => name !== 'spacing',\n};\nDoughnutController.overrides = {\n aspectRatio: 1,\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle}} = chart.legend.options;\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n index: i\n };\n });\n }\n return [];\n }\n },\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n },\n tooltip: {\n callbacks: {\n title() {\n return '';\n },\n label(tooltipItem) {\n let dataLabel = tooltipItem.label;\n const value = ': ' + tooltipItem.formattedValue;\n if (isArray(dataLabel)) {\n dataLabel = dataLabel.slice();\n dataLabel[0] += value;\n } else {\n dataLabel += value;\n }\n return dataLabel;\n }\n }\n }\n }\n};\n\nclass LineController extends DatasetController {\n initialize() {\n this.enableOptionSharing = true;\n super.initialize();\n }\n update(mode) {\n const meta = this._cachedMeta;\n const {dataset: line, data: points = [], _dataset} = meta;\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n this._drawStart = start;\n this._drawCount = count;\n if (scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n this.updateElements(points, start, count, mode);\n }\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n let prevParsed = start > 0 && this.getParsed(start - 1);\n for (let i = start; i < start + count; ++i) {\n const point = points[i];\n const parsed = this.getParsed(i);\n const properties = directUpdate ? point : {};\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n prevParsed = parsed;\n }\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n }\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n const data = meta.data || [];\n if (!data.length) {\n return border;\n }\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n draw() {\n const meta = this._cachedMeta;\n meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);\n super.draw();\n }\n}\nLineController.id = 'line';\nLineController.defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n showLine: true,\n spanGaps: false,\n};\nLineController.overrides = {\n scales: {\n _index_: {\n type: 'category',\n },\n _value_: {\n type: 'linear',\n },\n }\n};\nfunction getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {\n const pointCount = points.length;\n let start = 0;\n let count = pointCount;\n if (meta._sorted) {\n const {iScale, _parsed} = meta;\n const axis = iScale.axis;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n if (minDefined) {\n start = _limitValue(Math.min(\n _lookupByKey(_parsed, iScale.axis, min).lo,\n animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo),\n 0, pointCount - 1);\n }\n if (maxDefined) {\n count = _limitValue(Math.max(\n _lookupByKey(_parsed, iScale.axis, max).hi + 1,\n animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max)).hi + 1),\n start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n }\n return {start, count};\n}\nfunction scaleRangesChanged(meta) {\n const {xScale, yScale, _scaleRanges} = meta;\n const newRanges = {\n xmin: xScale.min,\n xmax: xScale.max,\n ymin: yScale.min,\n ymax: yScale.max\n };\n if (!_scaleRanges) {\n meta._scaleRanges = newRanges;\n return true;\n }\n const changed = _scaleRanges.xmin !== xScale.min\n\t\t|| _scaleRanges.xmax !== xScale.max\n\t\t|| _scaleRanges.ymin !== yScale.min\n\t\t|| _scaleRanges.ymax !== yScale.max;\n Object.assign(_scaleRanges, newRanges);\n return changed;\n}\n\nclass PolarAreaController extends DatasetController {\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n }\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index].r, chart.options.locale);\n return {\n label: labels[index] || '',\n value,\n };\n }\n update(mode) {\n const arcs = this._cachedMeta.data;\n this._updateRadius();\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n _updateRadius() {\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);\n const outerRadius = Math.max(minSize / 2, 0);\n const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);\n const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();\n this.outerRadius = outerRadius - (radiusLength * this.index);\n this.innerRadius = this.outerRadius - radiusLength;\n }\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const dataset = this.getDataset();\n const opts = chart.options;\n const animationOpts = opts.animation;\n const scale = this._cachedMeta.rScale;\n const centerX = scale.xCenter;\n const centerY = scale.yCenter;\n const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;\n let angle = datasetStartAngle;\n let i;\n const defaultAngle = 360 / this.countVisibleElements();\n for (i = 0; i < start; ++i) {\n angle += this._computeAngle(i, mode, defaultAngle);\n }\n for (i = start; i < start + count; i++) {\n const arc = arcs[i];\n let startAngle = angle;\n let endAngle = angle + this._computeAngle(i, mode, defaultAngle);\n let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0;\n angle = endAngle;\n if (reset) {\n if (animationOpts.animateScale) {\n outerRadius = 0;\n }\n if (animationOpts.animateRotate) {\n startAngle = endAngle = datasetStartAngle;\n }\n }\n const properties = {\n x: centerX,\n y: centerY,\n innerRadius: 0,\n outerRadius,\n startAngle,\n endAngle,\n options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)\n };\n this.updateElement(arc, i, properties, mode);\n }\n }\n countVisibleElements() {\n const dataset = this.getDataset();\n const meta = this._cachedMeta;\n let count = 0;\n meta.data.forEach((element, index) => {\n if (!isNaN(dataset.data[index]) && this.chart.getDataVisibility(index)) {\n count++;\n }\n });\n return count;\n }\n _computeAngle(index, mode, defaultAngle) {\n return this.chart.getDataVisibility(index)\n ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)\n : 0;\n }\n}\nPolarAreaController.id = 'polarArea';\nPolarAreaController.defaults = {\n dataElementType: 'arc',\n animation: {\n animateRotate: true,\n animateScale: true\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']\n },\n },\n indexAxis: 'r',\n startAngle: 0,\n};\nPolarAreaController.overrides = {\n aspectRatio: 1,\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle}} = chart.legend.options;\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n index: i\n };\n });\n }\n return [];\n }\n },\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n },\n tooltip: {\n callbacks: {\n title() {\n return '';\n },\n label(context) {\n return context.chart.data.labels[context.dataIndex] + ': ' + context.formattedValue;\n }\n }\n }\n },\n scales: {\n r: {\n type: 'radialLinear',\n angleLines: {\n display: false\n },\n beginAtZero: true,\n grid: {\n circular: true\n },\n pointLabels: {\n display: false\n },\n startAngle: 0\n }\n }\n};\n\nclass PieController extends DoughnutController {\n}\nPieController.id = 'pie';\nPieController.defaults = {\n cutout: 0,\n rotation: 0,\n circumference: 360,\n radius: '100%'\n};\n\nclass RadarController extends DatasetController {\n getLabelAndValue(index) {\n const vScale = this._cachedMeta.vScale;\n const parsed = this.getParsed(index);\n return {\n label: vScale.getLabels()[index],\n value: '' + vScale.getLabelForValue(parsed[vScale.axis])\n };\n }\n update(mode) {\n const meta = this._cachedMeta;\n const line = meta.dataset;\n const points = meta.data || [];\n const labels = meta.iScale.getLabels();\n line.points = points;\n if (mode !== 'resize') {\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n const properties = {\n _loop: true,\n _fullLoop: labels.length === points.length,\n options\n };\n this.updateElement(line, undefined, properties, mode);\n }\n this.updateElements(points, 0, points.length, mode);\n }\n updateElements(points, start, count, mode) {\n const dataset = this.getDataset();\n const scale = this._cachedMeta.rScale;\n const reset = mode === 'reset';\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n const pointPosition = scale.getPointPositionForValue(i, dataset.data[i]);\n const x = reset ? scale.xCenter : pointPosition.x;\n const y = reset ? scale.yCenter : pointPosition.y;\n const properties = {\n x,\n y,\n angle: pointPosition.angle,\n skip: isNaN(x) || isNaN(y),\n options\n };\n this.updateElement(point, i, properties, mode);\n }\n }\n}\nRadarController.id = 'radar';\nRadarController.defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n indexAxis: 'r',\n showLine: true,\n elements: {\n line: {\n fill: 'start'\n }\n },\n};\nRadarController.overrides = {\n aspectRatio: 1,\n scales: {\n r: {\n type: 'radialLinear',\n }\n }\n};\n\nclass ScatterController extends LineController {\n}\nScatterController.id = 'scatter';\nScatterController.defaults = {\n showLine: false,\n fill: false\n};\nScatterController.overrides = {\n interaction: {\n mode: 'point'\n },\n plugins: {\n tooltip: {\n callbacks: {\n title() {\n return '';\n },\n label(item) {\n return '(' + item.label + ', ' + item.formattedValue + ')';\n }\n }\n }\n },\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n};\n\nvar controllers = /*#__PURE__*/Object.freeze({\n__proto__: null,\nBarController: BarController,\nBubbleController: BubbleController,\nDoughnutController: DoughnutController,\nLineController: LineController,\nPolarAreaController: PolarAreaController,\nPieController: PieController,\nRadarController: RadarController,\nScatterController: ScatterController\n});\n\nfunction abstract() {\n throw new Error('This method is not implemented: Check that a complete date adapter is provided.');\n}\nclass DateAdapter {\n constructor(options) {\n this.options = options || {};\n }\n formats() {\n return abstract();\n }\n parse(value, format) {\n return abstract();\n }\n format(timestamp, format) {\n return abstract();\n }\n add(timestamp, amount, unit) {\n return abstract();\n }\n diff(a, b, unit) {\n return abstract();\n }\n startOf(timestamp, unit, weekday) {\n return abstract();\n }\n endOf(timestamp, unit) {\n return abstract();\n }\n}\nDateAdapter.override = function(members) {\n Object.assign(DateAdapter.prototype, members);\n};\nvar adapters = {\n _date: DateAdapter\n};\n\nfunction getRelativePosition(e, chart) {\n if ('native' in e) {\n return {\n x: e.x,\n y: e.y\n };\n }\n return getRelativePosition$1(e, chart);\n}\nfunction evaluateAllVisibleItems(chart, handler) {\n const metasets = chart.getSortedVisibleDatasetMetas();\n let index, data, element;\n for (let i = 0, ilen = metasets.length; i < ilen; ++i) {\n ({index, data} = metasets[i]);\n for (let j = 0, jlen = data.length; j < jlen; ++j) {\n element = data[j];\n if (!element.skip) {\n handler(element, index, j);\n }\n }\n }\n}\nfunction binarySearch(metaset, axis, value, intersect) {\n const {controller, data, _sorted} = metaset;\n const iScale = controller._cachedMeta.iScale;\n if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {\n const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;\n if (!intersect) {\n return lookupMethod(data, axis, value);\n } else if (controller._sharedOptions) {\n const el = data[0];\n const range = typeof el.getRange === 'function' && el.getRange(axis);\n if (range) {\n const start = lookupMethod(data, axis, value - range);\n const end = lookupMethod(data, axis, value + range);\n return {lo: start.lo, hi: end.hi};\n }\n }\n }\n return {lo: 0, hi: data.length - 1};\n}\nfunction optimizedEvaluateItems(chart, axis, position, handler, intersect) {\n const metasets = chart.getSortedVisibleDatasetMetas();\n const value = position[axis];\n for (let i = 0, ilen = metasets.length; i < ilen; ++i) {\n const {index, data} = metasets[i];\n const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);\n for (let j = lo; j <= hi; ++j) {\n const element = data[j];\n if (!element.skip) {\n handler(element, index, j);\n }\n }\n }\n}\nfunction getDistanceMetricForAxis(axis) {\n const useX = axis.indexOf('x') !== -1;\n const useY = axis.indexOf('y') !== -1;\n return function(pt1, pt2) {\n const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;\n const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;\n return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));\n };\n}\nfunction getIntersectItems(chart, position, axis, useFinalPosition) {\n const items = [];\n if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {\n return items;\n }\n const evaluationFunc = function(element, datasetIndex, index) {\n if (element.inRange(position.x, position.y, useFinalPosition)) {\n items.push({element, datasetIndex, index});\n }\n };\n optimizedEvaluateItems(chart, axis, position, evaluationFunc, true);\n return items;\n}\nfunction getNearestRadialItems(chart, position, axis, useFinalPosition) {\n let items = [];\n function evaluationFunc(element, datasetIndex, index) {\n const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition);\n const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y});\n if (_angleBetween(angle, startAngle, endAngle)) {\n items.push({element, datasetIndex, index});\n }\n }\n optimizedEvaluateItems(chart, axis, position, evaluationFunc);\n return items;\n}\nfunction getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition) {\n let items = [];\n const distanceMetric = getDistanceMetricForAxis(axis);\n let minDistance = Number.POSITIVE_INFINITY;\n function evaluationFunc(element, datasetIndex, index) {\n const inRange = element.inRange(position.x, position.y, useFinalPosition);\n if (intersect && !inRange) {\n return;\n }\n const center = element.getCenterPoint(useFinalPosition);\n const pointInArea = _isPointInArea(center, chart.chartArea, chart._minPadding);\n if (!pointInArea && !inRange) {\n return;\n }\n const distance = distanceMetric(position, center);\n if (distance < minDistance) {\n items = [{element, datasetIndex, index}];\n minDistance = distance;\n } else if (distance === minDistance) {\n items.push({element, datasetIndex, index});\n }\n }\n optimizedEvaluateItems(chart, axis, position, evaluationFunc);\n return items;\n}\nfunction getNearestItems(chart, position, axis, intersect, useFinalPosition) {\n if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {\n return [];\n }\n return axis === 'r' && !intersect\n ? getNearestRadialItems(chart, position, axis, useFinalPosition)\n : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition);\n}\nfunction getAxisItems(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const items = [];\n const axis = options.axis;\n const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';\n let intersectsItem = false;\n evaluateAllVisibleItems(chart, (element, datasetIndex, index) => {\n if (element[rangeMethod](position[axis], useFinalPosition)) {\n items.push({element, datasetIndex, index});\n }\n if (element.inRange(position.x, position.y, useFinalPosition)) {\n intersectsItem = true;\n }\n });\n if (options.intersect && !intersectsItem) {\n return [];\n }\n return items;\n}\nvar Interaction = {\n modes: {\n index(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'x';\n const items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition)\n : getNearestItems(chart, position, axis, false, useFinalPosition);\n const elements = [];\n if (!items.length) {\n return [];\n }\n chart.getSortedVisibleDatasetMetas().forEach((meta) => {\n const index = items[0].index;\n const element = meta.data[index];\n if (element && !element.skip) {\n elements.push({element, datasetIndex: meta.index, index});\n }\n });\n return elements;\n },\n dataset(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n let items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition) :\n getNearestItems(chart, position, axis, false, useFinalPosition);\n if (items.length > 0) {\n const datasetIndex = items[0].datasetIndex;\n const data = chart.getDatasetMeta(datasetIndex).data;\n items = [];\n for (let i = 0; i < data.length; ++i) {\n items.push({element: data[i], datasetIndex, index: i});\n }\n }\n return items;\n },\n point(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n return getIntersectItems(chart, position, axis, useFinalPosition);\n },\n nearest(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n return getNearestItems(chart, position, axis, options.intersect, useFinalPosition);\n },\n x(chart, e, options, useFinalPosition) {\n return getAxisItems(chart, e, {axis: 'x', intersect: options.intersect}, useFinalPosition);\n },\n y(chart, e, options, useFinalPosition) {\n return getAxisItems(chart, e, {axis: 'y', intersect: options.intersect}, useFinalPosition);\n }\n }\n};\n\nconst STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];\nfunction filterByPosition(array, position) {\n return array.filter(v => v.pos === position);\n}\nfunction filterDynamicPositionByAxis(array, axis) {\n return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);\n}\nfunction sortByWeight(array, reverse) {\n return array.sort((a, b) => {\n const v0 = reverse ? b : a;\n const v1 = reverse ? a : b;\n return v0.weight === v1.weight ?\n v0.index - v1.index :\n v0.weight - v1.weight;\n });\n}\nfunction wrapBoxes(boxes) {\n const layoutBoxes = [];\n let i, ilen, box, pos, stack, stackWeight;\n for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {\n box = boxes[i];\n ({position: pos, options: {stack, stackWeight = 1}} = box);\n layoutBoxes.push({\n index: i,\n box,\n pos,\n horizontal: box.isHorizontal(),\n weight: box.weight,\n stack: stack && (pos + stack),\n stackWeight\n });\n }\n return layoutBoxes;\n}\nfunction buildStacks(layouts) {\n const stacks = {};\n for (const wrap of layouts) {\n const {stack, pos, stackWeight} = wrap;\n if (!stack || !STATIC_POSITIONS.includes(pos)) {\n continue;\n }\n const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0});\n _stack.count++;\n _stack.weight += stackWeight;\n }\n return stacks;\n}\nfunction setLayoutDims(layouts, params) {\n const stacks = buildStacks(layouts);\n const {vBoxMaxWidth, hBoxMaxHeight} = params;\n let i, ilen, layout;\n for (i = 0, ilen = layouts.length; i < ilen; ++i) {\n layout = layouts[i];\n const {fullSize} = layout.box;\n const stack = stacks[layout.stack];\n const factor = stack && layout.stackWeight / stack.weight;\n if (layout.horizontal) {\n layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;\n layout.height = hBoxMaxHeight;\n } else {\n layout.width = vBoxMaxWidth;\n layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;\n }\n }\n return stacks;\n}\nfunction buildLayoutBoxes(boxes) {\n const layoutBoxes = wrapBoxes(boxes);\n const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);\n const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);\n const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));\n const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);\n const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));\n const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');\n const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');\n return {\n fullSize,\n leftAndTop: left.concat(top),\n rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),\n chartArea: filterByPosition(layoutBoxes, 'chartArea'),\n vertical: left.concat(right).concat(centerVertical),\n horizontal: top.concat(bottom).concat(centerHorizontal)\n };\n}\nfunction getCombinedMax(maxPadding, chartArea, a, b) {\n return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);\n}\nfunction updateMaxPadding(maxPadding, boxPadding) {\n maxPadding.top = Math.max(maxPadding.top, boxPadding.top);\n maxPadding.left = Math.max(maxPadding.left, boxPadding.left);\n maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);\n maxPadding.right = Math.max(maxPadding.right, boxPadding.right);\n}\nfunction updateDims(chartArea, params, layout, stacks) {\n const {pos, box} = layout;\n const maxPadding = chartArea.maxPadding;\n if (!isObject(pos)) {\n if (layout.size) {\n chartArea[pos] -= layout.size;\n }\n const stack = stacks[layout.stack] || {size: 0, count: 1};\n stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);\n layout.size = stack.size / stack.count;\n chartArea[pos] += layout.size;\n }\n if (box.getPadding) {\n updateMaxPadding(maxPadding, box.getPadding());\n }\n const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));\n const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));\n const widthChanged = newWidth !== chartArea.w;\n const heightChanged = newHeight !== chartArea.h;\n chartArea.w = newWidth;\n chartArea.h = newHeight;\n return layout.horizontal\n ? {same: widthChanged, other: heightChanged}\n : {same: heightChanged, other: widthChanged};\n}\nfunction handleMaxPadding(chartArea) {\n const maxPadding = chartArea.maxPadding;\n function updatePos(pos) {\n const change = Math.max(maxPadding[pos] - chartArea[pos], 0);\n chartArea[pos] += change;\n return change;\n }\n chartArea.y += updatePos('top');\n chartArea.x += updatePos('left');\n updatePos('right');\n updatePos('bottom');\n}\nfunction getMargins(horizontal, chartArea) {\n const maxPadding = chartArea.maxPadding;\n function marginForPositions(positions) {\n const margin = {left: 0, top: 0, right: 0, bottom: 0};\n positions.forEach((pos) => {\n margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);\n });\n return margin;\n }\n return horizontal\n ? marginForPositions(['left', 'right'])\n : marginForPositions(['top', 'bottom']);\n}\nfunction fitBoxes(boxes, chartArea, params, stacks) {\n const refitBoxes = [];\n let i, ilen, layout, box, refit, changed;\n for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {\n layout = boxes[i];\n box = layout.box;\n box.update(\n layout.width || chartArea.w,\n layout.height || chartArea.h,\n getMargins(layout.horizontal, chartArea)\n );\n const {same, other} = updateDims(chartArea, params, layout, stacks);\n refit |= same && refitBoxes.length;\n changed = changed || other;\n if (!box.fullSize) {\n refitBoxes.push(layout);\n }\n }\n return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;\n}\nfunction setBoxDims(box, left, top, width, height) {\n box.top = top;\n box.left = left;\n box.right = left + width;\n box.bottom = top + height;\n box.width = width;\n box.height = height;\n}\nfunction placeBoxes(boxes, chartArea, params, stacks) {\n const userPadding = params.padding;\n let {x, y} = chartArea;\n for (const layout of boxes) {\n const box = layout.box;\n const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1};\n const weight = (layout.stackWeight / stack.weight) || 1;\n if (layout.horizontal) {\n const width = chartArea.w * weight;\n const height = stack.size || box.height;\n if (defined(stack.start)) {\n y = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);\n } else {\n setBoxDims(box, chartArea.left + stack.placed, y, width, height);\n }\n stack.start = y;\n stack.placed += width;\n y = box.bottom;\n } else {\n const height = chartArea.h * weight;\n const width = stack.size || box.width;\n if (defined(stack.start)) {\n x = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);\n } else {\n setBoxDims(box, x, chartArea.top + stack.placed, width, height);\n }\n stack.start = x;\n stack.placed += height;\n x = box.right;\n }\n }\n chartArea.x = x;\n chartArea.y = y;\n}\ndefaults.set('layout', {\n autoPadding: true,\n padding: {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n }\n});\nvar layouts = {\n addBox(chart, item) {\n if (!chart.boxes) {\n chart.boxes = [];\n }\n item.fullSize = item.fullSize || false;\n item.position = item.position || 'top';\n item.weight = item.weight || 0;\n item._layers = item._layers || function() {\n return [{\n z: 0,\n draw(chartArea) {\n item.draw(chartArea);\n }\n }];\n };\n chart.boxes.push(item);\n },\n removeBox(chart, layoutItem) {\n const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;\n if (index !== -1) {\n chart.boxes.splice(index, 1);\n }\n },\n configure(chart, item, options) {\n item.fullSize = options.fullSize;\n item.position = options.position;\n item.weight = options.weight;\n },\n update(chart, width, height, minPadding) {\n if (!chart) {\n return;\n }\n const padding = toPadding(chart.options.layout.padding);\n const availableWidth = Math.max(width - padding.width, 0);\n const availableHeight = Math.max(height - padding.height, 0);\n const boxes = buildLayoutBoxes(chart.boxes);\n const verticalBoxes = boxes.vertical;\n const horizontalBoxes = boxes.horizontal;\n each(chart.boxes, box => {\n if (typeof box.beforeLayout === 'function') {\n box.beforeLayout();\n }\n });\n const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>\n wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;\n const params = Object.freeze({\n outerWidth: width,\n outerHeight: height,\n padding,\n availableWidth,\n availableHeight,\n vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,\n hBoxMaxHeight: availableHeight / 2\n });\n const maxPadding = Object.assign({}, padding);\n updateMaxPadding(maxPadding, toPadding(minPadding));\n const chartArea = Object.assign({\n maxPadding,\n w: availableWidth,\n h: availableHeight,\n x: padding.left,\n y: padding.top\n }, padding);\n const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);\n fitBoxes(boxes.fullSize, chartArea, params, stacks);\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n }\n handleMaxPadding(chartArea);\n placeBoxes(boxes.leftAndTop, chartArea, params, stacks);\n chartArea.x += chartArea.w;\n chartArea.y += chartArea.h;\n placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);\n chart.chartArea = {\n left: chartArea.left,\n top: chartArea.top,\n right: chartArea.left + chartArea.w,\n bottom: chartArea.top + chartArea.h,\n height: chartArea.h,\n width: chartArea.w,\n };\n each(boxes.chartArea, (layout) => {\n const box = layout.box;\n Object.assign(box, chart.chartArea);\n box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0});\n });\n }\n};\n\nclass BasePlatform {\n acquireContext(canvas, aspectRatio) {}\n releaseContext(context) {\n return false;\n }\n addEventListener(chart, type, listener) {}\n removeEventListener(chart, type, listener) {}\n getDevicePixelRatio() {\n return 1;\n }\n getMaximumSize(element, width, height, aspectRatio) {\n width = Math.max(0, width || element.width);\n height = height || element.height;\n return {\n width,\n height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)\n };\n }\n isAttached(canvas) {\n return true;\n }\n updateConfig(config) {\n }\n}\n\nclass BasicPlatform extends BasePlatform {\n acquireContext(item) {\n return item && item.getContext && item.getContext('2d') || null;\n }\n updateConfig(config) {\n config.options.animation = false;\n }\n}\n\nconst EXPANDO_KEY = '$chartjs';\nconst EVENT_TYPES = {\n touchstart: 'mousedown',\n touchmove: 'mousemove',\n touchend: 'mouseup',\n pointerenter: 'mouseenter',\n pointerdown: 'mousedown',\n pointermove: 'mousemove',\n pointerup: 'mouseup',\n pointerleave: 'mouseout',\n pointerout: 'mouseout'\n};\nconst isNullOrEmpty = value => value === null || value === '';\nfunction initCanvas(canvas, aspectRatio) {\n const style = canvas.style;\n const renderHeight = canvas.getAttribute('height');\n const renderWidth = canvas.getAttribute('width');\n canvas[EXPANDO_KEY] = {\n initial: {\n height: renderHeight,\n width: renderWidth,\n style: {\n display: style.display,\n height: style.height,\n width: style.width\n }\n }\n };\n style.display = style.display || 'block';\n style.boxSizing = style.boxSizing || 'border-box';\n if (isNullOrEmpty(renderWidth)) {\n const displayWidth = readUsedSize(canvas, 'width');\n if (displayWidth !== undefined) {\n canvas.width = displayWidth;\n }\n }\n if (isNullOrEmpty(renderHeight)) {\n if (canvas.style.height === '') {\n canvas.height = canvas.width / (aspectRatio || 2);\n } else {\n const displayHeight = readUsedSize(canvas, 'height');\n if (displayHeight !== undefined) {\n canvas.height = displayHeight;\n }\n }\n }\n return canvas;\n}\nconst eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;\nfunction addListener(node, type, listener) {\n node.addEventListener(type, listener, eventListenerOptions);\n}\nfunction removeListener(chart, type, listener) {\n chart.canvas.removeEventListener(type, listener, eventListenerOptions);\n}\nfunction fromNativeEvent(event, chart) {\n const type = EVENT_TYPES[event.type] || event.type;\n const {x, y} = getRelativePosition$1(event, chart);\n return {\n type,\n chart,\n native: event,\n x: x !== undefined ? x : null,\n y: y !== undefined ? y : null,\n };\n}\nfunction nodeListContains(nodeList, canvas) {\n for (const node of nodeList) {\n if (node === canvas || node.contains(canvas)) {\n return true;\n }\n }\n}\nfunction createAttachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.addedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.removedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\nfunction createDetachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.removedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.addedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\nconst drpListeningCharts = new Map();\nlet oldDevicePixelRatio = 0;\nfunction onWindowResize() {\n const dpr = window.devicePixelRatio;\n if (dpr === oldDevicePixelRatio) {\n return;\n }\n oldDevicePixelRatio = dpr;\n drpListeningCharts.forEach((resize, chart) => {\n if (chart.currentDevicePixelRatio !== dpr) {\n resize();\n }\n });\n}\nfunction listenDevicePixelRatioChanges(chart, resize) {\n if (!drpListeningCharts.size) {\n window.addEventListener('resize', onWindowResize);\n }\n drpListeningCharts.set(chart, resize);\n}\nfunction unlistenDevicePixelRatioChanges(chart) {\n drpListeningCharts.delete(chart);\n if (!drpListeningCharts.size) {\n window.removeEventListener('resize', onWindowResize);\n }\n}\nfunction createResizeObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n return;\n }\n const resize = throttled((width, height) => {\n const w = container.clientWidth;\n listener(width, height);\n if (w < container.clientWidth) {\n listener();\n }\n }, window);\n const observer = new ResizeObserver(entries => {\n const entry = entries[0];\n const width = entry.contentRect.width;\n const height = entry.contentRect.height;\n if (width === 0 && height === 0) {\n return;\n }\n resize(width, height);\n });\n observer.observe(container);\n listenDevicePixelRatioChanges(chart, resize);\n return observer;\n}\nfunction releaseObserver(chart, type, observer) {\n if (observer) {\n observer.disconnect();\n }\n if (type === 'resize') {\n unlistenDevicePixelRatioChanges(chart);\n }\n}\nfunction createProxyAndListen(chart, type, listener) {\n const canvas = chart.canvas;\n const proxy = throttled((event) => {\n if (chart.ctx !== null) {\n listener(fromNativeEvent(event, chart));\n }\n }, chart, (args) => {\n const event = args[0];\n return [event, event.offsetX, event.offsetY];\n });\n addListener(canvas, type, proxy);\n return proxy;\n}\nclass DomPlatform extends BasePlatform {\n acquireContext(canvas, aspectRatio) {\n const context = canvas && canvas.getContext && canvas.getContext('2d');\n if (context && context.canvas === canvas) {\n initCanvas(canvas, aspectRatio);\n return context;\n }\n return null;\n }\n releaseContext(context) {\n const canvas = context.canvas;\n if (!canvas[EXPANDO_KEY]) {\n return false;\n }\n const initial = canvas[EXPANDO_KEY].initial;\n ['height', 'width'].forEach((prop) => {\n const value = initial[prop];\n if (isNullOrUndef(value)) {\n canvas.removeAttribute(prop);\n } else {\n canvas.setAttribute(prop, value);\n }\n });\n const style = initial.style || {};\n Object.keys(style).forEach((key) => {\n canvas.style[key] = style[key];\n });\n canvas.width = canvas.width;\n delete canvas[EXPANDO_KEY];\n return true;\n }\n addEventListener(chart, type, listener) {\n this.removeEventListener(chart, type);\n const proxies = chart.$proxies || (chart.$proxies = {});\n const handlers = {\n attach: createAttachObserver,\n detach: createDetachObserver,\n resize: createResizeObserver\n };\n const handler = handlers[type] || createProxyAndListen;\n proxies[type] = handler(chart, type, listener);\n }\n removeEventListener(chart, type) {\n const proxies = chart.$proxies || (chart.$proxies = {});\n const proxy = proxies[type];\n if (!proxy) {\n return;\n }\n const handlers = {\n attach: releaseObserver,\n detach: releaseObserver,\n resize: releaseObserver\n };\n const handler = handlers[type] || removeListener;\n handler(chart, type, proxy);\n proxies[type] = undefined;\n }\n getDevicePixelRatio() {\n return window.devicePixelRatio;\n }\n getMaximumSize(canvas, width, height, aspectRatio) {\n return getMaximumSize(canvas, width, height, aspectRatio);\n }\n isAttached(canvas) {\n const container = _getParentNode(canvas);\n return !!(container && container.isConnected);\n }\n}\n\nfunction _detectPlatform(canvas) {\n if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {\n return BasicPlatform;\n }\n return DomPlatform;\n}\n\nclass Element {\n constructor() {\n this.x = undefined;\n this.y = undefined;\n this.active = false;\n this.options = undefined;\n this.$animations = undefined;\n }\n tooltipPosition(useFinalPosition) {\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return {x, y};\n }\n hasValue() {\n return isNumber(this.x) && isNumber(this.y);\n }\n getProps(props, final) {\n const anims = this.$animations;\n if (!final || !anims) {\n return this;\n }\n const ret = {};\n props.forEach(prop => {\n ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop];\n });\n return ret;\n }\n}\nElement.defaults = {};\nElement.defaultRoutes = undefined;\n\nconst formatters = {\n values(value) {\n return isArray(value) ? value : '' + value;\n },\n numeric(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0';\n }\n const locale = this.chart.options.locale;\n let notation;\n let delta = tickValue;\n if (ticks.length > 1) {\n const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));\n if (maxTick < 1e-4 || maxTick > 1e+15) {\n notation = 'scientific';\n }\n delta = calculateDelta(tickValue, ticks);\n }\n const logDelta = log10(Math.abs(delta));\n const numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);\n const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};\n Object.assign(options, this.options.ticks.format);\n return formatNumber(tickValue, locale, options);\n },\n logarithmic(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0';\n }\n const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue))));\n if (remain === 1 || remain === 2 || remain === 5) {\n return formatters.numeric.call(this, tickValue, index, ticks);\n }\n return '';\n }\n};\nfunction calculateDelta(tickValue, ticks) {\n let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;\n if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {\n delta = tickValue - Math.floor(tickValue);\n }\n return delta;\n}\nvar Ticks = {formatters};\n\ndefaults.set('scale', {\n display: true,\n offset: false,\n reverse: false,\n beginAtZero: false,\n bounds: 'ticks',\n grace: 0,\n grid: {\n display: true,\n lineWidth: 1,\n drawBorder: true,\n drawOnChartArea: true,\n drawTicks: true,\n tickLength: 8,\n tickWidth: (_ctx, options) => options.lineWidth,\n tickColor: (_ctx, options) => options.color,\n offset: false,\n borderDash: [],\n borderDashOffset: 0.0,\n borderWidth: 1\n },\n title: {\n display: false,\n text: '',\n padding: {\n top: 4,\n bottom: 4\n }\n },\n ticks: {\n minRotation: 0,\n maxRotation: 50,\n mirror: false,\n textStrokeWidth: 0,\n textStrokeColor: '',\n padding: 3,\n display: true,\n autoSkip: true,\n autoSkipPadding: 3,\n labelOffset: 0,\n callback: Ticks.formatters.values,\n minor: {},\n major: {},\n align: 'center',\n crossAlign: 'near',\n showLabelBackdrop: false,\n backdropColor: 'rgba(255, 255, 255, 0.75)',\n backdropPadding: 2,\n }\n});\ndefaults.route('scale.ticks', 'color', '', 'color');\ndefaults.route('scale.grid', 'color', '', 'borderColor');\ndefaults.route('scale.grid', 'borderColor', '', 'borderColor');\ndefaults.route('scale.title', 'color', '', 'color');\ndefaults.describe('scale', {\n _fallback: false,\n _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',\n _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash',\n});\ndefaults.describe('scales', {\n _fallback: 'scale',\n});\ndefaults.describe('scale.ticks', {\n _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback',\n _indexable: (name) => name !== 'backdropPadding',\n});\n\nfunction autoSkip(scale, ticks) {\n const tickOpts = scale.options.ticks;\n const ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale);\n const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];\n const numMajorIndices = majorIndices.length;\n const first = majorIndices[0];\n const last = majorIndices[numMajorIndices - 1];\n const newTicks = [];\n if (numMajorIndices > ticksLimit) {\n skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);\n return newTicks;\n }\n const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);\n if (numMajorIndices > 0) {\n let i, ilen;\n const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;\n skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);\n for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {\n skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);\n }\n skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);\n return newTicks;\n }\n skip(ticks, newTicks, spacing);\n return newTicks;\n}\nfunction determineMaxTicks(scale) {\n const offset = scale.options.offset;\n const tickLength = scale._tickSize();\n const maxScale = scale._length / tickLength + (offset ? 0 : 1);\n const maxChart = scale._maxLength / tickLength;\n return Math.floor(Math.min(maxScale, maxChart));\n}\nfunction calculateSpacing(majorIndices, ticks, ticksLimit) {\n const evenMajorSpacing = getEvenSpacing(majorIndices);\n const spacing = ticks.length / ticksLimit;\n if (!evenMajorSpacing) {\n return Math.max(spacing, 1);\n }\n const factors = _factorize(evenMajorSpacing);\n for (let i = 0, ilen = factors.length - 1; i < ilen; i++) {\n const factor = factors[i];\n if (factor > spacing) {\n return factor;\n }\n }\n return Math.max(spacing, 1);\n}\nfunction getMajorIndices(ticks) {\n const result = [];\n let i, ilen;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n if (ticks[i].major) {\n result.push(i);\n }\n }\n return result;\n}\nfunction skipMajors(ticks, newTicks, majorIndices, spacing) {\n let count = 0;\n let next = majorIndices[0];\n let i;\n spacing = Math.ceil(spacing);\n for (i = 0; i < ticks.length; i++) {\n if (i === next) {\n newTicks.push(ticks[i]);\n count++;\n next = majorIndices[count * spacing];\n }\n }\n}\nfunction skip(ticks, newTicks, spacing, majorStart, majorEnd) {\n const start = valueOrDefault(majorStart, 0);\n const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);\n let count = 0;\n let length, i, next;\n spacing = Math.ceil(spacing);\n if (majorEnd) {\n length = majorEnd - majorStart;\n spacing = length / Math.floor(length / spacing);\n }\n next = start;\n while (next < 0) {\n count++;\n next = Math.round(start + count * spacing);\n }\n for (i = Math.max(start, 0); i < end; i++) {\n if (i === next) {\n newTicks.push(ticks[i]);\n count++;\n next = Math.round(start + count * spacing);\n }\n }\n}\nfunction getEvenSpacing(arr) {\n const len = arr.length;\n let i, diff;\n if (len < 2) {\n return false;\n }\n for (diff = arr[0], i = 1; i < len; ++i) {\n if (arr[i] - arr[i - 1] !== diff) {\n return false;\n }\n }\n return diff;\n}\n\nconst reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align;\nconst offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;\nfunction sample(arr, numItems) {\n const result = [];\n const increment = arr.length / numItems;\n const len = arr.length;\n let i = 0;\n for (; i < len; i += increment) {\n result.push(arr[Math.floor(i)]);\n }\n return result;\n}\nfunction getPixelForGridLine(scale, index, offsetGridLines) {\n const length = scale.ticks.length;\n const validIndex = Math.min(index, length - 1);\n const start = scale._startPixel;\n const end = scale._endPixel;\n const epsilon = 1e-6;\n let lineValue = scale.getPixelForTick(validIndex);\n let offset;\n if (offsetGridLines) {\n if (length === 1) {\n offset = Math.max(lineValue - start, end - lineValue);\n } else if (index === 0) {\n offset = (scale.getPixelForTick(1) - lineValue) / 2;\n } else {\n offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;\n }\n lineValue += validIndex < index ? offset : -offset;\n if (lineValue < start - epsilon || lineValue > end + epsilon) {\n return;\n }\n }\n return lineValue;\n}\nfunction garbageCollect(caches, length) {\n each(caches, (cache) => {\n const gc = cache.gc;\n const gcLen = gc.length / 2;\n let i;\n if (gcLen > length) {\n for (i = 0; i < gcLen; ++i) {\n delete cache.data[gc[i]];\n }\n gc.splice(0, gcLen);\n }\n });\n}\nfunction getTickMarkLength(options) {\n return options.drawTicks ? options.tickLength : 0;\n}\nfunction getTitleHeight(options, fallback) {\n if (!options.display) {\n return 0;\n }\n const font = toFont(options.font, fallback);\n const padding = toPadding(options.padding);\n const lines = isArray(options.text) ? options.text.length : 1;\n return (lines * font.lineHeight) + padding.height;\n}\nfunction createScaleContext(parent, scale) {\n return createContext(parent, {\n scale,\n type: 'scale'\n });\n}\nfunction createTickContext(parent, index, tick) {\n return createContext(parent, {\n tick,\n index,\n type: 'tick'\n });\n}\nfunction titleAlign(align, position, reverse) {\n let ret = _toLeftRightCenter(align);\n if ((reverse && position !== 'right') || (!reverse && position === 'right')) {\n ret = reverseAlign(ret);\n }\n return ret;\n}\nfunction titleArgs(scale, offset, position, align) {\n const {top, left, bottom, right, chart} = scale;\n const {chartArea, scales} = chart;\n let rotation = 0;\n let maxWidth, titleX, titleY;\n const height = bottom - top;\n const width = right - left;\n if (scale.isHorizontal()) {\n titleX = _alignStartEnd(align, left, right);\n if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;\n } else if (position === 'center') {\n titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;\n } else {\n titleY = offsetFromEdge(scale, position, offset);\n }\n maxWidth = right - left;\n } else {\n if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;\n } else if (position === 'center') {\n titleX = (chartArea.left + chartArea.right) / 2 - width + offset;\n } else {\n titleX = offsetFromEdge(scale, position, offset);\n }\n titleY = _alignStartEnd(align, bottom, top);\n rotation = position === 'left' ? -HALF_PI : HALF_PI;\n }\n return {titleX, titleY, maxWidth, rotation};\n}\nclass Scale extends Element {\n constructor(cfg) {\n super();\n this.id = cfg.id;\n this.type = cfg.type;\n this.options = undefined;\n this.ctx = cfg.ctx;\n this.chart = cfg.chart;\n this.top = undefined;\n this.bottom = undefined;\n this.left = undefined;\n this.right = undefined;\n this.width = undefined;\n this.height = undefined;\n this._margins = {\n left: 0,\n right: 0,\n top: 0,\n bottom: 0\n };\n this.maxWidth = undefined;\n this.maxHeight = undefined;\n this.paddingTop = undefined;\n this.paddingBottom = undefined;\n this.paddingLeft = undefined;\n this.paddingRight = undefined;\n this.axis = undefined;\n this.labelRotation = undefined;\n this.min = undefined;\n this.max = undefined;\n this._range = undefined;\n this.ticks = [];\n this._gridLineItems = null;\n this._labelItems = null;\n this._labelSizes = null;\n this._length = 0;\n this._maxLength = 0;\n this._longestTextCache = {};\n this._startPixel = undefined;\n this._endPixel = undefined;\n this._reversePixels = false;\n this._userMax = undefined;\n this._userMin = undefined;\n this._suggestedMax = undefined;\n this._suggestedMin = undefined;\n this._ticksLength = 0;\n this._borderValue = 0;\n this._cache = {};\n this._dataLimitsCached = false;\n this.$context = undefined;\n }\n init(options) {\n this.options = options.setContext(this.getContext());\n this.axis = options.axis;\n this._userMin = this.parse(options.min);\n this._userMax = this.parse(options.max);\n this._suggestedMin = this.parse(options.suggestedMin);\n this._suggestedMax = this.parse(options.suggestedMax);\n }\n parse(raw, index) {\n return raw;\n }\n getUserBounds() {\n let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this;\n _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);\n _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);\n _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);\n _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);\n return {\n min: finiteOrDefault(_userMin, _suggestedMin),\n max: finiteOrDefault(_userMax, _suggestedMax),\n minDefined: isNumberFinite(_userMin),\n maxDefined: isNumberFinite(_userMax)\n };\n }\n getMinMax(canStack) {\n let {min, max, minDefined, maxDefined} = this.getUserBounds();\n let range;\n if (minDefined && maxDefined) {\n return {min, max};\n }\n const metas = this.getMatchingVisibleMetas();\n for (let i = 0, ilen = metas.length; i < ilen; ++i) {\n range = metas[i].controller.getMinMax(this, canStack);\n if (!minDefined) {\n min = Math.min(min, range.min);\n }\n if (!maxDefined) {\n max = Math.max(max, range.max);\n }\n }\n min = maxDefined && min > max ? max : min;\n max = minDefined && min > max ? min : max;\n return {\n min: finiteOrDefault(min, finiteOrDefault(max, min)),\n max: finiteOrDefault(max, finiteOrDefault(min, max))\n };\n }\n getPadding() {\n return {\n left: this.paddingLeft || 0,\n top: this.paddingTop || 0,\n right: this.paddingRight || 0,\n bottom: this.paddingBottom || 0\n };\n }\n getTicks() {\n return this.ticks;\n }\n getLabels() {\n const data = this.chart.data;\n return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];\n }\n beforeLayout() {\n this._cache = {};\n this._dataLimitsCached = false;\n }\n beforeUpdate() {\n callback(this.options.beforeUpdate, [this]);\n }\n update(maxWidth, maxHeight, margins) {\n const {beginAtZero, grace, ticks: tickOpts} = this.options;\n const sampleSize = tickOpts.sampleSize;\n this.beforeUpdate();\n this.maxWidth = maxWidth;\n this.maxHeight = maxHeight;\n this._margins = margins = Object.assign({\n left: 0,\n right: 0,\n top: 0,\n bottom: 0\n }, margins);\n this.ticks = null;\n this._labelSizes = null;\n this._gridLineItems = null;\n this._labelItems = null;\n this.beforeSetDimensions();\n this.setDimensions();\n this.afterSetDimensions();\n this._maxLength = this.isHorizontal()\n ? this.width + margins.left + margins.right\n : this.height + margins.top + margins.bottom;\n if (!this._dataLimitsCached) {\n this.beforeDataLimits();\n this.determineDataLimits();\n this.afterDataLimits();\n this._range = _addGrace(this, grace, beginAtZero);\n this._dataLimitsCached = true;\n }\n this.beforeBuildTicks();\n this.ticks = this.buildTicks() || [];\n this.afterBuildTicks();\n const samplingEnabled = sampleSize < this.ticks.length;\n this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);\n this.configure();\n this.beforeCalculateLabelRotation();\n this.calculateLabelRotation();\n this.afterCalculateLabelRotation();\n if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {\n this.ticks = autoSkip(this, this.ticks);\n this._labelSizes = null;\n }\n if (samplingEnabled) {\n this._convertTicksToLabels(this.ticks);\n }\n this.beforeFit();\n this.fit();\n this.afterFit();\n this.afterUpdate();\n }\n configure() {\n let reversePixels = this.options.reverse;\n let startPixel, endPixel;\n if (this.isHorizontal()) {\n startPixel = this.left;\n endPixel = this.right;\n } else {\n startPixel = this.top;\n endPixel = this.bottom;\n reversePixels = !reversePixels;\n }\n this._startPixel = startPixel;\n this._endPixel = endPixel;\n this._reversePixels = reversePixels;\n this._length = endPixel - startPixel;\n this._alignToPixels = this.options.alignToPixels;\n }\n afterUpdate() {\n callback(this.options.afterUpdate, [this]);\n }\n beforeSetDimensions() {\n callback(this.options.beforeSetDimensions, [this]);\n }\n setDimensions() {\n if (this.isHorizontal()) {\n this.width = this.maxWidth;\n this.left = 0;\n this.right = this.width;\n } else {\n this.height = this.maxHeight;\n this.top = 0;\n this.bottom = this.height;\n }\n this.paddingLeft = 0;\n this.paddingTop = 0;\n this.paddingRight = 0;\n this.paddingBottom = 0;\n }\n afterSetDimensions() {\n callback(this.options.afterSetDimensions, [this]);\n }\n _callHooks(name) {\n this.chart.notifyPlugins(name, this.getContext());\n callback(this.options[name], [this]);\n }\n beforeDataLimits() {\n this._callHooks('beforeDataLimits');\n }\n determineDataLimits() {}\n afterDataLimits() {\n this._callHooks('afterDataLimits');\n }\n beforeBuildTicks() {\n this._callHooks('beforeBuildTicks');\n }\n buildTicks() {\n return [];\n }\n afterBuildTicks() {\n this._callHooks('afterBuildTicks');\n }\n beforeTickToLabelConversion() {\n callback(this.options.beforeTickToLabelConversion, [this]);\n }\n generateTickLabels(ticks) {\n const tickOpts = this.options.ticks;\n let i, ilen, tick;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n tick = ticks[i];\n tick.label = callback(tickOpts.callback, [tick.value, i, ticks], this);\n }\n }\n afterTickToLabelConversion() {\n callback(this.options.afterTickToLabelConversion, [this]);\n }\n beforeCalculateLabelRotation() {\n callback(this.options.beforeCalculateLabelRotation, [this]);\n }\n calculateLabelRotation() {\n const options = this.options;\n const tickOpts = options.ticks;\n const numTicks = this.ticks.length;\n const minRotation = tickOpts.minRotation || 0;\n const maxRotation = tickOpts.maxRotation;\n let labelRotation = minRotation;\n let tickWidth, maxHeight, maxLabelDiagonal;\n if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {\n this.labelRotation = minRotation;\n return;\n }\n const labelSizes = this._getLabelSizes();\n const maxLabelWidth = labelSizes.widest.width;\n const maxLabelHeight = labelSizes.highest.height;\n const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);\n tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);\n if (maxLabelWidth + 6 > tickWidth) {\n tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));\n maxHeight = this.maxHeight - getTickMarkLength(options.grid)\n\t\t\t\t- tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);\n maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);\n labelRotation = toDegrees(Math.min(\n Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)),\n Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))\n ));\n labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));\n }\n this.labelRotation = labelRotation;\n }\n afterCalculateLabelRotation() {\n callback(this.options.afterCalculateLabelRotation, [this]);\n }\n beforeFit() {\n callback(this.options.beforeFit, [this]);\n }\n fit() {\n const minSize = {\n width: 0,\n height: 0\n };\n const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = this;\n const display = this._isVisible();\n const isHorizontal = this.isHorizontal();\n if (display) {\n const titleHeight = getTitleHeight(titleOpts, chart.options.font);\n if (isHorizontal) {\n minSize.width = this.maxWidth;\n minSize.height = getTickMarkLength(gridOpts) + titleHeight;\n } else {\n minSize.height = this.maxHeight;\n minSize.width = getTickMarkLength(gridOpts) + titleHeight;\n }\n if (tickOpts.display && this.ticks.length) {\n const {first, last, widest, highest} = this._getLabelSizes();\n const tickPadding = tickOpts.padding * 2;\n const angleRadians = toRadians(this.labelRotation);\n const cos = Math.cos(angleRadians);\n const sin = Math.sin(angleRadians);\n if (isHorizontal) {\n const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;\n minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);\n } else {\n const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;\n minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);\n }\n this._calculatePadding(first, last, sin, cos);\n }\n }\n this._handleMargins();\n if (isHorizontal) {\n this.width = this._length = chart.width - this._margins.left - this._margins.right;\n this.height = minSize.height;\n } else {\n this.width = minSize.width;\n this.height = this._length = chart.height - this._margins.top - this._margins.bottom;\n }\n }\n _calculatePadding(first, last, sin, cos) {\n const {ticks: {align, padding}, position} = this.options;\n const isRotated = this.labelRotation !== 0;\n const labelsBelowTicks = position !== 'top' && this.axis === 'x';\n if (this.isHorizontal()) {\n const offsetLeft = this.getPixelForTick(0) - this.left;\n const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);\n let paddingLeft = 0;\n let paddingRight = 0;\n if (isRotated) {\n if (labelsBelowTicks) {\n paddingLeft = cos * first.width;\n paddingRight = sin * last.height;\n } else {\n paddingLeft = sin * first.height;\n paddingRight = cos * last.width;\n }\n } else if (align === 'start') {\n paddingRight = last.width;\n } else if (align === 'end') {\n paddingLeft = first.width;\n } else {\n paddingLeft = first.width / 2;\n paddingRight = last.width / 2;\n }\n this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);\n this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);\n } else {\n let paddingTop = last.height / 2;\n let paddingBottom = first.height / 2;\n if (align === 'start') {\n paddingTop = 0;\n paddingBottom = first.height;\n } else if (align === 'end') {\n paddingTop = last.height;\n paddingBottom = 0;\n }\n this.paddingTop = paddingTop + padding;\n this.paddingBottom = paddingBottom + padding;\n }\n }\n _handleMargins() {\n if (this._margins) {\n this._margins.left = Math.max(this.paddingLeft, this._margins.left);\n this._margins.top = Math.max(this.paddingTop, this._margins.top);\n this._margins.right = Math.max(this.paddingRight, this._margins.right);\n this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);\n }\n }\n afterFit() {\n callback(this.options.afterFit, [this]);\n }\n isHorizontal() {\n const {axis, position} = this.options;\n return position === 'top' || position === 'bottom' || axis === 'x';\n }\n isFullSize() {\n return this.options.fullSize;\n }\n _convertTicksToLabels(ticks) {\n this.beforeTickToLabelConversion();\n this.generateTickLabels(ticks);\n let i, ilen;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n if (isNullOrUndef(ticks[i].label)) {\n ticks.splice(i, 1);\n ilen--;\n i--;\n }\n }\n this.afterTickToLabelConversion();\n }\n _getLabelSizes() {\n let labelSizes = this._labelSizes;\n if (!labelSizes) {\n const sampleSize = this.options.ticks.sampleSize;\n let ticks = this.ticks;\n if (sampleSize < ticks.length) {\n ticks = sample(ticks, sampleSize);\n }\n this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length);\n }\n return labelSizes;\n }\n _computeLabelSizes(ticks, length) {\n const {ctx, _longestTextCache: caches} = this;\n const widths = [];\n const heights = [];\n let widestLabelSize = 0;\n let highestLabelSize = 0;\n let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;\n for (i = 0; i < length; ++i) {\n label = ticks[i].label;\n tickFont = this._resolveTickFontOptions(i);\n ctx.font = fontString = tickFont.string;\n cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};\n lineHeight = tickFont.lineHeight;\n width = height = 0;\n if (!isNullOrUndef(label) && !isArray(label)) {\n width = _measureText(ctx, cache.data, cache.gc, width, label);\n height = lineHeight;\n } else if (isArray(label)) {\n for (j = 0, jlen = label.length; j < jlen; ++j) {\n nestedLabel = label[j];\n if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {\n width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);\n height += lineHeight;\n }\n }\n }\n widths.push(width);\n heights.push(height);\n widestLabelSize = Math.max(width, widestLabelSize);\n highestLabelSize = Math.max(height, highestLabelSize);\n }\n garbageCollect(caches, length);\n const widest = widths.indexOf(widestLabelSize);\n const highest = heights.indexOf(highestLabelSize);\n const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0});\n return {\n first: valueAt(0),\n last: valueAt(length - 1),\n widest: valueAt(widest),\n highest: valueAt(highest),\n widths,\n heights,\n };\n }\n getLabelForValue(value) {\n return value;\n }\n getPixelForValue(value, index) {\n return NaN;\n }\n getValueForPixel(pixel) {}\n getPixelForTick(index) {\n const ticks = this.ticks;\n if (index < 0 || index > ticks.length - 1) {\n return null;\n }\n return this.getPixelForValue(ticks[index].value);\n }\n getPixelForDecimal(decimal) {\n if (this._reversePixels) {\n decimal = 1 - decimal;\n }\n const pixel = this._startPixel + decimal * this._length;\n return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel);\n }\n getDecimalForPixel(pixel) {\n const decimal = (pixel - this._startPixel) / this._length;\n return this._reversePixels ? 1 - decimal : decimal;\n }\n getBasePixel() {\n return this.getPixelForValue(this.getBaseValue());\n }\n getBaseValue() {\n const {min, max} = this;\n return min < 0 && max < 0 ? max :\n min > 0 && max > 0 ? min :\n 0;\n }\n getContext(index) {\n const ticks = this.ticks || [];\n if (index >= 0 && index < ticks.length) {\n const tick = ticks[index];\n return tick.$context ||\n\t\t\t\t(tick.$context = createTickContext(this.getContext(), index, tick));\n }\n return this.$context ||\n\t\t\t(this.$context = createScaleContext(this.chart.getContext(), this));\n }\n _tickSize() {\n const optionTicks = this.options.ticks;\n const rot = toRadians(this.labelRotation);\n const cos = Math.abs(Math.cos(rot));\n const sin = Math.abs(Math.sin(rot));\n const labelSizes = this._getLabelSizes();\n const padding = optionTicks.autoSkipPadding || 0;\n const w = labelSizes ? labelSizes.widest.width + padding : 0;\n const h = labelSizes ? labelSizes.highest.height + padding : 0;\n return this.isHorizontal()\n ? h * cos > w * sin ? w / cos : h / sin\n : h * sin < w * cos ? h / cos : w / sin;\n }\n _isVisible() {\n const display = this.options.display;\n if (display !== 'auto') {\n return !!display;\n }\n return this.getMatchingVisibleMetas().length > 0;\n }\n _computeGridLineItems(chartArea) {\n const axis = this.axis;\n const chart = this.chart;\n const options = this.options;\n const {grid, position} = options;\n const offset = grid.offset;\n const isHorizontal = this.isHorizontal();\n const ticks = this.ticks;\n const ticksLength = ticks.length + (offset ? 1 : 0);\n const tl = getTickMarkLength(grid);\n const items = [];\n const borderOpts = grid.setContext(this.getContext());\n const axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0;\n const axisHalfWidth = axisWidth / 2;\n const alignBorderValue = function(pixel) {\n return _alignPixel(chart, pixel, axisWidth);\n };\n let borderValue, i, lineValue, alignedLineValue;\n let tx1, ty1, tx2, ty2, x1, y1, x2, y2;\n if (position === 'top') {\n borderValue = alignBorderValue(this.bottom);\n ty1 = this.bottom - tl;\n ty2 = borderValue - axisHalfWidth;\n y1 = alignBorderValue(chartArea.top) + axisHalfWidth;\n y2 = chartArea.bottom;\n } else if (position === 'bottom') {\n borderValue = alignBorderValue(this.top);\n y1 = chartArea.top;\n y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;\n ty1 = borderValue + axisHalfWidth;\n ty2 = this.top + tl;\n } else if (position === 'left') {\n borderValue = alignBorderValue(this.right);\n tx1 = this.right - tl;\n tx2 = borderValue - axisHalfWidth;\n x1 = alignBorderValue(chartArea.left) + axisHalfWidth;\n x2 = chartArea.right;\n } else if (position === 'right') {\n borderValue = alignBorderValue(this.left);\n x1 = chartArea.left;\n x2 = alignBorderValue(chartArea.right) - axisHalfWidth;\n tx1 = borderValue + axisHalfWidth;\n tx2 = this.left + tl;\n } else if (axis === 'x') {\n if (position === 'center') {\n borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));\n }\n y1 = chartArea.top;\n y2 = chartArea.bottom;\n ty1 = borderValue + axisHalfWidth;\n ty2 = ty1 + tl;\n } else if (axis === 'y') {\n if (position === 'center') {\n borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));\n }\n tx1 = borderValue - axisHalfWidth;\n tx2 = tx1 - tl;\n x1 = chartArea.left;\n x2 = chartArea.right;\n }\n const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);\n const step = Math.max(1, Math.ceil(ticksLength / limit));\n for (i = 0; i < ticksLength; i += step) {\n const optsAtIndex = grid.setContext(this.getContext(i));\n const lineWidth = optsAtIndex.lineWidth;\n const lineColor = optsAtIndex.color;\n const borderDash = grid.borderDash || [];\n const borderDashOffset = optsAtIndex.borderDashOffset;\n const tickWidth = optsAtIndex.tickWidth;\n const tickColor = optsAtIndex.tickColor;\n const tickBorderDash = optsAtIndex.tickBorderDash || [];\n const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;\n lineValue = getPixelForGridLine(this, i, offset);\n if (lineValue === undefined) {\n continue;\n }\n alignedLineValue = _alignPixel(chart, lineValue, lineWidth);\n if (isHorizontal) {\n tx1 = tx2 = x1 = x2 = alignedLineValue;\n } else {\n ty1 = ty2 = y1 = y2 = alignedLineValue;\n }\n items.push({\n tx1,\n ty1,\n tx2,\n ty2,\n x1,\n y1,\n x2,\n y2,\n width: lineWidth,\n color: lineColor,\n borderDash,\n borderDashOffset,\n tickWidth,\n tickColor,\n tickBorderDash,\n tickBorderDashOffset,\n });\n }\n this._ticksLength = ticksLength;\n this._borderValue = borderValue;\n return items;\n }\n _computeLabelItems(chartArea) {\n const axis = this.axis;\n const options = this.options;\n const {position, ticks: optionTicks} = options;\n const isHorizontal = this.isHorizontal();\n const ticks = this.ticks;\n const {align, crossAlign, padding, mirror} = optionTicks;\n const tl = getTickMarkLength(options.grid);\n const tickAndPadding = tl + padding;\n const hTickAndPadding = mirror ? -padding : tickAndPadding;\n const rotation = -toRadians(this.labelRotation);\n const items = [];\n let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;\n let textBaseline = 'middle';\n if (position === 'top') {\n y = this.bottom - hTickAndPadding;\n textAlign = this._getXAxisLabelAlignment();\n } else if (position === 'bottom') {\n y = this.top + hTickAndPadding;\n textAlign = this._getXAxisLabelAlignment();\n } else if (position === 'left') {\n const ret = this._getYAxisLabelAlignment(tl);\n textAlign = ret.textAlign;\n x = ret.x;\n } else if (position === 'right') {\n const ret = this._getYAxisLabelAlignment(tl);\n textAlign = ret.textAlign;\n x = ret.x;\n } else if (axis === 'x') {\n if (position === 'center') {\n y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding;\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;\n }\n textAlign = this._getXAxisLabelAlignment();\n } else if (axis === 'y') {\n if (position === 'center') {\n x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding;\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n x = this.chart.scales[positionAxisID].getPixelForValue(value);\n }\n textAlign = this._getYAxisLabelAlignment(tl).textAlign;\n }\n if (axis === 'y') {\n if (align === 'start') {\n textBaseline = 'top';\n } else if (align === 'end') {\n textBaseline = 'bottom';\n }\n }\n const labelSizes = this._getLabelSizes();\n for (i = 0, ilen = ticks.length; i < ilen; ++i) {\n tick = ticks[i];\n label = tick.label;\n const optsAtIndex = optionTicks.setContext(this.getContext(i));\n pixel = this.getPixelForTick(i) + optionTicks.labelOffset;\n font = this._resolveTickFontOptions(i);\n lineHeight = font.lineHeight;\n lineCount = isArray(label) ? label.length : 1;\n const halfCount = lineCount / 2;\n const color = optsAtIndex.color;\n const strokeColor = optsAtIndex.textStrokeColor;\n const strokeWidth = optsAtIndex.textStrokeWidth;\n if (isHorizontal) {\n x = pixel;\n if (position === 'top') {\n if (crossAlign === 'near' || rotation !== 0) {\n textOffset = -lineCount * lineHeight + lineHeight / 2;\n } else if (crossAlign === 'center') {\n textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;\n } else {\n textOffset = -labelSizes.highest.height + lineHeight / 2;\n }\n } else {\n if (crossAlign === 'near' || rotation !== 0) {\n textOffset = lineHeight / 2;\n } else if (crossAlign === 'center') {\n textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;\n } else {\n textOffset = labelSizes.highest.height - lineCount * lineHeight;\n }\n }\n if (mirror) {\n textOffset *= -1;\n }\n } else {\n y = pixel;\n textOffset = (1 - lineCount) * lineHeight / 2;\n }\n let backdrop;\n if (optsAtIndex.showLabelBackdrop) {\n const labelPadding = toPadding(optsAtIndex.backdropPadding);\n const height = labelSizes.heights[i];\n const width = labelSizes.widths[i];\n let top = y + textOffset - labelPadding.top;\n let left = x - labelPadding.left;\n switch (textBaseline) {\n case 'middle':\n top -= height / 2;\n break;\n case 'bottom':\n top -= height;\n break;\n }\n switch (textAlign) {\n case 'center':\n left -= width / 2;\n break;\n case 'right':\n left -= width;\n break;\n }\n backdrop = {\n left,\n top,\n width: width + labelPadding.width,\n height: height + labelPadding.height,\n color: optsAtIndex.backdropColor,\n };\n }\n items.push({\n rotation,\n label,\n font,\n color,\n strokeColor,\n strokeWidth,\n textOffset,\n textAlign,\n textBaseline,\n translation: [x, y],\n backdrop,\n });\n }\n return items;\n }\n _getXAxisLabelAlignment() {\n const {position, ticks} = this.options;\n const rotation = -toRadians(this.labelRotation);\n if (rotation) {\n return position === 'top' ? 'left' : 'right';\n }\n let align = 'center';\n if (ticks.align === 'start') {\n align = 'left';\n } else if (ticks.align === 'end') {\n align = 'right';\n }\n return align;\n }\n _getYAxisLabelAlignment(tl) {\n const {position, ticks: {crossAlign, mirror, padding}} = this.options;\n const labelSizes = this._getLabelSizes();\n const tickAndPadding = tl + padding;\n const widest = labelSizes.widest.width;\n let textAlign;\n let x;\n if (position === 'left') {\n if (mirror) {\n x = this.right + padding;\n if (crossAlign === 'near') {\n textAlign = 'left';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x += (widest / 2);\n } else {\n textAlign = 'right';\n x += widest;\n }\n } else {\n x = this.right - tickAndPadding;\n if (crossAlign === 'near') {\n textAlign = 'right';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x -= (widest / 2);\n } else {\n textAlign = 'left';\n x = this.left;\n }\n }\n } else if (position === 'right') {\n if (mirror) {\n x = this.left + padding;\n if (crossAlign === 'near') {\n textAlign = 'right';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x -= (widest / 2);\n } else {\n textAlign = 'left';\n x -= widest;\n }\n } else {\n x = this.left + tickAndPadding;\n if (crossAlign === 'near') {\n textAlign = 'left';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x += widest / 2;\n } else {\n textAlign = 'right';\n x = this.right;\n }\n }\n } else {\n textAlign = 'right';\n }\n return {textAlign, x};\n }\n _computeLabelArea() {\n if (this.options.ticks.mirror) {\n return;\n }\n const chart = this.chart;\n const position = this.options.position;\n if (position === 'left' || position === 'right') {\n return {top: 0, left: this.left, bottom: chart.height, right: this.right};\n } if (position === 'top' || position === 'bottom') {\n return {top: this.top, left: 0, bottom: this.bottom, right: chart.width};\n }\n }\n drawBackground() {\n const {ctx, options: {backgroundColor}, left, top, width, height} = this;\n if (backgroundColor) {\n ctx.save();\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(left, top, width, height);\n ctx.restore();\n }\n }\n getLineWidthForValue(value) {\n const grid = this.options.grid;\n if (!this._isVisible() || !grid.display) {\n return 0;\n }\n const ticks = this.ticks;\n const index = ticks.findIndex(t => t.value === value);\n if (index >= 0) {\n const opts = grid.setContext(this.getContext(index));\n return opts.lineWidth;\n }\n return 0;\n }\n drawGrid(chartArea) {\n const grid = this.options.grid;\n const ctx = this.ctx;\n const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));\n let i, ilen;\n const drawLine = (p1, p2, style) => {\n if (!style.width || !style.color) {\n return;\n }\n ctx.save();\n ctx.lineWidth = style.width;\n ctx.strokeStyle = style.color;\n ctx.setLineDash(style.borderDash || []);\n ctx.lineDashOffset = style.borderDashOffset;\n ctx.beginPath();\n ctx.moveTo(p1.x, p1.y);\n ctx.lineTo(p2.x, p2.y);\n ctx.stroke();\n ctx.restore();\n };\n if (grid.display) {\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n const item = items[i];\n if (grid.drawOnChartArea) {\n drawLine(\n {x: item.x1, y: item.y1},\n {x: item.x2, y: item.y2},\n item\n );\n }\n if (grid.drawTicks) {\n drawLine(\n {x: item.tx1, y: item.ty1},\n {x: item.tx2, y: item.ty2},\n {\n color: item.tickColor,\n width: item.tickWidth,\n borderDash: item.tickBorderDash,\n borderDashOffset: item.tickBorderDashOffset\n }\n );\n }\n }\n }\n }\n drawBorder() {\n const {chart, ctx, options: {grid}} = this;\n const borderOpts = grid.setContext(this.getContext());\n const axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0;\n if (!axisWidth) {\n return;\n }\n const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;\n const borderValue = this._borderValue;\n let x1, x2, y1, y2;\n if (this.isHorizontal()) {\n x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2;\n x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;\n y1 = y2 = borderValue;\n } else {\n y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2;\n y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;\n x1 = x2 = borderValue;\n }\n ctx.save();\n ctx.lineWidth = borderOpts.borderWidth;\n ctx.strokeStyle = borderOpts.borderColor;\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.stroke();\n ctx.restore();\n }\n drawLabels(chartArea) {\n const optionTicks = this.options.ticks;\n if (!optionTicks.display) {\n return;\n }\n const ctx = this.ctx;\n const area = this._computeLabelArea();\n if (area) {\n clipArea(ctx, area);\n }\n const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));\n let i, ilen;\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n const item = items[i];\n const tickFont = item.font;\n const label = item.label;\n if (item.backdrop) {\n ctx.fillStyle = item.backdrop.color;\n ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height);\n }\n let y = item.textOffset;\n renderText(ctx, label, 0, y, tickFont, item);\n }\n if (area) {\n unclipArea(ctx);\n }\n }\n drawTitle() {\n const {ctx, options: {position, title, reverse}} = this;\n if (!title.display) {\n return;\n }\n const font = toFont(title.font);\n const padding = toPadding(title.padding);\n const align = title.align;\n let offset = font.lineHeight / 2;\n if (position === 'bottom' || position === 'center' || isObject(position)) {\n offset += padding.bottom;\n if (isArray(title.text)) {\n offset += font.lineHeight * (title.text.length - 1);\n }\n } else {\n offset += padding.top;\n }\n const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align);\n renderText(ctx, title.text, 0, 0, font, {\n color: title.color,\n maxWidth,\n rotation,\n textAlign: titleAlign(align, position, reverse),\n textBaseline: 'middle',\n translation: [titleX, titleY],\n });\n }\n draw(chartArea) {\n if (!this._isVisible()) {\n return;\n }\n this.drawBackground();\n this.drawGrid(chartArea);\n this.drawBorder();\n this.drawTitle();\n this.drawLabels(chartArea);\n }\n _layers() {\n const opts = this.options;\n const tz = opts.ticks && opts.ticks.z || 0;\n const gz = valueOrDefault(opts.grid && opts.grid.z, -1);\n if (!this._isVisible() || this.draw !== Scale.prototype.draw) {\n return [{\n z: tz,\n draw: (chartArea) => {\n this.draw(chartArea);\n }\n }];\n }\n return [{\n z: gz,\n draw: (chartArea) => {\n this.drawBackground();\n this.drawGrid(chartArea);\n this.drawTitle();\n }\n }, {\n z: gz + 1,\n draw: () => {\n this.drawBorder();\n }\n }, {\n z: tz,\n draw: (chartArea) => {\n this.drawLabels(chartArea);\n }\n }];\n }\n getMatchingVisibleMetas(type) {\n const metas = this.chart.getSortedVisibleDatasetMetas();\n const axisID = this.axis + 'AxisID';\n const result = [];\n let i, ilen;\n for (i = 0, ilen = metas.length; i < ilen; ++i) {\n const meta = metas[i];\n if (meta[axisID] === this.id && (!type || meta.type === type)) {\n result.push(meta);\n }\n }\n return result;\n }\n _resolveTickFontOptions(index) {\n const opts = this.options.ticks.setContext(this.getContext(index));\n return toFont(opts.font);\n }\n _maxDigits() {\n const fontSize = this._resolveTickFontOptions(0).lineHeight;\n return (this.isHorizontal() ? this.width : this.height) / fontSize;\n }\n}\n\nclass TypedRegistry {\n constructor(type, scope, override) {\n this.type = type;\n this.scope = scope;\n this.override = override;\n this.items = Object.create(null);\n }\n isForType(type) {\n return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);\n }\n register(item) {\n const proto = Object.getPrototypeOf(item);\n let parentScope;\n if (isIChartComponent(proto)) {\n parentScope = this.register(proto);\n }\n const items = this.items;\n const id = item.id;\n const scope = this.scope + '.' + id;\n if (!id) {\n throw new Error('class does not have id: ' + item);\n }\n if (id in items) {\n return scope;\n }\n items[id] = item;\n registerDefaults(item, scope, parentScope);\n if (this.override) {\n defaults.override(item.id, item.overrides);\n }\n return scope;\n }\n get(id) {\n return this.items[id];\n }\n unregister(item) {\n const items = this.items;\n const id = item.id;\n const scope = this.scope;\n if (id in items) {\n delete items[id];\n }\n if (scope && id in defaults[scope]) {\n delete defaults[scope][id];\n if (this.override) {\n delete overrides[id];\n }\n }\n }\n}\nfunction registerDefaults(item, scope, parentScope) {\n const itemDefaults = merge(Object.create(null), [\n parentScope ? defaults.get(parentScope) : {},\n defaults.get(scope),\n item.defaults\n ]);\n defaults.set(scope, itemDefaults);\n if (item.defaultRoutes) {\n routeDefaults(scope, item.defaultRoutes);\n }\n if (item.descriptors) {\n defaults.describe(scope, item.descriptors);\n }\n}\nfunction routeDefaults(scope, routes) {\n Object.keys(routes).forEach(property => {\n const propertyParts = property.split('.');\n const sourceName = propertyParts.pop();\n const sourceScope = [scope].concat(propertyParts).join('.');\n const parts = routes[property].split('.');\n const targetName = parts.pop();\n const targetScope = parts.join('.');\n defaults.route(sourceScope, sourceName, targetScope, targetName);\n });\n}\nfunction isIChartComponent(proto) {\n return 'id' in proto && 'defaults' in proto;\n}\n\nclass Registry {\n constructor() {\n this.controllers = new TypedRegistry(DatasetController, 'datasets', true);\n this.elements = new TypedRegistry(Element, 'elements');\n this.plugins = new TypedRegistry(Object, 'plugins');\n this.scales = new TypedRegistry(Scale, 'scales');\n this._typedRegistries = [this.controllers, this.scales, this.elements];\n }\n add(...args) {\n this._each('register', args);\n }\n remove(...args) {\n this._each('unregister', args);\n }\n addControllers(...args) {\n this._each('register', args, this.controllers);\n }\n addElements(...args) {\n this._each('register', args, this.elements);\n }\n addPlugins(...args) {\n this._each('register', args, this.plugins);\n }\n addScales(...args) {\n this._each('register', args, this.scales);\n }\n getController(id) {\n return this._get(id, this.controllers, 'controller');\n }\n getElement(id) {\n return this._get(id, this.elements, 'element');\n }\n getPlugin(id) {\n return this._get(id, this.plugins, 'plugin');\n }\n getScale(id) {\n return this._get(id, this.scales, 'scale');\n }\n removeControllers(...args) {\n this._each('unregister', args, this.controllers);\n }\n removeElements(...args) {\n this._each('unregister', args, this.elements);\n }\n removePlugins(...args) {\n this._each('unregister', args, this.plugins);\n }\n removeScales(...args) {\n this._each('unregister', args, this.scales);\n }\n _each(method, args, typedRegistry) {\n [...args].forEach(arg => {\n const reg = typedRegistry || this._getRegistryForType(arg);\n if (typedRegistry || reg.isForType(arg) || (reg === this.plugins && arg.id)) {\n this._exec(method, reg, arg);\n } else {\n each(arg, item => {\n const itemReg = typedRegistry || this._getRegistryForType(item);\n this._exec(method, itemReg, item);\n });\n }\n });\n }\n _exec(method, registry, component) {\n const camelMethod = _capitalize(method);\n callback(component['before' + camelMethod], [], component);\n registry[method](component);\n callback(component['after' + camelMethod], [], component);\n }\n _getRegistryForType(type) {\n for (let i = 0; i < this._typedRegistries.length; i++) {\n const reg = this._typedRegistries[i];\n if (reg.isForType(type)) {\n return reg;\n }\n }\n return this.plugins;\n }\n _get(id, typedRegistry, type) {\n const item = typedRegistry.get(id);\n if (item === undefined) {\n throw new Error('\"' + id + '\" is not a registered ' + type + '.');\n }\n return item;\n }\n}\nvar registry = new Registry();\n\nclass PluginService {\n constructor() {\n this._init = [];\n }\n notify(chart, hook, args, filter) {\n if (hook === 'beforeInit') {\n this._init = this._createDescriptors(chart, true);\n this._notify(this._init, chart, 'install');\n }\n const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);\n const result = this._notify(descriptors, chart, hook, args);\n if (hook === 'afterDestroy') {\n this._notify(descriptors, chart, 'stop');\n this._notify(this._init, chart, 'uninstall');\n }\n return result;\n }\n _notify(descriptors, chart, hook, args) {\n args = args || {};\n for (const descriptor of descriptors) {\n const plugin = descriptor.plugin;\n const method = plugin[hook];\n const params = [chart, args, descriptor.options];\n if (callback(method, params, plugin) === false && args.cancelable) {\n return false;\n }\n }\n return true;\n }\n invalidate() {\n if (!isNullOrUndef(this._cache)) {\n this._oldCache = this._cache;\n this._cache = undefined;\n }\n }\n _descriptors(chart) {\n if (this._cache) {\n return this._cache;\n }\n const descriptors = this._cache = this._createDescriptors(chart);\n this._notifyStateChanges(chart);\n return descriptors;\n }\n _createDescriptors(chart, all) {\n const config = chart && chart.config;\n const options = valueOrDefault(config.options && config.options.plugins, {});\n const plugins = allPlugins(config);\n return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);\n }\n _notifyStateChanges(chart) {\n const previousDescriptors = this._oldCache || [];\n const descriptors = this._cache;\n const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id));\n this._notify(diff(previousDescriptors, descriptors), chart, 'stop');\n this._notify(diff(descriptors, previousDescriptors), chart, 'start');\n }\n}\nfunction allPlugins(config) {\n const plugins = [];\n const keys = Object.keys(registry.plugins.items);\n for (let i = 0; i < keys.length; i++) {\n plugins.push(registry.getPlugin(keys[i]));\n }\n const local = config.plugins || [];\n for (let i = 0; i < local.length; i++) {\n const plugin = local[i];\n if (plugins.indexOf(plugin) === -1) {\n plugins.push(plugin);\n }\n }\n return plugins;\n}\nfunction getOpts(options, all) {\n if (!all && options === false) {\n return null;\n }\n if (options === true) {\n return {};\n }\n return options;\n}\nfunction createDescriptors(chart, plugins, options, all) {\n const result = [];\n const context = chart.getContext();\n for (let i = 0; i < plugins.length; i++) {\n const plugin = plugins[i];\n const id = plugin.id;\n const opts = getOpts(options[id], all);\n if (opts === null) {\n continue;\n }\n result.push({\n plugin,\n options: pluginOpts(chart.config, plugin, opts, context)\n });\n }\n return result;\n}\nfunction pluginOpts(config, plugin, opts, context) {\n const keys = config.pluginScopeKeys(plugin);\n const scopes = config.getOptionScopes(opts, keys);\n return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false, allKeys: true});\n}\n\nfunction getIndexAxis(type, options) {\n const datasetDefaults = defaults.datasets[type] || {};\n const datasetOptions = (options.datasets || {})[type] || {};\n return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';\n}\nfunction getAxisFromDefaultScaleID(id, indexAxis) {\n let axis = id;\n if (id === '_index_') {\n axis = indexAxis;\n } else if (id === '_value_') {\n axis = indexAxis === 'x' ? 'y' : 'x';\n }\n return axis;\n}\nfunction getDefaultScaleIDFromAxis(axis, indexAxis) {\n return axis === indexAxis ? '_index_' : '_value_';\n}\nfunction axisFromPosition(position) {\n if (position === 'top' || position === 'bottom') {\n return 'x';\n }\n if (position === 'left' || position === 'right') {\n return 'y';\n }\n}\nfunction determineAxis(id, scaleOptions) {\n if (id === 'x' || id === 'y') {\n return id;\n }\n return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase();\n}\nfunction mergeScaleConfig(config, options) {\n const chartDefaults = overrides[config.type] || {scales: {}};\n const configScales = options.scales || {};\n const chartIndexAxis = getIndexAxis(config.type, options);\n const firstIDs = Object.create(null);\n const scales = Object.create(null);\n Object.keys(configScales).forEach(id => {\n const scaleConf = configScales[id];\n if (!isObject(scaleConf)) {\n return console.error(`Invalid scale configuration for scale: ${id}`);\n }\n if (scaleConf._proxy) {\n return console.warn(`Ignoring resolver passed as options for scale: ${id}`);\n }\n const axis = determineAxis(id, scaleConf);\n const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);\n const defaultScaleOptions = chartDefaults.scales || {};\n firstIDs[axis] = firstIDs[axis] || id;\n scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);\n });\n config.data.datasets.forEach(dataset => {\n const type = dataset.type || config.type;\n const indexAxis = dataset.indexAxis || getIndexAxis(type, options);\n const datasetDefaults = overrides[type] || {};\n const defaultScaleOptions = datasetDefaults.scales || {};\n Object.keys(defaultScaleOptions).forEach(defaultID => {\n const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);\n const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis;\n scales[id] = scales[id] || Object.create(null);\n mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);\n });\n });\n Object.keys(scales).forEach(key => {\n const scale = scales[key];\n mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);\n });\n return scales;\n}\nfunction initOptions(config) {\n const options = config.options || (config.options = {});\n options.plugins = valueOrDefault(options.plugins, {});\n options.scales = mergeScaleConfig(config, options);\n}\nfunction initData(data) {\n data = data || {};\n data.datasets = data.datasets || [];\n data.labels = data.labels || [];\n return data;\n}\nfunction initConfig(config) {\n config = config || {};\n config.data = initData(config.data);\n initOptions(config);\n return config;\n}\nconst keyCache = new Map();\nconst keysCached = new Set();\nfunction cachedKeys(cacheKey, generate) {\n let keys = keyCache.get(cacheKey);\n if (!keys) {\n keys = generate();\n keyCache.set(cacheKey, keys);\n keysCached.add(keys);\n }\n return keys;\n}\nconst addIfFound = (set, obj, key) => {\n const opts = resolveObjectKey(obj, key);\n if (opts !== undefined) {\n set.add(opts);\n }\n};\nclass Config {\n constructor(config) {\n this._config = initConfig(config);\n this._scopeCache = new Map();\n this._resolverCache = new Map();\n }\n get platform() {\n return this._config.platform;\n }\n get type() {\n return this._config.type;\n }\n set type(type) {\n this._config.type = type;\n }\n get data() {\n return this._config.data;\n }\n set data(data) {\n this._config.data = initData(data);\n }\n get options() {\n return this._config.options;\n }\n set options(options) {\n this._config.options = options;\n }\n get plugins() {\n return this._config.plugins;\n }\n update() {\n const config = this._config;\n this.clearCache();\n initOptions(config);\n }\n clearCache() {\n this._scopeCache.clear();\n this._resolverCache.clear();\n }\n datasetScopeKeys(datasetType) {\n return cachedKeys(datasetType,\n () => [[\n `datasets.${datasetType}`,\n ''\n ]]);\n }\n datasetAnimationScopeKeys(datasetType, transition) {\n return cachedKeys(`${datasetType}.transition.${transition}`,\n () => [\n [\n `datasets.${datasetType}.transitions.${transition}`,\n `transitions.${transition}`,\n ],\n [\n `datasets.${datasetType}`,\n ''\n ]\n ]);\n }\n datasetElementScopeKeys(datasetType, elementType) {\n return cachedKeys(`${datasetType}-${elementType}`,\n () => [[\n `datasets.${datasetType}.elements.${elementType}`,\n `datasets.${datasetType}`,\n `elements.${elementType}`,\n ''\n ]]);\n }\n pluginScopeKeys(plugin) {\n const id = plugin.id;\n const type = this.type;\n return cachedKeys(`${type}-plugin-${id}`,\n () => [[\n `plugins.${id}`,\n ...plugin.additionalOptionScopes || [],\n ]]);\n }\n _cachedScopes(mainScope, resetCache) {\n const _scopeCache = this._scopeCache;\n let cache = _scopeCache.get(mainScope);\n if (!cache || resetCache) {\n cache = new Map();\n _scopeCache.set(mainScope, cache);\n }\n return cache;\n }\n getOptionScopes(mainScope, keyLists, resetCache) {\n const {options, type} = this;\n const cache = this._cachedScopes(mainScope, resetCache);\n const cached = cache.get(keyLists);\n if (cached) {\n return cached;\n }\n const scopes = new Set();\n keyLists.forEach(keys => {\n if (mainScope) {\n scopes.add(mainScope);\n keys.forEach(key => addIfFound(scopes, mainScope, key));\n }\n keys.forEach(key => addIfFound(scopes, options, key));\n keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key));\n keys.forEach(key => addIfFound(scopes, defaults, key));\n keys.forEach(key => addIfFound(scopes, descriptors, key));\n });\n const array = Array.from(scopes);\n if (array.length === 0) {\n array.push(Object.create(null));\n }\n if (keysCached.has(keyLists)) {\n cache.set(keyLists, array);\n }\n return array;\n }\n chartOptionScopes() {\n const {options, type} = this;\n return [\n options,\n overrides[type] || {},\n defaults.datasets[type] || {},\n {type},\n defaults,\n descriptors\n ];\n }\n resolveNamedOptions(scopes, names, context, prefixes = ['']) {\n const result = {$shared: true};\n const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes);\n let options = resolver;\n if (needContext(resolver, names)) {\n result.$shared = false;\n context = isFunction(context) ? context() : context;\n const subResolver = this.createResolver(scopes, context, subPrefixes);\n options = _attachContext(resolver, context, subResolver);\n }\n for (const prop of names) {\n result[prop] = options[prop];\n }\n return result;\n }\n createResolver(scopes, context, prefixes = [''], descriptorDefaults) {\n const {resolver} = getResolver(this._resolverCache, scopes, prefixes);\n return isObject(context)\n ? _attachContext(resolver, context, undefined, descriptorDefaults)\n : resolver;\n }\n}\nfunction getResolver(resolverCache, scopes, prefixes) {\n let cache = resolverCache.get(scopes);\n if (!cache) {\n cache = new Map();\n resolverCache.set(scopes, cache);\n }\n const cacheKey = prefixes.join();\n let cached = cache.get(cacheKey);\n if (!cached) {\n const resolver = _createResolver(scopes, prefixes);\n cached = {\n resolver,\n subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover'))\n };\n cache.set(cacheKey, cached);\n }\n return cached;\n}\nconst hasFunction = value => isObject(value)\n && Object.getOwnPropertyNames(value).reduce((acc, key) => acc || isFunction(value[key]), false);\nfunction needContext(proxy, names) {\n const {isScriptable, isIndexable} = _descriptors(proxy);\n for (const prop of names) {\n const scriptable = isScriptable(prop);\n const indexable = isIndexable(prop);\n const value = (indexable || scriptable) && proxy[prop];\n if ((scriptable && (isFunction(value) || hasFunction(value)))\n || (indexable && isArray(value))) {\n return true;\n }\n }\n return false;\n}\n\nvar version = \"3.7.1\";\n\nconst KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];\nfunction positionIsHorizontal(position, axis) {\n return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');\n}\nfunction compare2Level(l1, l2) {\n return function(a, b) {\n return a[l1] === b[l1]\n ? a[l2] - b[l2]\n : a[l1] - b[l1];\n };\n}\nfunction onAnimationsComplete(context) {\n const chart = context.chart;\n const animationOptions = chart.options.animation;\n chart.notifyPlugins('afterRender');\n callback(animationOptions && animationOptions.onComplete, [context], chart);\n}\nfunction onAnimationProgress(context) {\n const chart = context.chart;\n const animationOptions = chart.options.animation;\n callback(animationOptions && animationOptions.onProgress, [context], chart);\n}\nfunction getCanvas(item) {\n if (_isDomSupported() && typeof item === 'string') {\n item = document.getElementById(item);\n } else if (item && item.length) {\n item = item[0];\n }\n if (item && item.canvas) {\n item = item.canvas;\n }\n return item;\n}\nconst instances = {};\nconst getChart = (key) => {\n const canvas = getCanvas(key);\n return Object.values(instances).filter((c) => c.canvas === canvas).pop();\n};\nfunction moveNumericKeys(obj, start, move) {\n const keys = Object.keys(obj);\n for (const key of keys) {\n const intKey = +key;\n if (intKey >= start) {\n const value = obj[key];\n delete obj[key];\n if (move > 0 || intKey > start) {\n obj[intKey + move] = value;\n }\n }\n }\n}\nfunction determineLastEvent(e, lastEvent, inChartArea, isClick) {\n if (!inChartArea || e.type === 'mouseout') {\n return null;\n }\n if (isClick) {\n return lastEvent;\n }\n return e;\n}\nclass Chart {\n constructor(item, userConfig) {\n const config = this.config = new Config(userConfig);\n const initialCanvas = getCanvas(item);\n const existingChart = getChart(initialCanvas);\n if (existingChart) {\n throw new Error(\n 'Canvas is already in use. Chart with ID \\'' + existingChart.id + '\\'' +\n\t\t\t\t' must be destroyed before the canvas can be reused.'\n );\n }\n const options = config.createResolver(config.chartOptionScopes(), this.getContext());\n this.platform = new (config.platform || _detectPlatform(initialCanvas))();\n this.platform.updateConfig(config);\n const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);\n const canvas = context && context.canvas;\n const height = canvas && canvas.height;\n const width = canvas && canvas.width;\n this.id = uid();\n this.ctx = context;\n this.canvas = canvas;\n this.width = width;\n this.height = height;\n this._options = options;\n this._aspectRatio = this.aspectRatio;\n this._layers = [];\n this._metasets = [];\n this._stacks = undefined;\n this.boxes = [];\n this.currentDevicePixelRatio = undefined;\n this.chartArea = undefined;\n this._active = [];\n this._lastEvent = undefined;\n this._listeners = {};\n this._responsiveListeners = undefined;\n this._sortedMetasets = [];\n this.scales = {};\n this._plugins = new PluginService();\n this.$proxies = {};\n this._hiddenIndices = {};\n this.attached = false;\n this._animationsDisabled = undefined;\n this.$context = undefined;\n this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0);\n this._dataChanges = [];\n instances[this.id] = this;\n if (!context || !canvas) {\n console.error(\"Failed to create chart: can't acquire context from the given item\");\n return;\n }\n animator.listen(this, 'complete', onAnimationsComplete);\n animator.listen(this, 'progress', onAnimationProgress);\n this._initialize();\n if (this.attached) {\n this.update();\n }\n }\n get aspectRatio() {\n const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this;\n if (!isNullOrUndef(aspectRatio)) {\n return aspectRatio;\n }\n if (maintainAspectRatio && _aspectRatio) {\n return _aspectRatio;\n }\n return height ? width / height : null;\n }\n get data() {\n return this.config.data;\n }\n set data(data) {\n this.config.data = data;\n }\n get options() {\n return this._options;\n }\n set options(options) {\n this.config.options = options;\n }\n _initialize() {\n this.notifyPlugins('beforeInit');\n if (this.options.responsive) {\n this.resize();\n } else {\n retinaScale(this, this.options.devicePixelRatio);\n }\n this.bindEvents();\n this.notifyPlugins('afterInit');\n return this;\n }\n clear() {\n clearCanvas(this.canvas, this.ctx);\n return this;\n }\n stop() {\n animator.stop(this);\n return this;\n }\n resize(width, height) {\n if (!animator.running(this)) {\n this._resize(width, height);\n } else {\n this._resizeBeforeDraw = {width, height};\n }\n }\n _resize(width, height) {\n const options = this.options;\n const canvas = this.canvas;\n const aspectRatio = options.maintainAspectRatio && this.aspectRatio;\n const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);\n const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();\n const mode = this.width ? 'resize' : 'attach';\n this.width = newSize.width;\n this.height = newSize.height;\n this._aspectRatio = this.aspectRatio;\n if (!retinaScale(this, newRatio, true)) {\n return;\n }\n this.notifyPlugins('resize', {size: newSize});\n callback(options.onResize, [this, newSize], this);\n if (this.attached) {\n if (this._doResize(mode)) {\n this.render();\n }\n }\n }\n ensureScalesHaveIDs() {\n const options = this.options;\n const scalesOptions = options.scales || {};\n each(scalesOptions, (axisOptions, axisID) => {\n axisOptions.id = axisID;\n });\n }\n buildOrUpdateScales() {\n const options = this.options;\n const scaleOpts = options.scales;\n const scales = this.scales;\n const updated = Object.keys(scales).reduce((obj, id) => {\n obj[id] = false;\n return obj;\n }, {});\n let items = [];\n if (scaleOpts) {\n items = items.concat(\n Object.keys(scaleOpts).map((id) => {\n const scaleOptions = scaleOpts[id];\n const axis = determineAxis(id, scaleOptions);\n const isRadial = axis === 'r';\n const isHorizontal = axis === 'x';\n return {\n options: scaleOptions,\n dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',\n dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'\n };\n })\n );\n }\n each(items, (item) => {\n const scaleOptions = item.options;\n const id = scaleOptions.id;\n const axis = determineAxis(id, scaleOptions);\n const scaleType = valueOrDefault(scaleOptions.type, item.dtype);\n if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {\n scaleOptions.position = item.dposition;\n }\n updated[id] = true;\n let scale = null;\n if (id in scales && scales[id].type === scaleType) {\n scale = scales[id];\n } else {\n const scaleClass = registry.getScale(scaleType);\n scale = new scaleClass({\n id,\n type: scaleType,\n ctx: this.ctx,\n chart: this\n });\n scales[scale.id] = scale;\n }\n scale.init(scaleOptions, options);\n });\n each(updated, (hasUpdated, id) => {\n if (!hasUpdated) {\n delete scales[id];\n }\n });\n each(scales, (scale) => {\n layouts.configure(this, scale, scale.options);\n layouts.addBox(this, scale);\n });\n }\n _updateMetasets() {\n const metasets = this._metasets;\n const numData = this.data.datasets.length;\n const numMeta = metasets.length;\n metasets.sort((a, b) => a.index - b.index);\n if (numMeta > numData) {\n for (let i = numData; i < numMeta; ++i) {\n this._destroyDatasetMeta(i);\n }\n metasets.splice(numData, numMeta - numData);\n }\n this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));\n }\n _removeUnreferencedMetasets() {\n const {_metasets: metasets, data: {datasets}} = this;\n if (metasets.length > datasets.length) {\n delete this._stacks;\n }\n metasets.forEach((meta, index) => {\n if (datasets.filter(x => x === meta._dataset).length === 0) {\n this._destroyDatasetMeta(index);\n }\n });\n }\n buildOrUpdateControllers() {\n const newControllers = [];\n const datasets = this.data.datasets;\n let i, ilen;\n this._removeUnreferencedMetasets();\n for (i = 0, ilen = datasets.length; i < ilen; i++) {\n const dataset = datasets[i];\n let meta = this.getDatasetMeta(i);\n const type = dataset.type || this.config.type;\n if (meta.type && meta.type !== type) {\n this._destroyDatasetMeta(i);\n meta = this.getDatasetMeta(i);\n }\n meta.type = type;\n meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);\n meta.order = dataset.order || 0;\n meta.index = i;\n meta.label = '' + dataset.label;\n meta.visible = this.isDatasetVisible(i);\n if (meta.controller) {\n meta.controller.updateIndex(i);\n meta.controller.linkScales();\n } else {\n const ControllerClass = registry.getController(type);\n const {datasetElementType, dataElementType} = defaults.datasets[type];\n Object.assign(ControllerClass.prototype, {\n dataElementType: registry.getElement(dataElementType),\n datasetElementType: datasetElementType && registry.getElement(datasetElementType)\n });\n meta.controller = new ControllerClass(this, i);\n newControllers.push(meta.controller);\n }\n }\n this._updateMetasets();\n return newControllers;\n }\n _resetElements() {\n each(this.data.datasets, (dataset, datasetIndex) => {\n this.getDatasetMeta(datasetIndex).controller.reset();\n }, this);\n }\n reset() {\n this._resetElements();\n this.notifyPlugins('reset');\n }\n update(mode) {\n const config = this.config;\n config.update();\n const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());\n const animsDisabled = this._animationsDisabled = !options.animation;\n this._updateScales();\n this._checkEventBindings();\n this._updateHiddenIndices();\n this._plugins.invalidate();\n if (this.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) {\n return;\n }\n const newControllers = this.buildOrUpdateControllers();\n this.notifyPlugins('beforeElementsUpdate');\n let minPadding = 0;\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; i++) {\n const {controller} = this.getDatasetMeta(i);\n const reset = !animsDisabled && newControllers.indexOf(controller) === -1;\n controller.buildOrUpdateElements(reset);\n minPadding = Math.max(+controller.getMaxOverflow(), minPadding);\n }\n minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;\n this._updateLayout(minPadding);\n if (!animsDisabled) {\n each(newControllers, (controller) => {\n controller.reset();\n });\n }\n this._updateDatasets(mode);\n this.notifyPlugins('afterUpdate', {mode});\n this._layers.sort(compare2Level('z', '_idx'));\n const {_active, _lastEvent} = this;\n if (_lastEvent) {\n this._eventHandler(_lastEvent, true);\n } else if (_active.length) {\n this._updateHoverStyles(_active, _active, true);\n }\n this.render();\n }\n _updateScales() {\n each(this.scales, (scale) => {\n layouts.removeBox(this, scale);\n });\n this.ensureScalesHaveIDs();\n this.buildOrUpdateScales();\n }\n _checkEventBindings() {\n const options = this.options;\n const existingEvents = new Set(Object.keys(this._listeners));\n const newEvents = new Set(options.events);\n if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {\n this.unbindEvents();\n this.bindEvents();\n }\n }\n _updateHiddenIndices() {\n const {_hiddenIndices} = this;\n const changes = this._getUniformDataChanges() || [];\n for (const {method, start, count} of changes) {\n const move = method === '_removeElements' ? -count : count;\n moveNumericKeys(_hiddenIndices, start, move);\n }\n }\n _getUniformDataChanges() {\n const _dataChanges = this._dataChanges;\n if (!_dataChanges || !_dataChanges.length) {\n return;\n }\n this._dataChanges = [];\n const datasetCount = this.data.datasets.length;\n const makeSet = (idx) => new Set(\n _dataChanges\n .filter(c => c[0] === idx)\n .map((c, i) => i + ',' + c.splice(1).join(','))\n );\n const changeSet = makeSet(0);\n for (let i = 1; i < datasetCount; i++) {\n if (!setsEqual(changeSet, makeSet(i))) {\n return;\n }\n }\n return Array.from(changeSet)\n .map(c => c.split(','))\n .map(a => ({method: a[1], start: +a[2], count: +a[3]}));\n }\n _updateLayout(minPadding) {\n if (this.notifyPlugins('beforeLayout', {cancelable: true}) === false) {\n return;\n }\n layouts.update(this, this.width, this.height, minPadding);\n const area = this.chartArea;\n const noArea = area.width <= 0 || area.height <= 0;\n this._layers = [];\n each(this.boxes, (box) => {\n if (noArea && box.position === 'chartArea') {\n return;\n }\n if (box.configure) {\n box.configure();\n }\n this._layers.push(...box._layers());\n }, this);\n this._layers.forEach((item, index) => {\n item._idx = index;\n });\n this.notifyPlugins('afterLayout');\n }\n _updateDatasets(mode) {\n if (this.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) {\n return;\n }\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this.getDatasetMeta(i).controller.configure();\n }\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this._updateDataset(i, isFunction(mode) ? mode({datasetIndex: i}) : mode);\n }\n this.notifyPlugins('afterDatasetsUpdate', {mode});\n }\n _updateDataset(index, mode) {\n const meta = this.getDatasetMeta(index);\n const args = {meta, index, mode, cancelable: true};\n if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {\n return;\n }\n meta.controller._update(mode);\n args.cancelable = false;\n this.notifyPlugins('afterDatasetUpdate', args);\n }\n render() {\n if (this.notifyPlugins('beforeRender', {cancelable: true}) === false) {\n return;\n }\n if (animator.has(this)) {\n if (this.attached && !animator.running(this)) {\n animator.start(this);\n }\n } else {\n this.draw();\n onAnimationsComplete({chart: this});\n }\n }\n draw() {\n let i;\n if (this._resizeBeforeDraw) {\n const {width, height} = this._resizeBeforeDraw;\n this._resize(width, height);\n this._resizeBeforeDraw = null;\n }\n this.clear();\n if (this.width <= 0 || this.height <= 0) {\n return;\n }\n if (this.notifyPlugins('beforeDraw', {cancelable: true}) === false) {\n return;\n }\n const layers = this._layers;\n for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {\n layers[i].draw(this.chartArea);\n }\n this._drawDatasets();\n for (; i < layers.length; ++i) {\n layers[i].draw(this.chartArea);\n }\n this.notifyPlugins('afterDraw');\n }\n _getSortedDatasetMetas(filterVisible) {\n const metasets = this._sortedMetasets;\n const result = [];\n let i, ilen;\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n const meta = metasets[i];\n if (!filterVisible || meta.visible) {\n result.push(meta);\n }\n }\n return result;\n }\n getSortedVisibleDatasetMetas() {\n return this._getSortedDatasetMetas(true);\n }\n _drawDatasets() {\n if (this.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) {\n return;\n }\n const metasets = this.getSortedVisibleDatasetMetas();\n for (let i = metasets.length - 1; i >= 0; --i) {\n this._drawDataset(metasets[i]);\n }\n this.notifyPlugins('afterDatasetsDraw');\n }\n _drawDataset(meta) {\n const ctx = this.ctx;\n const clip = meta._clip;\n const useClip = !clip.disabled;\n const area = this.chartArea;\n const args = {\n meta,\n index: meta.index,\n cancelable: true\n };\n if (this.notifyPlugins('beforeDatasetDraw', args) === false) {\n return;\n }\n if (useClip) {\n clipArea(ctx, {\n left: clip.left === false ? 0 : area.left - clip.left,\n right: clip.right === false ? this.width : area.right + clip.right,\n top: clip.top === false ? 0 : area.top - clip.top,\n bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom\n });\n }\n meta.controller.draw();\n if (useClip) {\n unclipArea(ctx);\n }\n args.cancelable = false;\n this.notifyPlugins('afterDatasetDraw', args);\n }\n getElementsAtEventForMode(e, mode, options, useFinalPosition) {\n const method = Interaction.modes[mode];\n if (typeof method === 'function') {\n return method(this, e, options, useFinalPosition);\n }\n return [];\n }\n getDatasetMeta(datasetIndex) {\n const dataset = this.data.datasets[datasetIndex];\n const metasets = this._metasets;\n let meta = metasets.filter(x => x && x._dataset === dataset).pop();\n if (!meta) {\n meta = {\n type: null,\n data: [],\n dataset: null,\n controller: null,\n hidden: null,\n xAxisID: null,\n yAxisID: null,\n order: dataset && dataset.order || 0,\n index: datasetIndex,\n _dataset: dataset,\n _parsed: [],\n _sorted: false\n };\n metasets.push(meta);\n }\n return meta;\n }\n getContext() {\n return this.$context || (this.$context = createContext(null, {chart: this, type: 'chart'}));\n }\n getVisibleDatasetCount() {\n return this.getSortedVisibleDatasetMetas().length;\n }\n isDatasetVisible(datasetIndex) {\n const dataset = this.data.datasets[datasetIndex];\n if (!dataset) {\n return false;\n }\n const meta = this.getDatasetMeta(datasetIndex);\n return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;\n }\n setDatasetVisibility(datasetIndex, visible) {\n const meta = this.getDatasetMeta(datasetIndex);\n meta.hidden = !visible;\n }\n toggleDataVisibility(index) {\n this._hiddenIndices[index] = !this._hiddenIndices[index];\n }\n getDataVisibility(index) {\n return !this._hiddenIndices[index];\n }\n _updateVisibility(datasetIndex, dataIndex, visible) {\n const mode = visible ? 'show' : 'hide';\n const meta = this.getDatasetMeta(datasetIndex);\n const anims = meta.controller._resolveAnimations(undefined, mode);\n if (defined(dataIndex)) {\n meta.data[dataIndex].hidden = !visible;\n this.update();\n } else {\n this.setDatasetVisibility(datasetIndex, visible);\n anims.update(meta, {visible});\n this.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined);\n }\n }\n hide(datasetIndex, dataIndex) {\n this._updateVisibility(datasetIndex, dataIndex, false);\n }\n show(datasetIndex, dataIndex) {\n this._updateVisibility(datasetIndex, dataIndex, true);\n }\n _destroyDatasetMeta(datasetIndex) {\n const meta = this._metasets[datasetIndex];\n if (meta && meta.controller) {\n meta.controller._destroy();\n }\n delete this._metasets[datasetIndex];\n }\n _stop() {\n let i, ilen;\n this.stop();\n animator.remove(this);\n for (i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this._destroyDatasetMeta(i);\n }\n }\n destroy() {\n this.notifyPlugins('beforeDestroy');\n const {canvas, ctx} = this;\n this._stop();\n this.config.clearCache();\n if (canvas) {\n this.unbindEvents();\n clearCanvas(canvas, ctx);\n this.platform.releaseContext(ctx);\n this.canvas = null;\n this.ctx = null;\n }\n this.notifyPlugins('destroy');\n delete instances[this.id];\n this.notifyPlugins('afterDestroy');\n }\n toBase64Image(...args) {\n return this.canvas.toDataURL(...args);\n }\n bindEvents() {\n this.bindUserEvents();\n if (this.options.responsive) {\n this.bindResponsiveEvents();\n } else {\n this.attached = true;\n }\n }\n bindUserEvents() {\n const listeners = this._listeners;\n const platform = this.platform;\n const _add = (type, listener) => {\n platform.addEventListener(this, type, listener);\n listeners[type] = listener;\n };\n const listener = (e, x, y) => {\n e.offsetX = x;\n e.offsetY = y;\n this._eventHandler(e);\n };\n each(this.options.events, (type) => _add(type, listener));\n }\n bindResponsiveEvents() {\n if (!this._responsiveListeners) {\n this._responsiveListeners = {};\n }\n const listeners = this._responsiveListeners;\n const platform = this.platform;\n const _add = (type, listener) => {\n platform.addEventListener(this, type, listener);\n listeners[type] = listener;\n };\n const _remove = (type, listener) => {\n if (listeners[type]) {\n platform.removeEventListener(this, type, listener);\n delete listeners[type];\n }\n };\n const listener = (width, height) => {\n if (this.canvas) {\n this.resize(width, height);\n }\n };\n let detached;\n const attached = () => {\n _remove('attach', attached);\n this.attached = true;\n this.resize();\n _add('resize', listener);\n _add('detach', detached);\n };\n detached = () => {\n this.attached = false;\n _remove('resize', listener);\n this._stop();\n this._resize(0, 0);\n _add('attach', attached);\n };\n if (platform.isAttached(this.canvas)) {\n attached();\n } else {\n detached();\n }\n }\n unbindEvents() {\n each(this._listeners, (listener, type) => {\n this.platform.removeEventListener(this, type, listener);\n });\n this._listeners = {};\n each(this._responsiveListeners, (listener, type) => {\n this.platform.removeEventListener(this, type, listener);\n });\n this._responsiveListeners = undefined;\n }\n updateHoverStyle(items, mode, enabled) {\n const prefix = enabled ? 'set' : 'remove';\n let meta, item, i, ilen;\n if (mode === 'dataset') {\n meta = this.getDatasetMeta(items[0].datasetIndex);\n meta.controller['_' + prefix + 'DatasetHoverStyle']();\n }\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n item = items[i];\n const controller = item && this.getDatasetMeta(item.datasetIndex).controller;\n if (controller) {\n controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);\n }\n }\n }\n getActiveElements() {\n return this._active || [];\n }\n setActiveElements(activeElements) {\n const lastActive = this._active || [];\n const active = activeElements.map(({datasetIndex, index}) => {\n const meta = this.getDatasetMeta(datasetIndex);\n if (!meta) {\n throw new Error('No dataset found at index ' + datasetIndex);\n }\n return {\n datasetIndex,\n element: meta.data[index],\n index,\n };\n });\n const changed = !_elementsEqual(active, lastActive);\n if (changed) {\n this._active = active;\n this._lastEvent = null;\n this._updateHoverStyles(active, lastActive);\n }\n }\n notifyPlugins(hook, args, filter) {\n return this._plugins.notify(this, hook, args, filter);\n }\n _updateHoverStyles(active, lastActive, replay) {\n const hoverOptions = this.options.hover;\n const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index));\n const deactivated = diff(lastActive, active);\n const activated = replay ? active : diff(active, lastActive);\n if (deactivated.length) {\n this.updateHoverStyle(deactivated, hoverOptions.mode, false);\n }\n if (activated.length && hoverOptions.mode) {\n this.updateHoverStyle(activated, hoverOptions.mode, true);\n }\n }\n _eventHandler(e, replay) {\n const args = {\n event: e,\n replay,\n cancelable: true,\n inChartArea: _isPointInArea(e, this.chartArea, this._minPadding)\n };\n const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.native.type);\n if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {\n return;\n }\n const changed = this._handleEvent(e, replay, args.inChartArea);\n args.cancelable = false;\n this.notifyPlugins('afterEvent', args, eventFilter);\n if (changed || args.changed) {\n this.render();\n }\n return this;\n }\n _handleEvent(e, replay, inChartArea) {\n const {_active: lastActive = [], options} = this;\n const useFinalPosition = replay;\n const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);\n const isClick = _isClickEvent(e);\n const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);\n if (inChartArea) {\n this._lastEvent = null;\n callback(options.onHover, [e, active, this], this);\n if (isClick) {\n callback(options.onClick, [e, active, this], this);\n }\n }\n const changed = !_elementsEqual(active, lastActive);\n if (changed || replay) {\n this._active = active;\n this._updateHoverStyles(active, lastActive, replay);\n }\n this._lastEvent = lastEvent;\n return changed;\n }\n _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {\n if (e.type === 'mouseout') {\n return [];\n }\n if (!inChartArea) {\n return lastActive;\n }\n const hoverOptions = this.options.hover;\n return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);\n }\n}\nconst invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate());\nconst enumerable = true;\nObject.defineProperties(Chart, {\n defaults: {\n enumerable,\n value: defaults\n },\n instances: {\n enumerable,\n value: instances\n },\n overrides: {\n enumerable,\n value: overrides\n },\n registry: {\n enumerable,\n value: registry\n },\n version: {\n enumerable,\n value: version\n },\n getChart: {\n enumerable,\n value: getChart\n },\n register: {\n enumerable,\n value: (...items) => {\n registry.add(...items);\n invalidatePlugins();\n }\n },\n unregister: {\n enumerable,\n value: (...items) => {\n registry.remove(...items);\n invalidatePlugins();\n }\n }\n});\n\nfunction clipArc(ctx, element, endAngle) {\n const {startAngle, pixelMargin, x, y, outerRadius, innerRadius} = element;\n let angleMargin = pixelMargin / outerRadius;\n ctx.beginPath();\n ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);\n if (innerRadius > pixelMargin) {\n angleMargin = pixelMargin / innerRadius;\n ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);\n } else {\n ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);\n }\n ctx.closePath();\n ctx.clip();\n}\nfunction toRadiusCorners(value) {\n return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']);\n}\nfunction parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {\n const o = toRadiusCorners(arc.options.borderRadius);\n const halfThickness = (outerRadius - innerRadius) / 2;\n const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);\n const computeOuterLimit = (val) => {\n const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;\n return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));\n };\n return {\n outerStart: computeOuterLimit(o.outerStart),\n outerEnd: computeOuterLimit(o.outerEnd),\n innerStart: _limitValue(o.innerStart, 0, innerLimit),\n innerEnd: _limitValue(o.innerEnd, 0, innerLimit),\n };\n}\nfunction rThetaToXY(r, theta, x, y) {\n return {\n x: x + r * Math.cos(theta),\n y: y + r * Math.sin(theta),\n };\n}\nfunction pathArc(ctx, element, offset, spacing, end) {\n const {x, y, startAngle: start, pixelMargin, innerRadius: innerR} = element;\n const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);\n const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;\n let spacingOffset = 0;\n const alpha = end - start;\n if (spacing) {\n const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;\n const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;\n const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;\n const adjustedAngle = avNogSpacingRadius !== 0 ? (alpha * avNogSpacingRadius) / (avNogSpacingRadius + spacing) : alpha;\n spacingOffset = (alpha - adjustedAngle) / 2;\n }\n const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;\n const angleOffset = (alpha - beta) / 2;\n const startAngle = start + angleOffset + spacingOffset;\n const endAngle = end - angleOffset - spacingOffset;\n const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);\n const outerStartAdjustedRadius = outerRadius - outerStart;\n const outerEndAdjustedRadius = outerRadius - outerEnd;\n const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;\n const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;\n const innerStartAdjustedRadius = innerRadius + innerStart;\n const innerEndAdjustedRadius = innerRadius + innerEnd;\n const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;\n const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;\n ctx.beginPath();\n ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle);\n if (outerEnd > 0) {\n const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);\n }\n const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);\n ctx.lineTo(p4.x, p4.y);\n if (innerEnd > 0) {\n const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);\n }\n ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), startAngle + (innerStart / innerRadius), true);\n if (innerStart > 0) {\n const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);\n }\n const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);\n ctx.lineTo(p8.x, p8.y);\n if (outerStart > 0) {\n const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);\n }\n ctx.closePath();\n}\nfunction drawArc(ctx, element, offset, spacing) {\n const {fullCircles, startAngle, circumference} = element;\n let endAngle = element.endAngle;\n if (fullCircles) {\n pathArc(ctx, element, offset, spacing, startAngle + TAU);\n for (let i = 0; i < fullCircles; ++i) {\n ctx.fill();\n }\n if (!isNaN(circumference)) {\n endAngle = startAngle + circumference % TAU;\n if (circumference % TAU === 0) {\n endAngle += TAU;\n }\n }\n }\n pathArc(ctx, element, offset, spacing, endAngle);\n ctx.fill();\n return endAngle;\n}\nfunction drawFullCircleBorders(ctx, element, inner) {\n const {x, y, startAngle, pixelMargin, fullCircles} = element;\n const outerRadius = Math.max(element.outerRadius - pixelMargin, 0);\n const innerRadius = element.innerRadius + pixelMargin;\n let i;\n if (inner) {\n clipArc(ctx, element, startAngle + TAU);\n }\n ctx.beginPath();\n ctx.arc(x, y, innerRadius, startAngle + TAU, startAngle, true);\n for (i = 0; i < fullCircles; ++i) {\n ctx.stroke();\n }\n ctx.beginPath();\n ctx.arc(x, y, outerRadius, startAngle, startAngle + TAU);\n for (i = 0; i < fullCircles; ++i) {\n ctx.stroke();\n }\n}\nfunction drawBorder(ctx, element, offset, spacing, endAngle) {\n const {options} = element;\n const {borderWidth, borderJoinStyle} = options;\n const inner = options.borderAlign === 'inner';\n if (!borderWidth) {\n return;\n }\n if (inner) {\n ctx.lineWidth = borderWidth * 2;\n ctx.lineJoin = borderJoinStyle || 'round';\n } else {\n ctx.lineWidth = borderWidth;\n ctx.lineJoin = borderJoinStyle || 'bevel';\n }\n if (element.fullCircles) {\n drawFullCircleBorders(ctx, element, inner);\n }\n if (inner) {\n clipArc(ctx, element, endAngle);\n }\n pathArc(ctx, element, offset, spacing, endAngle);\n ctx.stroke();\n}\nclass ArcElement extends Element {\n constructor(cfg) {\n super();\n this.options = undefined;\n this.circumference = undefined;\n this.startAngle = undefined;\n this.endAngle = undefined;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.pixelMargin = 0;\n this.fullCircles = 0;\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n inRange(chartX, chartY, useFinalPosition) {\n const point = this.getProps(['x', 'y'], useFinalPosition);\n const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY});\n const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([\n 'startAngle',\n 'endAngle',\n 'innerRadius',\n 'outerRadius',\n 'circumference'\n ], useFinalPosition);\n const rAdjust = this.options.spacing / 2;\n const _circumference = valueOrDefault(circumference, endAngle - startAngle);\n const betweenAngles = _circumference >= TAU || _angleBetween(angle, startAngle, endAngle);\n const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);\n return (betweenAngles && withinRadius);\n }\n getCenterPoint(useFinalPosition) {\n const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([\n 'x',\n 'y',\n 'startAngle',\n 'endAngle',\n 'innerRadius',\n 'outerRadius',\n 'circumference',\n ], useFinalPosition);\n const {offset, spacing} = this.options;\n const halfAngle = (startAngle + endAngle) / 2;\n const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;\n return {\n x: x + Math.cos(halfAngle) * halfRadius,\n y: y + Math.sin(halfAngle) * halfRadius\n };\n }\n tooltipPosition(useFinalPosition) {\n return this.getCenterPoint(useFinalPosition);\n }\n draw(ctx) {\n const {options, circumference} = this;\n const offset = (options.offset || 0) / 2;\n const spacing = (options.spacing || 0) / 2;\n this.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0;\n this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;\n if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {\n return;\n }\n ctx.save();\n let radiusOffset = 0;\n if (offset) {\n radiusOffset = offset / 2;\n const halfAngle = (this.startAngle + this.endAngle) / 2;\n ctx.translate(Math.cos(halfAngle) * radiusOffset, Math.sin(halfAngle) * radiusOffset);\n if (this.circumference >= PI) {\n radiusOffset = offset;\n }\n }\n ctx.fillStyle = options.backgroundColor;\n ctx.strokeStyle = options.borderColor;\n const endAngle = drawArc(ctx, this, radiusOffset, spacing);\n drawBorder(ctx, this, radiusOffset, spacing, endAngle);\n ctx.restore();\n }\n}\nArcElement.id = 'arc';\nArcElement.defaults = {\n borderAlign: 'center',\n borderColor: '#fff',\n borderJoinStyle: undefined,\n borderRadius: 0,\n borderWidth: 2,\n offset: 0,\n spacing: 0,\n angle: undefined,\n};\nArcElement.defaultRoutes = {\n backgroundColor: 'backgroundColor'\n};\n\nfunction setStyle(ctx, options, style = options) {\n ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);\n ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));\n ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);\n ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);\n ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);\n ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);\n}\nfunction lineTo(ctx, previous, target) {\n ctx.lineTo(target.x, target.y);\n}\nfunction getLineMethod(options) {\n if (options.stepped) {\n return _steppedLineTo;\n }\n if (options.tension || options.cubicInterpolationMode === 'monotone') {\n return _bezierCurveTo;\n }\n return lineTo;\n}\nfunction pathVars(points, segment, params = {}) {\n const count = points.length;\n const {start: paramsStart = 0, end: paramsEnd = count - 1} = params;\n const {start: segmentStart, end: segmentEnd} = segment;\n const start = Math.max(paramsStart, segmentStart);\n const end = Math.min(paramsEnd, segmentEnd);\n const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;\n return {\n count,\n start,\n loop: segment.loop,\n ilen: end < start && !outside ? count + end - start : end - start\n };\n}\nfunction pathSegment(ctx, line, segment, params) {\n const {points, options} = line;\n const {count, start, loop, ilen} = pathVars(points, segment, params);\n const lineMethod = getLineMethod(options);\n let {move = true, reverse} = params || {};\n let i, point, prev;\n for (i = 0; i <= ilen; ++i) {\n point = points[(start + (reverse ? ilen - i : i)) % count];\n if (point.skip) {\n continue;\n } else if (move) {\n ctx.moveTo(point.x, point.y);\n move = false;\n } else {\n lineMethod(ctx, prev, point, reverse, options.stepped);\n }\n prev = point;\n }\n if (loop) {\n point = points[(start + (reverse ? ilen : 0)) % count];\n lineMethod(ctx, prev, point, reverse, options.stepped);\n }\n return !!loop;\n}\nfunction fastPathSegment(ctx, line, segment, params) {\n const points = line.points;\n const {count, start, ilen} = pathVars(points, segment, params);\n const {move = true, reverse} = params || {};\n let avgX = 0;\n let countX = 0;\n let i, point, prevX, minY, maxY, lastY;\n const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count;\n const drawX = () => {\n if (minY !== maxY) {\n ctx.lineTo(avgX, maxY);\n ctx.lineTo(avgX, minY);\n ctx.lineTo(avgX, lastY);\n }\n };\n if (move) {\n point = points[pointIndex(0)];\n ctx.moveTo(point.x, point.y);\n }\n for (i = 0; i <= ilen; ++i) {\n point = points[pointIndex(i)];\n if (point.skip) {\n continue;\n }\n const x = point.x;\n const y = point.y;\n const truncX = x | 0;\n if (truncX === prevX) {\n if (y < minY) {\n minY = y;\n } else if (y > maxY) {\n maxY = y;\n }\n avgX = (countX * avgX + x) / ++countX;\n } else {\n drawX();\n ctx.lineTo(x, y);\n prevX = truncX;\n countX = 0;\n minY = maxY = y;\n }\n lastY = y;\n }\n drawX();\n}\nfunction _getSegmentMethod(line) {\n const opts = line.options;\n const borderDash = opts.borderDash && opts.borderDash.length;\n const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;\n return useFastPath ? fastPathSegment : pathSegment;\n}\nfunction _getInterpolationMethod(options) {\n if (options.stepped) {\n return _steppedInterpolation;\n }\n if (options.tension || options.cubicInterpolationMode === 'monotone') {\n return _bezierInterpolation;\n }\n return _pointInLine;\n}\nfunction strokePathWithCache(ctx, line, start, count) {\n let path = line._path;\n if (!path) {\n path = line._path = new Path2D();\n if (line.path(path, start, count)) {\n path.closePath();\n }\n }\n setStyle(ctx, line.options);\n ctx.stroke(path);\n}\nfunction strokePathDirect(ctx, line, start, count) {\n const {segments, options} = line;\n const segmentMethod = _getSegmentMethod(line);\n for (const segment of segments) {\n setStyle(ctx, options, segment.style);\n ctx.beginPath();\n if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) {\n ctx.closePath();\n }\n ctx.stroke();\n }\n}\nconst usePath2D = typeof Path2D === 'function';\nfunction draw(ctx, line, start, count) {\n if (usePath2D && !line.options.segment) {\n strokePathWithCache(ctx, line, start, count);\n } else {\n strokePathDirect(ctx, line, start, count);\n }\n}\nclass LineElement extends Element {\n constructor(cfg) {\n super();\n this.animated = true;\n this.options = undefined;\n this._chart = undefined;\n this._loop = undefined;\n this._fullLoop = undefined;\n this._path = undefined;\n this._points = undefined;\n this._segments = undefined;\n this._decimated = false;\n this._pointsUpdated = false;\n this._datasetIndex = undefined;\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n updateControlPoints(chartArea, indexAxis) {\n const options = this.options;\n if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {\n const loop = options.spanGaps ? this._loop : this._fullLoop;\n _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);\n this._pointsUpdated = true;\n }\n }\n set points(points) {\n this._points = points;\n delete this._segments;\n delete this._path;\n this._pointsUpdated = false;\n }\n get points() {\n return this._points;\n }\n get segments() {\n return this._segments || (this._segments = _computeSegments(this, this.options.segment));\n }\n first() {\n const segments = this.segments;\n const points = this.points;\n return segments.length && points[segments[0].start];\n }\n last() {\n const segments = this.segments;\n const points = this.points;\n const count = segments.length;\n return count && points[segments[count - 1].end];\n }\n interpolate(point, property) {\n const options = this.options;\n const value = point[property];\n const points = this.points;\n const segments = _boundSegments(this, {property, start: value, end: value});\n if (!segments.length) {\n return;\n }\n const result = [];\n const _interpolate = _getInterpolationMethod(options);\n let i, ilen;\n for (i = 0, ilen = segments.length; i < ilen; ++i) {\n const {start, end} = segments[i];\n const p1 = points[start];\n const p2 = points[end];\n if (p1 === p2) {\n result.push(p1);\n continue;\n }\n const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));\n const interpolated = _interpolate(p1, p2, t, options.stepped);\n interpolated[property] = point[property];\n result.push(interpolated);\n }\n return result.length === 1 ? result[0] : result;\n }\n pathSegment(ctx, segment, params) {\n const segmentMethod = _getSegmentMethod(this);\n return segmentMethod(ctx, this, segment, params);\n }\n path(ctx, start, count) {\n const segments = this.segments;\n const segmentMethod = _getSegmentMethod(this);\n let loop = this._loop;\n start = start || 0;\n count = count || (this.points.length - start);\n for (const segment of segments) {\n loop &= segmentMethod(ctx, this, segment, {start, end: start + count - 1});\n }\n return !!loop;\n }\n draw(ctx, chartArea, start, count) {\n const options = this.options || {};\n const points = this.points || [];\n if (points.length && options.borderWidth) {\n ctx.save();\n draw(ctx, this, start, count);\n ctx.restore();\n }\n if (this.animated) {\n this._pointsUpdated = false;\n this._path = undefined;\n }\n }\n}\nLineElement.id = 'line';\nLineElement.defaults = {\n borderCapStyle: 'butt',\n borderDash: [],\n borderDashOffset: 0,\n borderJoinStyle: 'miter',\n borderWidth: 3,\n capBezierPoints: true,\n cubicInterpolationMode: 'default',\n fill: false,\n spanGaps: false,\n stepped: false,\n tension: 0,\n};\nLineElement.defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n};\nLineElement.descriptors = {\n _scriptable: true,\n _indexable: (name) => name !== 'borderDash' && name !== 'fill',\n};\n\nfunction inRange$1(el, pos, axis, useFinalPosition) {\n const options = el.options;\n const {[axis]: value} = el.getProps([axis], useFinalPosition);\n return (Math.abs(pos - value) < options.radius + options.hitRadius);\n}\nclass PointElement extends Element {\n constructor(cfg) {\n super();\n this.options = undefined;\n this.parsed = undefined;\n this.skip = undefined;\n this.stop = undefined;\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n inRange(mouseX, mouseY, useFinalPosition) {\n const options = this.options;\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2));\n }\n inXRange(mouseX, useFinalPosition) {\n return inRange$1(this, mouseX, 'x', useFinalPosition);\n }\n inYRange(mouseY, useFinalPosition) {\n return inRange$1(this, mouseY, 'y', useFinalPosition);\n }\n getCenterPoint(useFinalPosition) {\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return {x, y};\n }\n size(options) {\n options = options || this.options || {};\n let radius = options.radius || 0;\n radius = Math.max(radius, radius && options.hoverRadius || 0);\n const borderWidth = radius && options.borderWidth || 0;\n return (radius + borderWidth) * 2;\n }\n draw(ctx, area) {\n const options = this.options;\n if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) {\n return;\n }\n ctx.strokeStyle = options.borderColor;\n ctx.lineWidth = options.borderWidth;\n ctx.fillStyle = options.backgroundColor;\n drawPoint(ctx, options, this.x, this.y);\n }\n getRange() {\n const options = this.options || {};\n return options.radius + options.hitRadius;\n }\n}\nPointElement.id = 'point';\nPointElement.defaults = {\n borderWidth: 1,\n hitRadius: 1,\n hoverBorderWidth: 1,\n hoverRadius: 4,\n pointStyle: 'circle',\n radius: 3,\n rotation: 0\n};\nPointElement.defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n};\n\nfunction getBarBounds(bar, useFinalPosition) {\n const {x, y, base, width, height} = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition);\n let left, right, top, bottom, half;\n if (bar.horizontal) {\n half = height / 2;\n left = Math.min(x, base);\n right = Math.max(x, base);\n top = y - half;\n bottom = y + half;\n } else {\n half = width / 2;\n left = x - half;\n right = x + half;\n top = Math.min(y, base);\n bottom = Math.max(y, base);\n }\n return {left, top, right, bottom};\n}\nfunction skipOrLimit(skip, value, min, max) {\n return skip ? 0 : _limitValue(value, min, max);\n}\nfunction parseBorderWidth(bar, maxW, maxH) {\n const value = bar.options.borderWidth;\n const skip = bar.borderSkipped;\n const o = toTRBL(value);\n return {\n t: skipOrLimit(skip.top, o.top, 0, maxH),\n r: skipOrLimit(skip.right, o.right, 0, maxW),\n b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),\n l: skipOrLimit(skip.left, o.left, 0, maxW)\n };\n}\nfunction parseBorderRadius(bar, maxW, maxH) {\n const {enableBorderRadius} = bar.getProps(['enableBorderRadius']);\n const value = bar.options.borderRadius;\n const o = toTRBLCorners(value);\n const maxR = Math.min(maxW, maxH);\n const skip = bar.borderSkipped;\n const enableBorder = enableBorderRadius || isObject(value);\n return {\n topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),\n topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),\n bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),\n bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)\n };\n}\nfunction boundingRects(bar) {\n const bounds = getBarBounds(bar);\n const width = bounds.right - bounds.left;\n const height = bounds.bottom - bounds.top;\n const border = parseBorderWidth(bar, width / 2, height / 2);\n const radius = parseBorderRadius(bar, width / 2, height / 2);\n return {\n outer: {\n x: bounds.left,\n y: bounds.top,\n w: width,\n h: height,\n radius\n },\n inner: {\n x: bounds.left + border.l,\n y: bounds.top + border.t,\n w: width - border.l - border.r,\n h: height - border.t - border.b,\n radius: {\n topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),\n topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),\n bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),\n bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)),\n }\n }\n };\n}\nfunction inRange(bar, x, y, useFinalPosition) {\n const skipX = x === null;\n const skipY = y === null;\n const skipBoth = skipX && skipY;\n const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);\n return bounds\n\t\t&& (skipX || _isBetween(x, bounds.left, bounds.right))\n\t\t&& (skipY || _isBetween(y, bounds.top, bounds.bottom));\n}\nfunction hasRadius(radius) {\n return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;\n}\nfunction addNormalRectPath(ctx, rect) {\n ctx.rect(rect.x, rect.y, rect.w, rect.h);\n}\nfunction inflateRect(rect, amount, refRect = {}) {\n const x = rect.x !== refRect.x ? -amount : 0;\n const y = rect.y !== refRect.y ? -amount : 0;\n const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;\n const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;\n return {\n x: rect.x + x,\n y: rect.y + y,\n w: rect.w + w,\n h: rect.h + h,\n radius: rect.radius\n };\n}\nclass BarElement extends Element {\n constructor(cfg) {\n super();\n this.options = undefined;\n this.horizontal = undefined;\n this.base = undefined;\n this.width = undefined;\n this.height = undefined;\n this.inflateAmount = undefined;\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n draw(ctx) {\n const {inflateAmount, options: {borderColor, backgroundColor}} = this;\n const {inner, outer} = boundingRects(this);\n const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;\n ctx.save();\n if (outer.w !== inner.w || outer.h !== inner.h) {\n ctx.beginPath();\n addRectPath(ctx, inflateRect(outer, inflateAmount, inner));\n ctx.clip();\n addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));\n ctx.fillStyle = borderColor;\n ctx.fill('evenodd');\n }\n ctx.beginPath();\n addRectPath(ctx, inflateRect(inner, inflateAmount));\n ctx.fillStyle = backgroundColor;\n ctx.fill();\n ctx.restore();\n }\n inRange(mouseX, mouseY, useFinalPosition) {\n return inRange(this, mouseX, mouseY, useFinalPosition);\n }\n inXRange(mouseX, useFinalPosition) {\n return inRange(this, mouseX, null, useFinalPosition);\n }\n inYRange(mouseY, useFinalPosition) {\n return inRange(this, null, mouseY, useFinalPosition);\n }\n getCenterPoint(useFinalPosition) {\n const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition);\n return {\n x: horizontal ? (x + base) / 2 : x,\n y: horizontal ? y : (y + base) / 2\n };\n }\n getRange(axis) {\n return axis === 'x' ? this.width / 2 : this.height / 2;\n }\n}\nBarElement.id = 'bar';\nBarElement.defaults = {\n borderSkipped: 'start',\n borderWidth: 0,\n borderRadius: 0,\n inflateAmount: 'auto',\n pointStyle: undefined\n};\nBarElement.defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n};\n\nvar elements = /*#__PURE__*/Object.freeze({\n__proto__: null,\nArcElement: ArcElement,\nLineElement: LineElement,\nPointElement: PointElement,\nBarElement: BarElement\n});\n\nfunction lttbDecimation(data, start, count, availableWidth, options) {\n const samples = options.samples || availableWidth;\n if (samples >= count) {\n return data.slice(start, start + count);\n }\n const decimated = [];\n const bucketWidth = (count - 2) / (samples - 2);\n let sampledIndex = 0;\n const endIndex = start + count - 1;\n let a = start;\n let i, maxAreaPoint, maxArea, area, nextA;\n decimated[sampledIndex++] = data[a];\n for (i = 0; i < samples - 2; i++) {\n let avgX = 0;\n let avgY = 0;\n let j;\n const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;\n const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;\n const avgRangeLength = avgRangeEnd - avgRangeStart;\n for (j = avgRangeStart; j < avgRangeEnd; j++) {\n avgX += data[j].x;\n avgY += data[j].y;\n }\n avgX /= avgRangeLength;\n avgY /= avgRangeLength;\n const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;\n const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;\n const {x: pointAx, y: pointAy} = data[a];\n maxArea = area = -1;\n for (j = rangeOffs; j < rangeTo; j++) {\n area = 0.5 * Math.abs(\n (pointAx - avgX) * (data[j].y - pointAy) -\n (pointAx - data[j].x) * (avgY - pointAy)\n );\n if (area > maxArea) {\n maxArea = area;\n maxAreaPoint = data[j];\n nextA = j;\n }\n }\n decimated[sampledIndex++] = maxAreaPoint;\n a = nextA;\n }\n decimated[sampledIndex++] = data[endIndex];\n return decimated;\n}\nfunction minMaxDecimation(data, start, count, availableWidth) {\n let avgX = 0;\n let countX = 0;\n let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;\n const decimated = [];\n const endIndex = start + count - 1;\n const xMin = data[start].x;\n const xMax = data[endIndex].x;\n const dx = xMax - xMin;\n for (i = start; i < start + count; ++i) {\n point = data[i];\n x = (point.x - xMin) / dx * availableWidth;\n y = point.y;\n const truncX = x | 0;\n if (truncX === prevX) {\n if (y < minY) {\n minY = y;\n minIndex = i;\n } else if (y > maxY) {\n maxY = y;\n maxIndex = i;\n }\n avgX = (countX * avgX + point.x) / ++countX;\n } else {\n const lastIndex = i - 1;\n if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {\n const intermediateIndex1 = Math.min(minIndex, maxIndex);\n const intermediateIndex2 = Math.max(minIndex, maxIndex);\n if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {\n decimated.push({\n ...data[intermediateIndex1],\n x: avgX,\n });\n }\n if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {\n decimated.push({\n ...data[intermediateIndex2],\n x: avgX\n });\n }\n }\n if (i > 0 && lastIndex !== startIndex) {\n decimated.push(data[lastIndex]);\n }\n decimated.push(point);\n prevX = truncX;\n countX = 0;\n minY = maxY = y;\n minIndex = maxIndex = startIndex = i;\n }\n }\n return decimated;\n}\nfunction cleanDecimatedDataset(dataset) {\n if (dataset._decimated) {\n const data = dataset._data;\n delete dataset._decimated;\n delete dataset._data;\n Object.defineProperty(dataset, 'data', {value: data});\n }\n}\nfunction cleanDecimatedData(chart) {\n chart.data.datasets.forEach((dataset) => {\n cleanDecimatedDataset(dataset);\n });\n}\nfunction getStartAndCountOfVisiblePointsSimplified(meta, points) {\n const pointCount = points.length;\n let start = 0;\n let count;\n const {iScale} = meta;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n if (minDefined) {\n start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);\n }\n if (maxDefined) {\n count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n return {start, count};\n}\nvar plugin_decimation = {\n id: 'decimation',\n defaults: {\n algorithm: 'min-max',\n enabled: false,\n },\n beforeElementsUpdate: (chart, args, options) => {\n if (!options.enabled) {\n cleanDecimatedData(chart);\n return;\n }\n const availableWidth = chart.width;\n chart.data.datasets.forEach((dataset, datasetIndex) => {\n const {_data, indexAxis} = dataset;\n const meta = chart.getDatasetMeta(datasetIndex);\n const data = _data || dataset.data;\n if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {\n return;\n }\n if (meta.type !== 'line') {\n return;\n }\n const xAxis = chart.scales[meta.xAxisID];\n if (xAxis.type !== 'linear' && xAxis.type !== 'time') {\n return;\n }\n if (chart.options.parsing) {\n return;\n }\n let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data);\n const threshold = options.threshold || 4 * availableWidth;\n if (count <= threshold) {\n cleanDecimatedDataset(dataset);\n return;\n }\n if (isNullOrUndef(_data)) {\n dataset._data = data;\n delete dataset.data;\n Object.defineProperty(dataset, 'data', {\n configurable: true,\n enumerable: true,\n get: function() {\n return this._decimated;\n },\n set: function(d) {\n this._data = d;\n }\n });\n }\n let decimated;\n switch (options.algorithm) {\n case 'lttb':\n decimated = lttbDecimation(data, start, count, availableWidth, options);\n break;\n case 'min-max':\n decimated = minMaxDecimation(data, start, count, availableWidth);\n break;\n default:\n throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);\n }\n dataset._decimated = decimated;\n });\n },\n destroy(chart) {\n cleanDecimatedData(chart);\n }\n};\n\nfunction getLineByIndex(chart, index) {\n const meta = chart.getDatasetMeta(index);\n const visible = meta && chart.isDatasetVisible(index);\n return visible ? meta.dataset : null;\n}\nfunction parseFillOption(line) {\n const options = line.options;\n const fillOption = options.fill;\n let fill = valueOrDefault(fillOption && fillOption.target, fillOption);\n if (fill === undefined) {\n fill = !!options.backgroundColor;\n }\n if (fill === false || fill === null) {\n return false;\n }\n if (fill === true) {\n return 'origin';\n }\n return fill;\n}\nfunction decodeFill(line, index, count) {\n const fill = parseFillOption(line);\n if (isObject(fill)) {\n return isNaN(fill.value) ? false : fill;\n }\n let target = parseFloat(fill);\n if (isNumberFinite(target) && Math.floor(target) === target) {\n if (fill[0] === '-' || fill[0] === '+') {\n target = index + target;\n }\n if (target === index || target < 0 || target >= count) {\n return false;\n }\n return target;\n }\n return ['origin', 'start', 'end', 'stack', 'shape'].indexOf(fill) >= 0 && fill;\n}\nfunction computeLinearBoundary(source) {\n const {scale = {}, fill} = source;\n let target = null;\n let horizontal;\n if (fill === 'start') {\n target = scale.bottom;\n } else if (fill === 'end') {\n target = scale.top;\n } else if (isObject(fill)) {\n target = scale.getPixelForValue(fill.value);\n } else if (scale.getBasePixel) {\n target = scale.getBasePixel();\n }\n if (isNumberFinite(target)) {\n horizontal = scale.isHorizontal();\n return {\n x: horizontal ? target : null,\n y: horizontal ? null : target\n };\n }\n return null;\n}\nclass simpleArc {\n constructor(opts) {\n this.x = opts.x;\n this.y = opts.y;\n this.radius = opts.radius;\n }\n pathSegment(ctx, bounds, opts) {\n const {x, y, radius} = this;\n bounds = bounds || {start: 0, end: TAU};\n ctx.arc(x, y, radius, bounds.end, bounds.start, true);\n return !opts.bounds;\n }\n interpolate(point) {\n const {x, y, radius} = this;\n const angle = point.angle;\n return {\n x: x + Math.cos(angle) * radius,\n y: y + Math.sin(angle) * radius,\n angle\n };\n }\n}\nfunction computeCircularBoundary(source) {\n const {scale, fill} = source;\n const options = scale.options;\n const length = scale.getLabels().length;\n const target = [];\n const start = options.reverse ? scale.max : scale.min;\n const end = options.reverse ? scale.min : scale.max;\n let i, center, value;\n if (fill === 'start') {\n value = start;\n } else if (fill === 'end') {\n value = end;\n } else if (isObject(fill)) {\n value = fill.value;\n } else {\n value = scale.getBaseValue();\n }\n if (options.grid.circular) {\n center = scale.getPointPositionForValue(0, start);\n return new simpleArc({\n x: center.x,\n y: center.y,\n radius: scale.getDistanceFromCenterForValue(value)\n });\n }\n for (i = 0; i < length; ++i) {\n target.push(scale.getPointPositionForValue(i, value));\n }\n return target;\n}\nfunction computeBoundary(source) {\n const scale = source.scale || {};\n if (scale.getPointPositionForValue) {\n return computeCircularBoundary(source);\n }\n return computeLinearBoundary(source);\n}\nfunction findSegmentEnd(start, end, points) {\n for (;end > start; end--) {\n const point = points[end];\n if (!isNaN(point.x) && !isNaN(point.y)) {\n break;\n }\n }\n return end;\n}\nfunction pointsFromSegments(boundary, line) {\n const {x = null, y = null} = boundary || {};\n const linePoints = line.points;\n const points = [];\n line.segments.forEach(({start, end}) => {\n end = findSegmentEnd(start, end, linePoints);\n const first = linePoints[start];\n const last = linePoints[end];\n if (y !== null) {\n points.push({x: first.x, y});\n points.push({x: last.x, y});\n } else if (x !== null) {\n points.push({x, y: first.y});\n points.push({x, y: last.y});\n }\n });\n return points;\n}\nfunction buildStackLine(source) {\n const {scale, index, line} = source;\n const points = [];\n const segments = line.segments;\n const sourcePoints = line.points;\n const linesBelow = getLinesBelow(scale, index);\n linesBelow.push(createBoundaryLine({x: null, y: scale.bottom}, line));\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n for (let j = segment.start; j <= segment.end; j++) {\n addPointsBelow(points, sourcePoints[j], linesBelow);\n }\n }\n return new LineElement({points, options: {}});\n}\nfunction getLinesBelow(scale, index) {\n const below = [];\n const metas = scale.getMatchingVisibleMetas('line');\n for (let i = 0; i < metas.length; i++) {\n const meta = metas[i];\n if (meta.index === index) {\n break;\n }\n if (!meta.hidden) {\n below.unshift(meta.dataset);\n }\n }\n return below;\n}\nfunction addPointsBelow(points, sourcePoint, linesBelow) {\n const postponed = [];\n for (let j = 0; j < linesBelow.length; j++) {\n const line = linesBelow[j];\n const {first, last, point} = findPoint(line, sourcePoint, 'x');\n if (!point || (first && last)) {\n continue;\n }\n if (first) {\n postponed.unshift(point);\n } else {\n points.push(point);\n if (!last) {\n break;\n }\n }\n }\n points.push(...postponed);\n}\nfunction findPoint(line, sourcePoint, property) {\n const point = line.interpolate(sourcePoint, property);\n if (!point) {\n return {};\n }\n const pointValue = point[property];\n const segments = line.segments;\n const linePoints = line.points;\n let first = false;\n let last = false;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const firstValue = linePoints[segment.start][property];\n const lastValue = linePoints[segment.end][property];\n if (_isBetween(pointValue, firstValue, lastValue)) {\n first = pointValue === firstValue;\n last = pointValue === lastValue;\n break;\n }\n }\n return {first, last, point};\n}\nfunction getTarget(source) {\n const {chart, fill, line} = source;\n if (isNumberFinite(fill)) {\n return getLineByIndex(chart, fill);\n }\n if (fill === 'stack') {\n return buildStackLine(source);\n }\n if (fill === 'shape') {\n return true;\n }\n const boundary = computeBoundary(source);\n if (boundary instanceof simpleArc) {\n return boundary;\n }\n return createBoundaryLine(boundary, line);\n}\nfunction createBoundaryLine(boundary, line) {\n let points = [];\n let _loop = false;\n if (isArray(boundary)) {\n _loop = true;\n points = boundary;\n } else {\n points = pointsFromSegments(boundary, line);\n }\n return points.length ? new LineElement({\n points,\n options: {tension: 0},\n _loop,\n _fullLoop: _loop\n }) : null;\n}\nfunction resolveTarget(sources, index, propagate) {\n const source = sources[index];\n let fill = source.fill;\n const visited = [index];\n let target;\n if (!propagate) {\n return fill;\n }\n while (fill !== false && visited.indexOf(fill) === -1) {\n if (!isNumberFinite(fill)) {\n return fill;\n }\n target = sources[fill];\n if (!target) {\n return false;\n }\n if (target.visible) {\n return fill;\n }\n visited.push(fill);\n fill = target.fill;\n }\n return false;\n}\nfunction _clip(ctx, target, clipY) {\n const {segments, points} = target;\n let first = true;\n let lineLoop = false;\n ctx.beginPath();\n for (const segment of segments) {\n const {start, end} = segment;\n const firstPoint = points[start];\n const lastPoint = points[findSegmentEnd(start, end, points)];\n if (first) {\n ctx.moveTo(firstPoint.x, firstPoint.y);\n first = false;\n } else {\n ctx.lineTo(firstPoint.x, clipY);\n ctx.lineTo(firstPoint.x, firstPoint.y);\n }\n lineLoop = !!target.pathSegment(ctx, segment, {move: lineLoop});\n if (lineLoop) {\n ctx.closePath();\n } else {\n ctx.lineTo(lastPoint.x, clipY);\n }\n }\n ctx.lineTo(target.first().x, clipY);\n ctx.closePath();\n ctx.clip();\n}\nfunction getBounds(property, first, last, loop) {\n if (loop) {\n return;\n }\n let start = first[property];\n let end = last[property];\n if (property === 'angle') {\n start = _normalizeAngle(start);\n end = _normalizeAngle(end);\n }\n return {property, start, end};\n}\nfunction _getEdge(a, b, prop, fn) {\n if (a && b) {\n return fn(a[prop], b[prop]);\n }\n return a ? a[prop] : b ? b[prop] : 0;\n}\nfunction _segments(line, target, property) {\n const segments = line.segments;\n const points = line.points;\n const tpoints = target.points;\n const parts = [];\n for (const segment of segments) {\n let {start, end} = segment;\n end = findSegmentEnd(start, end, points);\n const bounds = getBounds(property, points[start], points[end], segment.loop);\n if (!target.segments) {\n parts.push({\n source: segment,\n target: bounds,\n start: points[start],\n end: points[end]\n });\n continue;\n }\n const targetSegments = _boundSegments(target, bounds);\n for (const tgt of targetSegments) {\n const subBounds = getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);\n const fillSources = _boundSegment(segment, points, subBounds);\n for (const fillSource of fillSources) {\n parts.push({\n source: fillSource,\n target: tgt,\n start: {\n [property]: _getEdge(bounds, subBounds, 'start', Math.max)\n },\n end: {\n [property]: _getEdge(bounds, subBounds, 'end', Math.min)\n }\n });\n }\n }\n }\n return parts;\n}\nfunction clipBounds(ctx, scale, bounds) {\n const {top, bottom} = scale.chart.chartArea;\n const {property, start, end} = bounds || {};\n if (property === 'x') {\n ctx.beginPath();\n ctx.rect(start, top, end - start, bottom - top);\n ctx.clip();\n }\n}\nfunction interpolatedLineTo(ctx, target, point, property) {\n const interpolatedPoint = target.interpolate(point, property);\n if (interpolatedPoint) {\n ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);\n }\n}\nfunction _fill(ctx, cfg) {\n const {line, target, property, color, scale} = cfg;\n const segments = _segments(line, target, property);\n for (const {source: src, target: tgt, start, end} of segments) {\n const {style: {backgroundColor = color} = {}} = src;\n const notShape = target !== true;\n ctx.save();\n ctx.fillStyle = backgroundColor;\n clipBounds(ctx, scale, notShape && getBounds(property, start, end));\n ctx.beginPath();\n const lineLoop = !!line.pathSegment(ctx, src);\n let loop;\n if (notShape) {\n if (lineLoop) {\n ctx.closePath();\n } else {\n interpolatedLineTo(ctx, target, end, property);\n }\n const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true});\n loop = lineLoop && targetLoop;\n if (!loop) {\n interpolatedLineTo(ctx, target, start, property);\n }\n }\n ctx.closePath();\n ctx.fill(loop ? 'evenodd' : 'nonzero');\n ctx.restore();\n }\n}\nfunction doFill(ctx, cfg) {\n const {line, target, above, below, area, scale} = cfg;\n const property = line._loop ? 'angle' : cfg.axis;\n ctx.save();\n if (property === 'x' && below !== above) {\n _clip(ctx, target, area.top);\n _fill(ctx, {line, target, color: above, scale, property});\n ctx.restore();\n ctx.save();\n _clip(ctx, target, area.bottom);\n }\n _fill(ctx, {line, target, color: below, scale, property});\n ctx.restore();\n}\nfunction drawfill(ctx, source, area) {\n const target = getTarget(source);\n const {line, scale, axis} = source;\n const lineOpts = line.options;\n const fillOption = lineOpts.fill;\n const color = lineOpts.backgroundColor;\n const {above = color, below = color} = fillOption || {};\n if (target && line.points.length) {\n clipArea(ctx, area);\n doFill(ctx, {line, target, above, below, area, scale, axis});\n unclipArea(ctx);\n }\n}\nvar plugin_filler = {\n id: 'filler',\n afterDatasetsUpdate(chart, _args, options) {\n const count = (chart.data.datasets || []).length;\n const sources = [];\n let meta, i, line, source;\n for (i = 0; i < count; ++i) {\n meta = chart.getDatasetMeta(i);\n line = meta.dataset;\n source = null;\n if (line && line.options && line instanceof LineElement) {\n source = {\n visible: chart.isDatasetVisible(i),\n index: i,\n fill: decodeFill(line, i, count),\n chart,\n axis: meta.controller.options.indexAxis,\n scale: meta.vScale,\n line,\n };\n }\n meta.$filler = source;\n sources.push(source);\n }\n for (i = 0; i < count; ++i) {\n source = sources[i];\n if (!source || source.fill === false) {\n continue;\n }\n source.fill = resolveTarget(sources, i, options.propagate);\n }\n },\n beforeDraw(chart, _args, options) {\n const draw = options.drawTime === 'beforeDraw';\n const metasets = chart.getSortedVisibleDatasetMetas();\n const area = chart.chartArea;\n for (let i = metasets.length - 1; i >= 0; --i) {\n const source = metasets[i].$filler;\n if (!source) {\n continue;\n }\n source.line.updateControlPoints(area, source.axis);\n if (draw) {\n drawfill(chart.ctx, source, area);\n }\n }\n },\n beforeDatasetsDraw(chart, _args, options) {\n if (options.drawTime !== 'beforeDatasetsDraw') {\n return;\n }\n const metasets = chart.getSortedVisibleDatasetMetas();\n for (let i = metasets.length - 1; i >= 0; --i) {\n const source = metasets[i].$filler;\n if (source) {\n drawfill(chart.ctx, source, chart.chartArea);\n }\n }\n },\n beforeDatasetDraw(chart, args, options) {\n const source = args.meta.$filler;\n if (!source || source.fill === false || options.drawTime !== 'beforeDatasetDraw') {\n return;\n }\n drawfill(chart.ctx, source, chart.chartArea);\n },\n defaults: {\n propagate: true,\n drawTime: 'beforeDatasetDraw'\n }\n};\n\nconst getBoxSize = (labelOpts, fontSize) => {\n let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts;\n if (labelOpts.usePointStyle) {\n boxHeight = Math.min(boxHeight, fontSize);\n boxWidth = Math.min(boxWidth, fontSize);\n }\n return {\n boxWidth,\n boxHeight,\n itemHeight: Math.max(fontSize, boxHeight)\n };\n};\nconst itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;\nclass Legend extends Element {\n constructor(config) {\n super();\n this._added = false;\n this.legendHitBoxes = [];\n this._hoveredItem = null;\n this.doughnutMode = false;\n this.chart = config.chart;\n this.options = config.options;\n this.ctx = config.ctx;\n this.legendItems = undefined;\n this.columnSizes = undefined;\n this.lineWidths = undefined;\n this.maxHeight = undefined;\n this.maxWidth = undefined;\n this.top = undefined;\n this.bottom = undefined;\n this.left = undefined;\n this.right = undefined;\n this.height = undefined;\n this.width = undefined;\n this._margins = undefined;\n this.position = undefined;\n this.weight = undefined;\n this.fullSize = undefined;\n }\n update(maxWidth, maxHeight, margins) {\n this.maxWidth = maxWidth;\n this.maxHeight = maxHeight;\n this._margins = margins;\n this.setDimensions();\n this.buildLabels();\n this.fit();\n }\n setDimensions() {\n if (this.isHorizontal()) {\n this.width = this.maxWidth;\n this.left = this._margins.left;\n this.right = this.width;\n } else {\n this.height = this.maxHeight;\n this.top = this._margins.top;\n this.bottom = this.height;\n }\n }\n buildLabels() {\n const labelOpts = this.options.labels || {};\n let legendItems = callback(labelOpts.generateLabels, [this.chart], this) || [];\n if (labelOpts.filter) {\n legendItems = legendItems.filter((item) => labelOpts.filter(item, this.chart.data));\n }\n if (labelOpts.sort) {\n legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, this.chart.data));\n }\n if (this.options.reverse) {\n legendItems.reverse();\n }\n this.legendItems = legendItems;\n }\n fit() {\n const {options, ctx} = this;\n if (!options.display) {\n this.width = this.height = 0;\n return;\n }\n const labelOpts = options.labels;\n const labelFont = toFont(labelOpts.font);\n const fontSize = labelFont.size;\n const titleHeight = this._computeTitleHeight();\n const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize);\n let width, height;\n ctx.font = labelFont.string;\n if (this.isHorizontal()) {\n width = this.maxWidth;\n height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;\n } else {\n height = this.maxHeight;\n width = this._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10;\n }\n this.width = Math.min(width, options.maxWidth || this.maxWidth);\n this.height = Math.min(height, options.maxHeight || this.maxHeight);\n }\n _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {\n const {ctx, maxWidth, options: {labels: {padding}}} = this;\n const hitboxes = this.legendHitBoxes = [];\n const lineWidths = this.lineWidths = [0];\n const lineHeight = itemHeight + padding;\n let totalHeight = titleHeight;\n ctx.textAlign = 'left';\n ctx.textBaseline = 'middle';\n let row = -1;\n let top = -lineHeight;\n this.legendItems.forEach((legendItem, i) => {\n const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;\n if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {\n totalHeight += lineHeight;\n lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;\n top += lineHeight;\n row++;\n }\n hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight};\n lineWidths[lineWidths.length - 1] += itemWidth + padding;\n });\n return totalHeight;\n }\n _fitCols(titleHeight, fontSize, boxWidth, itemHeight) {\n const {ctx, maxHeight, options: {labels: {padding}}} = this;\n const hitboxes = this.legendHitBoxes = [];\n const columnSizes = this.columnSizes = [];\n const heightLimit = maxHeight - titleHeight;\n let totalWidth = padding;\n let currentColWidth = 0;\n let currentColHeight = 0;\n let left = 0;\n let col = 0;\n this.legendItems.forEach((legendItem, i) => {\n const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;\n if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {\n totalWidth += currentColWidth + padding;\n columnSizes.push({width: currentColWidth, height: currentColHeight});\n left += currentColWidth + padding;\n col++;\n currentColWidth = currentColHeight = 0;\n }\n hitboxes[i] = {left, top: currentColHeight, col, width: itemWidth, height: itemHeight};\n currentColWidth = Math.max(currentColWidth, itemWidth);\n currentColHeight += itemHeight + padding;\n });\n totalWidth += currentColWidth;\n columnSizes.push({width: currentColWidth, height: currentColHeight});\n return totalWidth;\n }\n adjustHitBoxes() {\n if (!this.options.display) {\n return;\n }\n const titleHeight = this._computeTitleHeight();\n const {legendHitBoxes: hitboxes, options: {align, labels: {padding}, rtl}} = this;\n const rtlHelper = getRtlAdapter(rtl, this.left, this.width);\n if (this.isHorizontal()) {\n let row = 0;\n let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);\n for (const hitbox of hitboxes) {\n if (row !== hitbox.row) {\n row = hitbox.row;\n left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);\n }\n hitbox.top += this.top + titleHeight + padding;\n hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);\n left += hitbox.width + padding;\n }\n } else {\n let col = 0;\n let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);\n for (const hitbox of hitboxes) {\n if (hitbox.col !== col) {\n col = hitbox.col;\n top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);\n }\n hitbox.top = top;\n hitbox.left += this.left + padding;\n hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);\n top += hitbox.height + padding;\n }\n }\n }\n isHorizontal() {\n return this.options.position === 'top' || this.options.position === 'bottom';\n }\n draw() {\n if (this.options.display) {\n const ctx = this.ctx;\n clipArea(ctx, this);\n this._draw();\n unclipArea(ctx);\n }\n }\n _draw() {\n const {options: opts, columnSizes, lineWidths, ctx} = this;\n const {align, labels: labelOpts} = opts;\n const defaultColor = defaults.color;\n const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);\n const labelFont = toFont(labelOpts.font);\n const {color: fontColor, padding} = labelOpts;\n const fontSize = labelFont.size;\n const halfFontSize = fontSize / 2;\n let cursor;\n this.drawTitle();\n ctx.textAlign = rtlHelper.textAlign('left');\n ctx.textBaseline = 'middle';\n ctx.lineWidth = 0.5;\n ctx.font = labelFont.string;\n const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize);\n const drawLegendBox = function(x, y, legendItem) {\n if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {\n return;\n }\n ctx.save();\n const lineWidth = valueOrDefault(legendItem.lineWidth, 1);\n ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);\n ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');\n ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);\n ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');\n ctx.lineWidth = lineWidth;\n ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);\n ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));\n if (labelOpts.usePointStyle) {\n const drawOptions = {\n radius: boxWidth * Math.SQRT2 / 2,\n pointStyle: legendItem.pointStyle,\n rotation: legendItem.rotation,\n borderWidth: lineWidth\n };\n const centerX = rtlHelper.xPlus(x, boxWidth / 2);\n const centerY = y + halfFontSize;\n drawPoint(ctx, drawOptions, centerX, centerY);\n } else {\n const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);\n const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);\n const borderRadius = toTRBLCorners(legendItem.borderRadius);\n ctx.beginPath();\n if (Object.values(borderRadius).some(v => v !== 0)) {\n addRoundedRectPath(ctx, {\n x: xBoxLeft,\n y: yBoxTop,\n w: boxWidth,\n h: boxHeight,\n radius: borderRadius,\n });\n } else {\n ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);\n }\n ctx.fill();\n if (lineWidth !== 0) {\n ctx.stroke();\n }\n }\n ctx.restore();\n };\n const fillText = function(x, y, legendItem) {\n renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, {\n strikethrough: legendItem.hidden,\n textAlign: rtlHelper.textAlign(legendItem.textAlign)\n });\n };\n const isHorizontal = this.isHorizontal();\n const titleHeight = this._computeTitleHeight();\n if (isHorizontal) {\n cursor = {\n x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),\n y: this.top + padding + titleHeight,\n line: 0\n };\n } else {\n cursor = {\n x: this.left + padding,\n y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),\n line: 0\n };\n }\n overrideTextDirection(this.ctx, opts.textDirection);\n const lineHeight = itemHeight + padding;\n this.legendItems.forEach((legendItem, i) => {\n ctx.strokeStyle = legendItem.fontColor || fontColor;\n ctx.fillStyle = legendItem.fontColor || fontColor;\n const textWidth = ctx.measureText(legendItem.text).width;\n const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));\n const width = boxWidth + halfFontSize + textWidth;\n let x = cursor.x;\n let y = cursor.y;\n rtlHelper.setWidth(this.width);\n if (isHorizontal) {\n if (i > 0 && x + width + padding > this.right) {\n y = cursor.y += lineHeight;\n cursor.line++;\n x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);\n }\n } else if (i > 0 && y + lineHeight > this.bottom) {\n x = cursor.x = x + columnSizes[cursor.line].width + padding;\n cursor.line++;\n y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);\n }\n const realX = rtlHelper.x(x);\n drawLegendBox(realX, y, legendItem);\n x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);\n fillText(rtlHelper.x(x), y, legendItem);\n if (isHorizontal) {\n cursor.x += width + padding;\n } else {\n cursor.y += lineHeight;\n }\n });\n restoreTextDirection(this.ctx, opts.textDirection);\n }\n drawTitle() {\n const opts = this.options;\n const titleOpts = opts.title;\n const titleFont = toFont(titleOpts.font);\n const titlePadding = toPadding(titleOpts.padding);\n if (!titleOpts.display) {\n return;\n }\n const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);\n const ctx = this.ctx;\n const position = titleOpts.position;\n const halfFontSize = titleFont.size / 2;\n const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;\n let y;\n let left = this.left;\n let maxWidth = this.width;\n if (this.isHorizontal()) {\n maxWidth = Math.max(...this.lineWidths);\n y = this.top + topPaddingPlusHalfFontSize;\n left = _alignStartEnd(opts.align, left, this.right - maxWidth);\n } else {\n const maxHeight = this.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0);\n y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());\n }\n const x = _alignStartEnd(position, left, left + maxWidth);\n ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));\n ctx.textBaseline = 'middle';\n ctx.strokeStyle = titleOpts.color;\n ctx.fillStyle = titleOpts.color;\n ctx.font = titleFont.string;\n renderText(ctx, titleOpts.text, x, y, titleFont);\n }\n _computeTitleHeight() {\n const titleOpts = this.options.title;\n const titleFont = toFont(titleOpts.font);\n const titlePadding = toPadding(titleOpts.padding);\n return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;\n }\n _getLegendItemAt(x, y) {\n let i, hitBox, lh;\n if (_isBetween(x, this.left, this.right)\n && _isBetween(y, this.top, this.bottom)) {\n lh = this.legendHitBoxes;\n for (i = 0; i < lh.length; ++i) {\n hitBox = lh[i];\n if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width)\n && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {\n return this.legendItems[i];\n }\n }\n }\n return null;\n }\n handleEvent(e) {\n const opts = this.options;\n if (!isListened(e.type, opts)) {\n return;\n }\n const hoveredItem = this._getLegendItemAt(e.x, e.y);\n if (e.type === 'mousemove') {\n const previous = this._hoveredItem;\n const sameItem = itemsEqual(previous, hoveredItem);\n if (previous && !sameItem) {\n callback(opts.onLeave, [e, previous, this], this);\n }\n this._hoveredItem = hoveredItem;\n if (hoveredItem && !sameItem) {\n callback(opts.onHover, [e, hoveredItem, this], this);\n }\n } else if (hoveredItem) {\n callback(opts.onClick, [e, hoveredItem, this], this);\n }\n }\n}\nfunction isListened(type, opts) {\n if (type === 'mousemove' && (opts.onHover || opts.onLeave)) {\n return true;\n }\n if (opts.onClick && (type === 'click' || type === 'mouseup')) {\n return true;\n }\n return false;\n}\nvar plugin_legend = {\n id: 'legend',\n _element: Legend,\n start(chart, _args, options) {\n const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart});\n layouts.configure(chart, legend, options);\n layouts.addBox(chart, legend);\n },\n stop(chart) {\n layouts.removeBox(chart, chart.legend);\n delete chart.legend;\n },\n beforeUpdate(chart, _args, options) {\n const legend = chart.legend;\n layouts.configure(chart, legend, options);\n legend.options = options;\n },\n afterUpdate(chart) {\n const legend = chart.legend;\n legend.buildLabels();\n legend.adjustHitBoxes();\n },\n afterEvent(chart, args) {\n if (!args.replay) {\n chart.legend.handleEvent(args.event);\n }\n },\n defaults: {\n display: true,\n position: 'top',\n align: 'center',\n fullSize: true,\n reverse: false,\n weight: 1000,\n onClick(e, legendItem, legend) {\n const index = legendItem.datasetIndex;\n const ci = legend.chart;\n if (ci.isDatasetVisible(index)) {\n ci.hide(index);\n legendItem.hidden = true;\n } else {\n ci.show(index);\n legendItem.hidden = false;\n }\n },\n onHover: null,\n onLeave: null,\n labels: {\n color: (ctx) => ctx.chart.options.color,\n boxWidth: 40,\n padding: 10,\n generateLabels(chart) {\n const datasets = chart.data.datasets;\n const {labels: {usePointStyle, pointStyle, textAlign, color}} = chart.legend.options;\n return chart._getSortedDatasetMetas().map((meta) => {\n const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);\n const borderWidth = toPadding(style.borderWidth);\n return {\n text: datasets[meta.index].label,\n fillStyle: style.backgroundColor,\n fontColor: color,\n hidden: !meta.visible,\n lineCap: style.borderCapStyle,\n lineDash: style.borderDash,\n lineDashOffset: style.borderDashOffset,\n lineJoin: style.borderJoinStyle,\n lineWidth: (borderWidth.width + borderWidth.height) / 4,\n strokeStyle: style.borderColor,\n pointStyle: pointStyle || style.pointStyle,\n rotation: style.rotation,\n textAlign: textAlign || style.textAlign,\n borderRadius: 0,\n datasetIndex: meta.index\n };\n }, this);\n }\n },\n title: {\n color: (ctx) => ctx.chart.options.color,\n display: false,\n position: 'center',\n text: '',\n }\n },\n descriptors: {\n _scriptable: (name) => !name.startsWith('on'),\n labels: {\n _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name),\n }\n },\n};\n\nclass Title extends Element {\n constructor(config) {\n super();\n this.chart = config.chart;\n this.options = config.options;\n this.ctx = config.ctx;\n this._padding = undefined;\n this.top = undefined;\n this.bottom = undefined;\n this.left = undefined;\n this.right = undefined;\n this.width = undefined;\n this.height = undefined;\n this.position = undefined;\n this.weight = undefined;\n this.fullSize = undefined;\n }\n update(maxWidth, maxHeight) {\n const opts = this.options;\n this.left = 0;\n this.top = 0;\n if (!opts.display) {\n this.width = this.height = this.right = this.bottom = 0;\n return;\n }\n this.width = this.right = maxWidth;\n this.height = this.bottom = maxHeight;\n const lineCount = isArray(opts.text) ? opts.text.length : 1;\n this._padding = toPadding(opts.padding);\n const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height;\n if (this.isHorizontal()) {\n this.height = textSize;\n } else {\n this.width = textSize;\n }\n }\n isHorizontal() {\n const pos = this.options.position;\n return pos === 'top' || pos === 'bottom';\n }\n _drawArgs(offset) {\n const {top, left, bottom, right, options} = this;\n const align = options.align;\n let rotation = 0;\n let maxWidth, titleX, titleY;\n if (this.isHorizontal()) {\n titleX = _alignStartEnd(align, left, right);\n titleY = top + offset;\n maxWidth = right - left;\n } else {\n if (options.position === 'left') {\n titleX = left + offset;\n titleY = _alignStartEnd(align, bottom, top);\n rotation = PI * -0.5;\n } else {\n titleX = right - offset;\n titleY = _alignStartEnd(align, top, bottom);\n rotation = PI * 0.5;\n }\n maxWidth = bottom - top;\n }\n return {titleX, titleY, maxWidth, rotation};\n }\n draw() {\n const ctx = this.ctx;\n const opts = this.options;\n if (!opts.display) {\n return;\n }\n const fontOpts = toFont(opts.font);\n const lineHeight = fontOpts.lineHeight;\n const offset = lineHeight / 2 + this._padding.top;\n const {titleX, titleY, maxWidth, rotation} = this._drawArgs(offset);\n renderText(ctx, opts.text, 0, 0, fontOpts, {\n color: opts.color,\n maxWidth,\n rotation,\n textAlign: _toLeftRightCenter(opts.align),\n textBaseline: 'middle',\n translation: [titleX, titleY],\n });\n }\n}\nfunction createTitle(chart, titleOpts) {\n const title = new Title({\n ctx: chart.ctx,\n options: titleOpts,\n chart\n });\n layouts.configure(chart, title, titleOpts);\n layouts.addBox(chart, title);\n chart.titleBlock = title;\n}\nvar plugin_title = {\n id: 'title',\n _element: Title,\n start(chart, _args, options) {\n createTitle(chart, options);\n },\n stop(chart) {\n const titleBlock = chart.titleBlock;\n layouts.removeBox(chart, titleBlock);\n delete chart.titleBlock;\n },\n beforeUpdate(chart, _args, options) {\n const title = chart.titleBlock;\n layouts.configure(chart, title, options);\n title.options = options;\n },\n defaults: {\n align: 'center',\n display: false,\n font: {\n weight: 'bold',\n },\n fullSize: true,\n padding: 10,\n position: 'top',\n text: '',\n weight: 2000\n },\n defaultRoutes: {\n color: 'color'\n },\n descriptors: {\n _scriptable: true,\n _indexable: false,\n },\n};\n\nconst map = new WeakMap();\nvar plugin_subtitle = {\n id: 'subtitle',\n start(chart, _args, options) {\n const title = new Title({\n ctx: chart.ctx,\n options,\n chart\n });\n layouts.configure(chart, title, options);\n layouts.addBox(chart, title);\n map.set(chart, title);\n },\n stop(chart) {\n layouts.removeBox(chart, map.get(chart));\n map.delete(chart);\n },\n beforeUpdate(chart, _args, options) {\n const title = map.get(chart);\n layouts.configure(chart, title, options);\n title.options = options;\n },\n defaults: {\n align: 'center',\n display: false,\n font: {\n weight: 'normal',\n },\n fullSize: true,\n padding: 0,\n position: 'top',\n text: '',\n weight: 1500\n },\n defaultRoutes: {\n color: 'color'\n },\n descriptors: {\n _scriptable: true,\n _indexable: false,\n },\n};\n\nconst positioners = {\n average(items) {\n if (!items.length) {\n return false;\n }\n let i, len;\n let x = 0;\n let y = 0;\n let count = 0;\n for (i = 0, len = items.length; i < len; ++i) {\n const el = items[i].element;\n if (el && el.hasValue()) {\n const pos = el.tooltipPosition();\n x += pos.x;\n y += pos.y;\n ++count;\n }\n }\n return {\n x: x / count,\n y: y / count\n };\n },\n nearest(items, eventPosition) {\n if (!items.length) {\n return false;\n }\n let x = eventPosition.x;\n let y = eventPosition.y;\n let minDistance = Number.POSITIVE_INFINITY;\n let i, len, nearestElement;\n for (i = 0, len = items.length; i < len; ++i) {\n const el = items[i].element;\n if (el && el.hasValue()) {\n const center = el.getCenterPoint();\n const d = distanceBetweenPoints(eventPosition, center);\n if (d < minDistance) {\n minDistance = d;\n nearestElement = el;\n }\n }\n }\n if (nearestElement) {\n const tp = nearestElement.tooltipPosition();\n x = tp.x;\n y = tp.y;\n }\n return {\n x,\n y\n };\n }\n};\nfunction pushOrConcat(base, toPush) {\n if (toPush) {\n if (isArray(toPush)) {\n Array.prototype.push.apply(base, toPush);\n } else {\n base.push(toPush);\n }\n }\n return base;\n}\nfunction splitNewlines(str) {\n if ((typeof str === 'string' || str instanceof String) && str.indexOf('\\n') > -1) {\n return str.split('\\n');\n }\n return str;\n}\nfunction createTooltipItem(chart, item) {\n const {element, datasetIndex, index} = item;\n const controller = chart.getDatasetMeta(datasetIndex).controller;\n const {label, value} = controller.getLabelAndValue(index);\n return {\n chart,\n label,\n parsed: controller.getParsed(index),\n raw: chart.data.datasets[datasetIndex].data[index],\n formattedValue: value,\n dataset: controller.getDataset(),\n dataIndex: index,\n datasetIndex,\n element\n };\n}\nfunction getTooltipSize(tooltip, options) {\n const ctx = tooltip.chart.ctx;\n const {body, footer, title} = tooltip;\n const {boxWidth, boxHeight} = options;\n const bodyFont = toFont(options.bodyFont);\n const titleFont = toFont(options.titleFont);\n const footerFont = toFont(options.footerFont);\n const titleLineCount = title.length;\n const footerLineCount = footer.length;\n const bodyLineItemCount = body.length;\n const padding = toPadding(options.padding);\n let height = padding.height;\n let width = 0;\n let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);\n combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;\n if (titleLineCount) {\n height += titleLineCount * titleFont.lineHeight\n\t\t\t+ (titleLineCount - 1) * options.titleSpacing\n\t\t\t+ options.titleMarginBottom;\n }\n if (combinedBodyLength) {\n const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;\n height += bodyLineItemCount * bodyLineHeight\n\t\t\t+ (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight\n\t\t\t+ (combinedBodyLength - 1) * options.bodySpacing;\n }\n if (footerLineCount) {\n height += options.footerMarginTop\n\t\t\t+ footerLineCount * footerFont.lineHeight\n\t\t\t+ (footerLineCount - 1) * options.footerSpacing;\n }\n let widthPadding = 0;\n const maxLineWidth = function(line) {\n width = Math.max(width, ctx.measureText(line).width + widthPadding);\n };\n ctx.save();\n ctx.font = titleFont.string;\n each(tooltip.title, maxLineWidth);\n ctx.font = bodyFont.string;\n each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);\n widthPadding = options.displayColors ? (boxWidth + 2 + options.boxPadding) : 0;\n each(body, (bodyItem) => {\n each(bodyItem.before, maxLineWidth);\n each(bodyItem.lines, maxLineWidth);\n each(bodyItem.after, maxLineWidth);\n });\n widthPadding = 0;\n ctx.font = footerFont.string;\n each(tooltip.footer, maxLineWidth);\n ctx.restore();\n width += padding.width;\n return {width, height};\n}\nfunction determineYAlign(chart, size) {\n const {y, height} = size;\n if (y < height / 2) {\n return 'top';\n } else if (y > (chart.height - height / 2)) {\n return 'bottom';\n }\n return 'center';\n}\nfunction doesNotFitWithAlign(xAlign, chart, options, size) {\n const {x, width} = size;\n const caret = options.caretSize + options.caretPadding;\n if (xAlign === 'left' && x + width + caret > chart.width) {\n return true;\n }\n if (xAlign === 'right' && x - width - caret < 0) {\n return true;\n }\n}\nfunction determineXAlign(chart, options, size, yAlign) {\n const {x, width} = size;\n const {width: chartWidth, chartArea: {left, right}} = chart;\n let xAlign = 'center';\n if (yAlign === 'center') {\n xAlign = x <= (left + right) / 2 ? 'left' : 'right';\n } else if (x <= width / 2) {\n xAlign = 'left';\n } else if (x >= chartWidth - width / 2) {\n xAlign = 'right';\n }\n if (doesNotFitWithAlign(xAlign, chart, options, size)) {\n xAlign = 'center';\n }\n return xAlign;\n}\nfunction determineAlignment(chart, options, size) {\n const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);\n return {\n xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),\n yAlign\n };\n}\nfunction alignX(size, xAlign) {\n let {x, width} = size;\n if (xAlign === 'right') {\n x -= width;\n } else if (xAlign === 'center') {\n x -= (width / 2);\n }\n return x;\n}\nfunction alignY(size, yAlign, paddingAndSize) {\n let {y, height} = size;\n if (yAlign === 'top') {\n y += paddingAndSize;\n } else if (yAlign === 'bottom') {\n y -= height + paddingAndSize;\n } else {\n y -= (height / 2);\n }\n return y;\n}\nfunction getBackgroundPoint(options, size, alignment, chart) {\n const {caretSize, caretPadding, cornerRadius} = options;\n const {xAlign, yAlign} = alignment;\n const paddingAndSize = caretSize + caretPadding;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius);\n let x = alignX(size, xAlign);\n const y = alignY(size, yAlign, paddingAndSize);\n if (yAlign === 'center') {\n if (xAlign === 'left') {\n x += paddingAndSize;\n } else if (xAlign === 'right') {\n x -= paddingAndSize;\n }\n } else if (xAlign === 'left') {\n x -= Math.max(topLeft, bottomLeft) + caretSize;\n } else if (xAlign === 'right') {\n x += Math.max(topRight, bottomRight) + caretSize;\n }\n return {\n x: _limitValue(x, 0, chart.width - size.width),\n y: _limitValue(y, 0, chart.height - size.height)\n };\n}\nfunction getAlignedX(tooltip, align, options) {\n const padding = toPadding(options.padding);\n return align === 'center'\n ? tooltip.x + tooltip.width / 2\n : align === 'right'\n ? tooltip.x + tooltip.width - padding.right\n : tooltip.x + padding.left;\n}\nfunction getBeforeAfterBodyLines(callback) {\n return pushOrConcat([], splitNewlines(callback));\n}\nfunction createTooltipContext(parent, tooltip, tooltipItems) {\n return createContext(parent, {\n tooltip,\n tooltipItems,\n type: 'tooltip'\n });\n}\nfunction overrideCallbacks(callbacks, context) {\n const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;\n return override ? callbacks.override(override) : callbacks;\n}\nclass Tooltip extends Element {\n constructor(config) {\n super();\n this.opacity = 0;\n this._active = [];\n this._eventPosition = undefined;\n this._size = undefined;\n this._cachedAnimations = undefined;\n this._tooltipItems = [];\n this.$animations = undefined;\n this.$context = undefined;\n this.chart = config.chart || config._chart;\n this._chart = this.chart;\n this.options = config.options;\n this.dataPoints = undefined;\n this.title = undefined;\n this.beforeBody = undefined;\n this.body = undefined;\n this.afterBody = undefined;\n this.footer = undefined;\n this.xAlign = undefined;\n this.yAlign = undefined;\n this.x = undefined;\n this.y = undefined;\n this.height = undefined;\n this.width = undefined;\n this.caretX = undefined;\n this.caretY = undefined;\n this.labelColors = undefined;\n this.labelPointStyles = undefined;\n this.labelTextColors = undefined;\n }\n initialize(options) {\n this.options = options;\n this._cachedAnimations = undefined;\n this.$context = undefined;\n }\n _resolveAnimations() {\n const cached = this._cachedAnimations;\n if (cached) {\n return cached;\n }\n const chart = this.chart;\n const options = this.options.setContext(this.getContext());\n const opts = options.enabled && chart.options.animation && options.animations;\n const animations = new Animations(this.chart, opts);\n if (opts._cacheable) {\n this._cachedAnimations = Object.freeze(animations);\n }\n return animations;\n }\n getContext() {\n return this.$context ||\n\t\t\t(this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));\n }\n getTitle(context, options) {\n const {callbacks} = options;\n const beforeTitle = callbacks.beforeTitle.apply(this, [context]);\n const title = callbacks.title.apply(this, [context]);\n const afterTitle = callbacks.afterTitle.apply(this, [context]);\n let lines = [];\n lines = pushOrConcat(lines, splitNewlines(beforeTitle));\n lines = pushOrConcat(lines, splitNewlines(title));\n lines = pushOrConcat(lines, splitNewlines(afterTitle));\n return lines;\n }\n getBeforeBody(tooltipItems, options) {\n return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems]));\n }\n getBody(tooltipItems, options) {\n const {callbacks} = options;\n const bodyItems = [];\n each(tooltipItems, (context) => {\n const bodyItem = {\n before: [],\n lines: [],\n after: []\n };\n const scoped = overrideCallbacks(callbacks, context);\n pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(this, context)));\n pushOrConcat(bodyItem.lines, scoped.label.call(this, context));\n pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(this, context)));\n bodyItems.push(bodyItem);\n });\n return bodyItems;\n }\n getAfterBody(tooltipItems, options) {\n return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems]));\n }\n getFooter(tooltipItems, options) {\n const {callbacks} = options;\n const beforeFooter = callbacks.beforeFooter.apply(this, [tooltipItems]);\n const footer = callbacks.footer.apply(this, [tooltipItems]);\n const afterFooter = callbacks.afterFooter.apply(this, [tooltipItems]);\n let lines = [];\n lines = pushOrConcat(lines, splitNewlines(beforeFooter));\n lines = pushOrConcat(lines, splitNewlines(footer));\n lines = pushOrConcat(lines, splitNewlines(afterFooter));\n return lines;\n }\n _createItems(options) {\n const active = this._active;\n const data = this.chart.data;\n const labelColors = [];\n const labelPointStyles = [];\n const labelTextColors = [];\n let tooltipItems = [];\n let i, len;\n for (i = 0, len = active.length; i < len; ++i) {\n tooltipItems.push(createTooltipItem(this.chart, active[i]));\n }\n if (options.filter) {\n tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data));\n }\n if (options.itemSort) {\n tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data));\n }\n each(tooltipItems, (context) => {\n const scoped = overrideCallbacks(options.callbacks, context);\n labelColors.push(scoped.labelColor.call(this, context));\n labelPointStyles.push(scoped.labelPointStyle.call(this, context));\n labelTextColors.push(scoped.labelTextColor.call(this, context));\n });\n this.labelColors = labelColors;\n this.labelPointStyles = labelPointStyles;\n this.labelTextColors = labelTextColors;\n this.dataPoints = tooltipItems;\n return tooltipItems;\n }\n update(changed, replay) {\n const options = this.options.setContext(this.getContext());\n const active = this._active;\n let properties;\n let tooltipItems = [];\n if (!active.length) {\n if (this.opacity !== 0) {\n properties = {\n opacity: 0\n };\n }\n } else {\n const position = positioners[options.position].call(this, active, this._eventPosition);\n tooltipItems = this._createItems(options);\n this.title = this.getTitle(tooltipItems, options);\n this.beforeBody = this.getBeforeBody(tooltipItems, options);\n this.body = this.getBody(tooltipItems, options);\n this.afterBody = this.getAfterBody(tooltipItems, options);\n this.footer = this.getFooter(tooltipItems, options);\n const size = this._size = getTooltipSize(this, options);\n const positionAndSize = Object.assign({}, position, size);\n const alignment = determineAlignment(this.chart, options, positionAndSize);\n const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);\n this.xAlign = alignment.xAlign;\n this.yAlign = alignment.yAlign;\n properties = {\n opacity: 1,\n x: backgroundPoint.x,\n y: backgroundPoint.y,\n width: size.width,\n height: size.height,\n caretX: position.x,\n caretY: position.y\n };\n }\n this._tooltipItems = tooltipItems;\n this.$context = undefined;\n if (properties) {\n this._resolveAnimations().update(this, properties);\n }\n if (changed && options.external) {\n options.external.call(this, {chart: this.chart, tooltip: this, replay});\n }\n }\n drawCaret(tooltipPoint, ctx, size, options) {\n const caretPosition = this.getCaretPosition(tooltipPoint, size, options);\n ctx.lineTo(caretPosition.x1, caretPosition.y1);\n ctx.lineTo(caretPosition.x2, caretPosition.y2);\n ctx.lineTo(caretPosition.x3, caretPosition.y3);\n }\n getCaretPosition(tooltipPoint, size, options) {\n const {xAlign, yAlign} = this;\n const {caretSize, cornerRadius} = options;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius);\n const {x: ptX, y: ptY} = tooltipPoint;\n const {width, height} = size;\n let x1, x2, x3, y1, y2, y3;\n if (yAlign === 'center') {\n y2 = ptY + (height / 2);\n if (xAlign === 'left') {\n x1 = ptX;\n x2 = x1 - caretSize;\n y1 = y2 + caretSize;\n y3 = y2 - caretSize;\n } else {\n x1 = ptX + width;\n x2 = x1 + caretSize;\n y1 = y2 - caretSize;\n y3 = y2 + caretSize;\n }\n x3 = x1;\n } else {\n if (xAlign === 'left') {\n x2 = ptX + Math.max(topLeft, bottomLeft) + (caretSize);\n } else if (xAlign === 'right') {\n x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;\n } else {\n x2 = this.caretX;\n }\n if (yAlign === 'top') {\n y1 = ptY;\n y2 = y1 - caretSize;\n x1 = x2 - caretSize;\n x3 = x2 + caretSize;\n } else {\n y1 = ptY + height;\n y2 = y1 + caretSize;\n x1 = x2 + caretSize;\n x3 = x2 - caretSize;\n }\n y3 = y1;\n }\n return {x1, x2, x3, y1, y2, y3};\n }\n drawTitle(pt, ctx, options) {\n const title = this.title;\n const length = title.length;\n let titleFont, titleSpacing, i;\n if (length) {\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n pt.x = getAlignedX(this, options.titleAlign, options);\n ctx.textAlign = rtlHelper.textAlign(options.titleAlign);\n ctx.textBaseline = 'middle';\n titleFont = toFont(options.titleFont);\n titleSpacing = options.titleSpacing;\n ctx.fillStyle = options.titleColor;\n ctx.font = titleFont.string;\n for (i = 0; i < length; ++i) {\n ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);\n pt.y += titleFont.lineHeight + titleSpacing;\n if (i + 1 === length) {\n pt.y += options.titleMarginBottom - titleSpacing;\n }\n }\n }\n }\n _drawColorBox(ctx, pt, i, rtlHelper, options) {\n const labelColors = this.labelColors[i];\n const labelPointStyle = this.labelPointStyles[i];\n const {boxHeight, boxWidth, boxPadding} = options;\n const bodyFont = toFont(options.bodyFont);\n const colorX = getAlignedX(this, 'left', options);\n const rtlColorX = rtlHelper.x(colorX);\n const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;\n const colorY = pt.y + yOffSet;\n if (options.usePointStyle) {\n const drawOptions = {\n radius: Math.min(boxWidth, boxHeight) / 2,\n pointStyle: labelPointStyle.pointStyle,\n rotation: labelPointStyle.rotation,\n borderWidth: 1\n };\n const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;\n const centerY = colorY + boxHeight / 2;\n ctx.strokeStyle = options.multiKeyBackground;\n ctx.fillStyle = options.multiKeyBackground;\n drawPoint(ctx, drawOptions, centerX, centerY);\n ctx.strokeStyle = labelColors.borderColor;\n ctx.fillStyle = labelColors.backgroundColor;\n drawPoint(ctx, drawOptions, centerX, centerY);\n } else {\n ctx.lineWidth = labelColors.borderWidth || 1;\n ctx.strokeStyle = labelColors.borderColor;\n ctx.setLineDash(labelColors.borderDash || []);\n ctx.lineDashOffset = labelColors.borderDashOffset || 0;\n const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth - boxPadding);\n const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - boxPadding - 2);\n const borderRadius = toTRBLCorners(labelColors.borderRadius);\n if (Object.values(borderRadius).some(v => v !== 0)) {\n ctx.beginPath();\n ctx.fillStyle = options.multiKeyBackground;\n addRoundedRectPath(ctx, {\n x: outerX,\n y: colorY,\n w: boxWidth,\n h: boxHeight,\n radius: borderRadius,\n });\n ctx.fill();\n ctx.stroke();\n ctx.fillStyle = labelColors.backgroundColor;\n ctx.beginPath();\n addRoundedRectPath(ctx, {\n x: innerX,\n y: colorY + 1,\n w: boxWidth - 2,\n h: boxHeight - 2,\n radius: borderRadius,\n });\n ctx.fill();\n } else {\n ctx.fillStyle = options.multiKeyBackground;\n ctx.fillRect(outerX, colorY, boxWidth, boxHeight);\n ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);\n ctx.fillStyle = labelColors.backgroundColor;\n ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);\n }\n }\n ctx.fillStyle = this.labelTextColors[i];\n }\n drawBody(pt, ctx, options) {\n const {body} = this;\n const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth, boxPadding} = options;\n const bodyFont = toFont(options.bodyFont);\n let bodyLineHeight = bodyFont.lineHeight;\n let xLinePadding = 0;\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n const fillLineOfText = function(line) {\n ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);\n pt.y += bodyLineHeight + bodySpacing;\n };\n const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);\n let bodyItem, textColor, lines, i, j, ilen, jlen;\n ctx.textAlign = bodyAlign;\n ctx.textBaseline = 'middle';\n ctx.font = bodyFont.string;\n pt.x = getAlignedX(this, bodyAlignForCalculation, options);\n ctx.fillStyle = options.bodyColor;\n each(this.beforeBody, fillLineOfText);\n xLinePadding = displayColors && bodyAlignForCalculation !== 'right'\n ? bodyAlign === 'center' ? (boxWidth / 2 + boxPadding) : (boxWidth + 2 + boxPadding)\n : 0;\n for (i = 0, ilen = body.length; i < ilen; ++i) {\n bodyItem = body[i];\n textColor = this.labelTextColors[i];\n ctx.fillStyle = textColor;\n each(bodyItem.before, fillLineOfText);\n lines = bodyItem.lines;\n if (displayColors && lines.length) {\n this._drawColorBox(ctx, pt, i, rtlHelper, options);\n bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);\n }\n for (j = 0, jlen = lines.length; j < jlen; ++j) {\n fillLineOfText(lines[j]);\n bodyLineHeight = bodyFont.lineHeight;\n }\n each(bodyItem.after, fillLineOfText);\n }\n xLinePadding = 0;\n bodyLineHeight = bodyFont.lineHeight;\n each(this.afterBody, fillLineOfText);\n pt.y -= bodySpacing;\n }\n drawFooter(pt, ctx, options) {\n const footer = this.footer;\n const length = footer.length;\n let footerFont, i;\n if (length) {\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n pt.x = getAlignedX(this, options.footerAlign, options);\n pt.y += options.footerMarginTop;\n ctx.textAlign = rtlHelper.textAlign(options.footerAlign);\n ctx.textBaseline = 'middle';\n footerFont = toFont(options.footerFont);\n ctx.fillStyle = options.footerColor;\n ctx.font = footerFont.string;\n for (i = 0; i < length; ++i) {\n ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);\n pt.y += footerFont.lineHeight + options.footerSpacing;\n }\n }\n }\n drawBackground(pt, ctx, tooltipSize, options) {\n const {xAlign, yAlign} = this;\n const {x, y} = pt;\n const {width, height} = tooltipSize;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(options.cornerRadius);\n ctx.fillStyle = options.backgroundColor;\n ctx.strokeStyle = options.borderColor;\n ctx.lineWidth = options.borderWidth;\n ctx.beginPath();\n ctx.moveTo(x + topLeft, y);\n if (yAlign === 'top') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + width - topRight, y);\n ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);\n if (yAlign === 'center' && xAlign === 'right') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + width, y + height - bottomRight);\n ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);\n if (yAlign === 'bottom') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + bottomLeft, y + height);\n ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);\n if (yAlign === 'center' && xAlign === 'left') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x, y + topLeft);\n ctx.quadraticCurveTo(x, y, x + topLeft, y);\n ctx.closePath();\n ctx.fill();\n if (options.borderWidth > 0) {\n ctx.stroke();\n }\n }\n _updateAnimationTarget(options) {\n const chart = this.chart;\n const anims = this.$animations;\n const animX = anims && anims.x;\n const animY = anims && anims.y;\n if (animX || animY) {\n const position = positioners[options.position].call(this, this._active, this._eventPosition);\n if (!position) {\n return;\n }\n const size = this._size = getTooltipSize(this, options);\n const positionAndSize = Object.assign({}, position, this._size);\n const alignment = determineAlignment(chart, options, positionAndSize);\n const point = getBackgroundPoint(options, positionAndSize, alignment, chart);\n if (animX._to !== point.x || animY._to !== point.y) {\n this.xAlign = alignment.xAlign;\n this.yAlign = alignment.yAlign;\n this.width = size.width;\n this.height = size.height;\n this.caretX = position.x;\n this.caretY = position.y;\n this._resolveAnimations().update(this, point);\n }\n }\n }\n draw(ctx) {\n const options = this.options.setContext(this.getContext());\n let opacity = this.opacity;\n if (!opacity) {\n return;\n }\n this._updateAnimationTarget(options);\n const tooltipSize = {\n width: this.width,\n height: this.height\n };\n const pt = {\n x: this.x,\n y: this.y\n };\n opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;\n const padding = toPadding(options.padding);\n const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;\n if (options.enabled && hasTooltipContent) {\n ctx.save();\n ctx.globalAlpha = opacity;\n this.drawBackground(pt, ctx, tooltipSize, options);\n overrideTextDirection(ctx, options.textDirection);\n pt.y += padding.top;\n this.drawTitle(pt, ctx, options);\n this.drawBody(pt, ctx, options);\n this.drawFooter(pt, ctx, options);\n restoreTextDirection(ctx, options.textDirection);\n ctx.restore();\n }\n }\n getActiveElements() {\n return this._active || [];\n }\n setActiveElements(activeElements, eventPosition) {\n const lastActive = this._active;\n const active = activeElements.map(({datasetIndex, index}) => {\n const meta = this.chart.getDatasetMeta(datasetIndex);\n if (!meta) {\n throw new Error('Cannot find a dataset at index ' + datasetIndex);\n }\n return {\n datasetIndex,\n element: meta.data[index],\n index,\n };\n });\n const changed = !_elementsEqual(lastActive, active);\n const positionChanged = this._positionChanged(active, eventPosition);\n if (changed || positionChanged) {\n this._active = active;\n this._eventPosition = eventPosition;\n this._ignoreReplayEvents = true;\n this.update(true);\n }\n }\n handleEvent(e, replay, inChartArea = true) {\n if (replay && this._ignoreReplayEvents) {\n return false;\n }\n this._ignoreReplayEvents = false;\n const options = this.options;\n const lastActive = this._active || [];\n const active = this._getActiveElements(e, lastActive, replay, inChartArea);\n const positionChanged = this._positionChanged(active, e);\n const changed = replay || !_elementsEqual(active, lastActive) || positionChanged;\n if (changed) {\n this._active = active;\n if (options.enabled || options.external) {\n this._eventPosition = {\n x: e.x,\n y: e.y\n };\n this.update(true, replay);\n }\n }\n return changed;\n }\n _getActiveElements(e, lastActive, replay, inChartArea) {\n const options = this.options;\n if (e.type === 'mouseout') {\n return [];\n }\n if (!inChartArea) {\n return lastActive;\n }\n const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);\n if (options.reverse) {\n active.reverse();\n }\n return active;\n }\n _positionChanged(active, e) {\n const {caretX, caretY, options} = this;\n const position = positioners[options.position].call(this, active, e);\n return position !== false && (caretX !== position.x || caretY !== position.y);\n }\n}\nTooltip.positioners = positioners;\nvar plugin_tooltip = {\n id: 'tooltip',\n _element: Tooltip,\n positioners,\n afterInit(chart, _args, options) {\n if (options) {\n chart.tooltip = new Tooltip({chart, options});\n }\n },\n beforeUpdate(chart, _args, options) {\n if (chart.tooltip) {\n chart.tooltip.initialize(options);\n }\n },\n reset(chart, _args, options) {\n if (chart.tooltip) {\n chart.tooltip.initialize(options);\n }\n },\n afterDraw(chart) {\n const tooltip = chart.tooltip;\n const args = {\n tooltip\n };\n if (chart.notifyPlugins('beforeTooltipDraw', args) === false) {\n return;\n }\n if (tooltip) {\n tooltip.draw(chart.ctx);\n }\n chart.notifyPlugins('afterTooltipDraw', args);\n },\n afterEvent(chart, args) {\n if (chart.tooltip) {\n const useFinalPosition = args.replay;\n if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {\n args.changed = true;\n }\n }\n },\n defaults: {\n enabled: true,\n external: null,\n position: 'average',\n backgroundColor: 'rgba(0,0,0,0.8)',\n titleColor: '#fff',\n titleFont: {\n weight: 'bold',\n },\n titleSpacing: 2,\n titleMarginBottom: 6,\n titleAlign: 'left',\n bodyColor: '#fff',\n bodySpacing: 2,\n bodyFont: {\n },\n bodyAlign: 'left',\n footerColor: '#fff',\n footerSpacing: 2,\n footerMarginTop: 6,\n footerFont: {\n weight: 'bold',\n },\n footerAlign: 'left',\n padding: 6,\n caretPadding: 2,\n caretSize: 5,\n cornerRadius: 6,\n boxHeight: (ctx, opts) => opts.bodyFont.size,\n boxWidth: (ctx, opts) => opts.bodyFont.size,\n multiKeyBackground: '#fff',\n displayColors: true,\n boxPadding: 0,\n borderColor: 'rgba(0,0,0,0)',\n borderWidth: 0,\n animation: {\n duration: 400,\n easing: 'easeOutQuart',\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'],\n },\n opacity: {\n easing: 'linear',\n duration: 200\n }\n },\n callbacks: {\n beforeTitle: noop,\n title(tooltipItems) {\n if (tooltipItems.length > 0) {\n const item = tooltipItems[0];\n const labels = item.chart.data.labels;\n const labelCount = labels ? labels.length : 0;\n if (this && this.options && this.options.mode === 'dataset') {\n return item.dataset.label || '';\n } else if (item.label) {\n return item.label;\n } else if (labelCount > 0 && item.dataIndex < labelCount) {\n return labels[item.dataIndex];\n }\n }\n return '';\n },\n afterTitle: noop,\n beforeBody: noop,\n beforeLabel: noop,\n label(tooltipItem) {\n if (this && this.options && this.options.mode === 'dataset') {\n return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;\n }\n let label = tooltipItem.dataset.label || '';\n if (label) {\n label += ': ';\n }\n const value = tooltipItem.formattedValue;\n if (!isNullOrUndef(value)) {\n label += value;\n }\n return label;\n },\n labelColor(tooltipItem) {\n const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);\n const options = meta.controller.getStyle(tooltipItem.dataIndex);\n return {\n borderColor: options.borderColor,\n backgroundColor: options.backgroundColor,\n borderWidth: options.borderWidth,\n borderDash: options.borderDash,\n borderDashOffset: options.borderDashOffset,\n borderRadius: 0,\n };\n },\n labelTextColor() {\n return this.options.bodyColor;\n },\n labelPointStyle(tooltipItem) {\n const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);\n const options = meta.controller.getStyle(tooltipItem.dataIndex);\n return {\n pointStyle: options.pointStyle,\n rotation: options.rotation,\n };\n },\n afterLabel: noop,\n afterBody: noop,\n beforeFooter: noop,\n footer: noop,\n afterFooter: noop\n }\n },\n defaultRoutes: {\n bodyFont: 'font',\n footerFont: 'font',\n titleFont: 'font'\n },\n descriptors: {\n _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external',\n _indexable: false,\n callbacks: {\n _scriptable: false,\n _indexable: false,\n },\n animation: {\n _fallback: false\n },\n animations: {\n _fallback: 'animation'\n }\n },\n additionalOptionScopes: ['interaction']\n};\n\nvar plugins = /*#__PURE__*/Object.freeze({\n__proto__: null,\nDecimation: plugin_decimation,\nFiller: plugin_filler,\nLegend: plugin_legend,\nSubTitle: plugin_subtitle,\nTitle: plugin_title,\nTooltip: plugin_tooltip\n});\n\nconst addIfString = (labels, raw, index, addedLabels) => {\n if (typeof raw === 'string') {\n index = labels.push(raw) - 1;\n addedLabels.unshift({index, label: raw});\n } else if (isNaN(raw)) {\n index = null;\n }\n return index;\n};\nfunction findOrAddLabel(labels, raw, index, addedLabels) {\n const first = labels.indexOf(raw);\n if (first === -1) {\n return addIfString(labels, raw, index, addedLabels);\n }\n const last = labels.lastIndexOf(raw);\n return first !== last ? index : first;\n}\nconst validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);\nclass CategoryScale extends Scale {\n constructor(cfg) {\n super(cfg);\n this._startValue = undefined;\n this._valueRange = 0;\n this._addedLabels = [];\n }\n init(scaleOptions) {\n const added = this._addedLabels;\n if (added.length) {\n const labels = this.getLabels();\n for (const {index, label} of added) {\n if (labels[index] === label) {\n labels.splice(index, 1);\n }\n }\n this._addedLabels = [];\n }\n super.init(scaleOptions);\n }\n parse(raw, index) {\n if (isNullOrUndef(raw)) {\n return null;\n }\n const labels = this.getLabels();\n index = isFinite(index) && labels[index] === raw ? index\n : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels);\n return validIndex(index, labels.length - 1);\n }\n determineDataLimits() {\n const {minDefined, maxDefined} = this.getUserBounds();\n let {min, max} = this.getMinMax(true);\n if (this.options.bounds === 'ticks') {\n if (!minDefined) {\n min = 0;\n }\n if (!maxDefined) {\n max = this.getLabels().length - 1;\n }\n }\n this.min = min;\n this.max = max;\n }\n buildTicks() {\n const min = this.min;\n const max = this.max;\n const offset = this.options.offset;\n const ticks = [];\n let labels = this.getLabels();\n labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1);\n this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);\n this._startValue = this.min - (offset ? 0.5 : 0);\n for (let value = min; value <= max; value++) {\n ticks.push({value});\n }\n return ticks;\n }\n getLabelForValue(value) {\n const labels = this.getLabels();\n if (value >= 0 && value < labels.length) {\n return labels[value];\n }\n return value;\n }\n configure() {\n super.configure();\n if (!this.isHorizontal()) {\n this._reversePixels = !this._reversePixels;\n }\n }\n getPixelForValue(value) {\n if (typeof value !== 'number') {\n value = this.parse(value);\n }\n return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);\n }\n getPixelForTick(index) {\n const ticks = this.ticks;\n if (index < 0 || index > ticks.length - 1) {\n return null;\n }\n return this.getPixelForValue(ticks[index].value);\n }\n getValueForPixel(pixel) {\n return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);\n }\n getBasePixel() {\n return this.bottom;\n }\n}\nCategoryScale.id = 'category';\nCategoryScale.defaults = {\n ticks: {\n callback: CategoryScale.prototype.getLabelForValue\n }\n};\n\nfunction generateTicks$1(generationOptions, dataRange) {\n const ticks = [];\n const MIN_SPACING = 1e-14;\n const {bounds, step, min, max, precision, count, maxTicks, maxDigits, includeBounds} = generationOptions;\n const unit = step || 1;\n const maxSpaces = maxTicks - 1;\n const {min: rmin, max: rmax} = dataRange;\n const minDefined = !isNullOrUndef(min);\n const maxDefined = !isNullOrUndef(max);\n const countDefined = !isNullOrUndef(count);\n const minSpacing = (rmax - rmin) / (maxDigits + 1);\n let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;\n let factor, niceMin, niceMax, numSpaces;\n if (spacing < MIN_SPACING && !minDefined && !maxDefined) {\n return [{value: rmin}, {value: rmax}];\n }\n numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);\n if (numSpaces > maxSpaces) {\n spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;\n }\n if (!isNullOrUndef(precision)) {\n factor = Math.pow(10, precision);\n spacing = Math.ceil(spacing * factor) / factor;\n }\n if (bounds === 'ticks') {\n niceMin = Math.floor(rmin / spacing) * spacing;\n niceMax = Math.ceil(rmax / spacing) * spacing;\n } else {\n niceMin = rmin;\n niceMax = rmax;\n }\n if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {\n numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));\n spacing = (max - min) / numSpaces;\n niceMin = min;\n niceMax = max;\n } else if (countDefined) {\n niceMin = minDefined ? min : niceMin;\n niceMax = maxDefined ? max : niceMax;\n numSpaces = count - 1;\n spacing = (niceMax - niceMin) / numSpaces;\n } else {\n numSpaces = (niceMax - niceMin) / spacing;\n if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {\n numSpaces = Math.round(numSpaces);\n } else {\n numSpaces = Math.ceil(numSpaces);\n }\n }\n const decimalPlaces = Math.max(\n _decimalPlaces(spacing),\n _decimalPlaces(niceMin)\n );\n factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);\n niceMin = Math.round(niceMin * factor) / factor;\n niceMax = Math.round(niceMax * factor) / factor;\n let j = 0;\n if (minDefined) {\n if (includeBounds && niceMin !== min) {\n ticks.push({value: min});\n if (niceMin < min) {\n j++;\n }\n if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {\n j++;\n }\n } else if (niceMin < min) {\n j++;\n }\n }\n for (; j < numSpaces; ++j) {\n ticks.push({value: Math.round((niceMin + j * spacing) * factor) / factor});\n }\n if (maxDefined && includeBounds && niceMax !== max) {\n if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {\n ticks[ticks.length - 1].value = max;\n } else {\n ticks.push({value: max});\n }\n } else if (!maxDefined || niceMax === max) {\n ticks.push({value: niceMax});\n }\n return ticks;\n}\nfunction relativeLabelSize(value, minSpacing, {horizontal, minRotation}) {\n const rad = toRadians(minRotation);\n const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;\n const length = 0.75 * minSpacing * ('' + value).length;\n return Math.min(minSpacing / ratio, length);\n}\nclass LinearScaleBase extends Scale {\n constructor(cfg) {\n super(cfg);\n this.start = undefined;\n this.end = undefined;\n this._startValue = undefined;\n this._endValue = undefined;\n this._valueRange = 0;\n }\n parse(raw, index) {\n if (isNullOrUndef(raw)) {\n return null;\n }\n if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {\n return null;\n }\n return +raw;\n }\n handleTickRangeOptions() {\n const {beginAtZero} = this.options;\n const {minDefined, maxDefined} = this.getUserBounds();\n let {min, max} = this;\n const setMin = v => (min = minDefined ? min : v);\n const setMax = v => (max = maxDefined ? max : v);\n if (beginAtZero) {\n const minSign = sign(min);\n const maxSign = sign(max);\n if (minSign < 0 && maxSign < 0) {\n setMax(0);\n } else if (minSign > 0 && maxSign > 0) {\n setMin(0);\n }\n }\n if (min === max) {\n let offset = 1;\n if (max >= Number.MAX_SAFE_INTEGER || min <= Number.MIN_SAFE_INTEGER) {\n offset = Math.abs(max * 0.05);\n }\n setMax(max + offset);\n if (!beginAtZero) {\n setMin(min - offset);\n }\n }\n this.min = min;\n this.max = max;\n }\n getTickLimit() {\n const tickOpts = this.options.ticks;\n let {maxTicksLimit, stepSize} = tickOpts;\n let maxTicks;\n if (stepSize) {\n maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;\n if (maxTicks > 1000) {\n console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);\n maxTicks = 1000;\n }\n } else {\n maxTicks = this.computeTickLimit();\n maxTicksLimit = maxTicksLimit || 11;\n }\n if (maxTicksLimit) {\n maxTicks = Math.min(maxTicksLimit, maxTicks);\n }\n return maxTicks;\n }\n computeTickLimit() {\n return Number.POSITIVE_INFINITY;\n }\n buildTicks() {\n const opts = this.options;\n const tickOpts = opts.ticks;\n let maxTicks = this.getTickLimit();\n maxTicks = Math.max(2, maxTicks);\n const numericGeneratorOptions = {\n maxTicks,\n bounds: opts.bounds,\n min: opts.min,\n max: opts.max,\n precision: tickOpts.precision,\n step: tickOpts.stepSize,\n count: tickOpts.count,\n maxDigits: this._maxDigits(),\n horizontal: this.isHorizontal(),\n minRotation: tickOpts.minRotation || 0,\n includeBounds: tickOpts.includeBounds !== false\n };\n const dataRange = this._range || this;\n const ticks = generateTicks$1(numericGeneratorOptions, dataRange);\n if (opts.bounds === 'ticks') {\n _setMinAndMaxByKey(ticks, this, 'value');\n }\n if (opts.reverse) {\n ticks.reverse();\n this.start = this.max;\n this.end = this.min;\n } else {\n this.start = this.min;\n this.end = this.max;\n }\n return ticks;\n }\n configure() {\n const ticks = this.ticks;\n let start = this.min;\n let end = this.max;\n super.configure();\n if (this.options.offset && ticks.length) {\n const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;\n start -= offset;\n end += offset;\n }\n this._startValue = start;\n this._endValue = end;\n this._valueRange = end - start;\n }\n getLabelForValue(value) {\n return formatNumber(value, this.chart.options.locale, this.options.ticks.format);\n }\n}\n\nclass LinearScale extends LinearScaleBase {\n determineDataLimits() {\n const {min, max} = this.getMinMax(true);\n this.min = isNumberFinite(min) ? min : 0;\n this.max = isNumberFinite(max) ? max : 1;\n this.handleTickRangeOptions();\n }\n computeTickLimit() {\n const horizontal = this.isHorizontal();\n const length = horizontal ? this.width : this.height;\n const minRotation = toRadians(this.options.ticks.minRotation);\n const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;\n const tickFont = this._resolveTickFontOptions(0);\n return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));\n }\n getPixelForValue(value) {\n return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);\n }\n getValueForPixel(pixel) {\n return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;\n }\n}\nLinearScale.id = 'linear';\nLinearScale.defaults = {\n ticks: {\n callback: Ticks.formatters.numeric\n }\n};\n\nfunction isMajor(tickVal) {\n const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal))));\n return remain === 1;\n}\nfunction generateTicks(generationOptions, dataRange) {\n const endExp = Math.floor(log10(dataRange.max));\n const endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));\n const ticks = [];\n let tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));\n let exp = Math.floor(log10(tickVal));\n let significand = Math.floor(tickVal / Math.pow(10, exp));\n let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;\n do {\n ticks.push({value: tickVal, major: isMajor(tickVal)});\n ++significand;\n if (significand === 10) {\n significand = 1;\n ++exp;\n precision = exp >= 0 ? 1 : precision;\n }\n tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;\n } while (exp < endExp || (exp === endExp && significand < endSignificand));\n const lastTick = finiteOrDefault(generationOptions.max, tickVal);\n ticks.push({value: lastTick, major: isMajor(tickVal)});\n return ticks;\n}\nclass LogarithmicScale extends Scale {\n constructor(cfg) {\n super(cfg);\n this.start = undefined;\n this.end = undefined;\n this._startValue = undefined;\n this._valueRange = 0;\n }\n parse(raw, index) {\n const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);\n if (value === 0) {\n this._zero = true;\n return undefined;\n }\n return isNumberFinite(value) && value > 0 ? value : null;\n }\n determineDataLimits() {\n const {min, max} = this.getMinMax(true);\n this.min = isNumberFinite(min) ? Math.max(0, min) : null;\n this.max = isNumberFinite(max) ? Math.max(0, max) : null;\n if (this.options.beginAtZero) {\n this._zero = true;\n }\n this.handleTickRangeOptions();\n }\n handleTickRangeOptions() {\n const {minDefined, maxDefined} = this.getUserBounds();\n let min = this.min;\n let max = this.max;\n const setMin = v => (min = minDefined ? min : v);\n const setMax = v => (max = maxDefined ? max : v);\n const exp = (v, m) => Math.pow(10, Math.floor(log10(v)) + m);\n if (min === max) {\n if (min <= 0) {\n setMin(1);\n setMax(10);\n } else {\n setMin(exp(min, -1));\n setMax(exp(max, +1));\n }\n }\n if (min <= 0) {\n setMin(exp(max, -1));\n }\n if (max <= 0) {\n setMax(exp(min, +1));\n }\n if (this._zero && this.min !== this._suggestedMin && min === exp(this.min, 0)) {\n setMin(exp(min, -1));\n }\n this.min = min;\n this.max = max;\n }\n buildTicks() {\n const opts = this.options;\n const generationOptions = {\n min: this._userMin,\n max: this._userMax\n };\n const ticks = generateTicks(generationOptions, this);\n if (opts.bounds === 'ticks') {\n _setMinAndMaxByKey(ticks, this, 'value');\n }\n if (opts.reverse) {\n ticks.reverse();\n this.start = this.max;\n this.end = this.min;\n } else {\n this.start = this.min;\n this.end = this.max;\n }\n return ticks;\n }\n getLabelForValue(value) {\n return value === undefined\n ? '0'\n : formatNumber(value, this.chart.options.locale, this.options.ticks.format);\n }\n configure() {\n const start = this.min;\n super.configure();\n this._startValue = log10(start);\n this._valueRange = log10(this.max) - log10(start);\n }\n getPixelForValue(value) {\n if (value === undefined || value === 0) {\n value = this.min;\n }\n if (value === null || isNaN(value)) {\n return NaN;\n }\n return this.getPixelForDecimal(value === this.min\n ? 0\n : (log10(value) - this._startValue) / this._valueRange);\n }\n getValueForPixel(pixel) {\n const decimal = this.getDecimalForPixel(pixel);\n return Math.pow(10, this._startValue + decimal * this._valueRange);\n }\n}\nLogarithmicScale.id = 'logarithmic';\nLogarithmicScale.defaults = {\n ticks: {\n callback: Ticks.formatters.logarithmic,\n major: {\n enabled: true\n }\n }\n};\n\nfunction getTickBackdropHeight(opts) {\n const tickOpts = opts.ticks;\n if (tickOpts.display && opts.display) {\n const padding = toPadding(tickOpts.backdropPadding);\n return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;\n }\n return 0;\n}\nfunction measureLabelSize(ctx, font, label) {\n label = isArray(label) ? label : [label];\n return {\n w: _longestText(ctx, font.string, label),\n h: label.length * font.lineHeight\n };\n}\nfunction determineLimits(angle, pos, size, min, max) {\n if (angle === min || angle === max) {\n return {\n start: pos - (size / 2),\n end: pos + (size / 2)\n };\n } else if (angle < min || angle > max) {\n return {\n start: pos - size,\n end: pos\n };\n }\n return {\n start: pos,\n end: pos + size\n };\n}\nfunction fitWithPointLabels(scale) {\n const orig = {\n l: scale.left + scale._padding.left,\n r: scale.right - scale._padding.right,\n t: scale.top + scale._padding.top,\n b: scale.bottom - scale._padding.bottom\n };\n const limits = Object.assign({}, orig);\n const labelSizes = [];\n const padding = [];\n const valueCount = scale._pointLabels.length;\n const pointLabelOpts = scale.options.pointLabels;\n const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0;\n for (let i = 0; i < valueCount; i++) {\n const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));\n padding[i] = opts.padding;\n const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);\n const plFont = toFont(opts.font);\n const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);\n labelSizes[i] = textSize;\n const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle);\n const angle = Math.round(toDegrees(angleRadians));\n const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);\n const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);\n updateLimits(limits, orig, angleRadians, hLimits, vLimits);\n }\n scale.setCenterPoint(\n orig.l - limits.l,\n limits.r - orig.r,\n orig.t - limits.t,\n limits.b - orig.b\n );\n scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);\n}\nfunction updateLimits(limits, orig, angle, hLimits, vLimits) {\n const sin = Math.abs(Math.sin(angle));\n const cos = Math.abs(Math.cos(angle));\n let x = 0;\n let y = 0;\n if (hLimits.start < orig.l) {\n x = (orig.l - hLimits.start) / sin;\n limits.l = Math.min(limits.l, orig.l - x);\n } else if (hLimits.end > orig.r) {\n x = (hLimits.end - orig.r) / sin;\n limits.r = Math.max(limits.r, orig.r + x);\n }\n if (vLimits.start < orig.t) {\n y = (orig.t - vLimits.start) / cos;\n limits.t = Math.min(limits.t, orig.t - y);\n } else if (vLimits.end > orig.b) {\n y = (vLimits.end - orig.b) / cos;\n limits.b = Math.max(limits.b, orig.b + y);\n }\n}\nfunction buildPointLabelItems(scale, labelSizes, padding) {\n const items = [];\n const valueCount = scale._pointLabels.length;\n const opts = scale.options;\n const extra = getTickBackdropHeight(opts) / 2;\n const outerDistance = scale.drawingArea;\n const additionalAngle = opts.pointLabels.centerPointLabels ? PI / valueCount : 0;\n for (let i = 0; i < valueCount; i++) {\n const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + padding[i], additionalAngle);\n const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI)));\n const size = labelSizes[i];\n const y = yForAngle(pointLabelPosition.y, size.h, angle);\n const textAlign = getTextAlignForAngle(angle);\n const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);\n items.push({\n x: pointLabelPosition.x,\n y,\n textAlign,\n left,\n top: y,\n right: left + size.w,\n bottom: y + size.h\n });\n }\n return items;\n}\nfunction getTextAlignForAngle(angle) {\n if (angle === 0 || angle === 180) {\n return 'center';\n } else if (angle < 180) {\n return 'left';\n }\n return 'right';\n}\nfunction leftForTextAlign(x, w, align) {\n if (align === 'right') {\n x -= w;\n } else if (align === 'center') {\n x -= (w / 2);\n }\n return x;\n}\nfunction yForAngle(y, h, angle) {\n if (angle === 90 || angle === 270) {\n y -= (h / 2);\n } else if (angle > 270 || angle < 90) {\n y -= h;\n }\n return y;\n}\nfunction drawPointLabels(scale, labelCount) {\n const {ctx, options: {pointLabels}} = scale;\n for (let i = labelCount - 1; i >= 0; i--) {\n const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));\n const plFont = toFont(optsAtIndex.font);\n const {x, y, textAlign, left, top, right, bottom} = scale._pointLabelItems[i];\n const {backdropColor} = optsAtIndex;\n if (!isNullOrUndef(backdropColor)) {\n const padding = toPadding(optsAtIndex.backdropPadding);\n ctx.fillStyle = backdropColor;\n ctx.fillRect(left - padding.left, top - padding.top, right - left + padding.width, bottom - top + padding.height);\n }\n renderText(\n ctx,\n scale._pointLabels[i],\n x,\n y + (plFont.lineHeight / 2),\n plFont,\n {\n color: optsAtIndex.color,\n textAlign: textAlign,\n textBaseline: 'middle'\n }\n );\n }\n}\nfunction pathRadiusLine(scale, radius, circular, labelCount) {\n const {ctx} = scale;\n if (circular) {\n ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);\n } else {\n let pointPosition = scale.getPointPosition(0, radius);\n ctx.moveTo(pointPosition.x, pointPosition.y);\n for (let i = 1; i < labelCount; i++) {\n pointPosition = scale.getPointPosition(i, radius);\n ctx.lineTo(pointPosition.x, pointPosition.y);\n }\n }\n}\nfunction drawRadiusLine(scale, gridLineOpts, radius, labelCount) {\n const ctx = scale.ctx;\n const circular = gridLineOpts.circular;\n const {color, lineWidth} = gridLineOpts;\n if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) {\n return;\n }\n ctx.save();\n ctx.strokeStyle = color;\n ctx.lineWidth = lineWidth;\n ctx.setLineDash(gridLineOpts.borderDash);\n ctx.lineDashOffset = gridLineOpts.borderDashOffset;\n ctx.beginPath();\n pathRadiusLine(scale, radius, circular, labelCount);\n ctx.closePath();\n ctx.stroke();\n ctx.restore();\n}\nfunction createPointLabelContext(parent, index, label) {\n return createContext(parent, {\n label,\n index,\n type: 'pointLabel'\n });\n}\nclass RadialLinearScale extends LinearScaleBase {\n constructor(cfg) {\n super(cfg);\n this.xCenter = undefined;\n this.yCenter = undefined;\n this.drawingArea = undefined;\n this._pointLabels = [];\n this._pointLabelItems = [];\n }\n setDimensions() {\n const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2);\n const w = this.width = this.maxWidth - padding.width;\n const h = this.height = this.maxHeight - padding.height;\n this.xCenter = Math.floor(this.left + w / 2 + padding.left);\n this.yCenter = Math.floor(this.top + h / 2 + padding.top);\n this.drawingArea = Math.floor(Math.min(w, h) / 2);\n }\n determineDataLimits() {\n const {min, max} = this.getMinMax(false);\n this.min = isNumberFinite(min) && !isNaN(min) ? min : 0;\n this.max = isNumberFinite(max) && !isNaN(max) ? max : 0;\n this.handleTickRangeOptions();\n }\n computeTickLimit() {\n return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));\n }\n generateTickLabels(ticks) {\n LinearScaleBase.prototype.generateTickLabels.call(this, ticks);\n this._pointLabels = this.getLabels()\n .map((value, index) => {\n const label = callback(this.options.pointLabels.callback, [value, index], this);\n return label || label === 0 ? label : '';\n })\n .filter((v, i) => this.chart.getDataVisibility(i));\n }\n fit() {\n const opts = this.options;\n if (opts.display && opts.pointLabels.display) {\n fitWithPointLabels(this);\n } else {\n this.setCenterPoint(0, 0, 0, 0);\n }\n }\n setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {\n this.xCenter += Math.floor((leftMovement - rightMovement) / 2);\n this.yCenter += Math.floor((topMovement - bottomMovement) / 2);\n this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));\n }\n getIndexAngle(index) {\n const angleMultiplier = TAU / (this._pointLabels.length || 1);\n const startAngle = this.options.startAngle || 0;\n return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));\n }\n getDistanceFromCenterForValue(value) {\n if (isNullOrUndef(value)) {\n return NaN;\n }\n const scalingFactor = this.drawingArea / (this.max - this.min);\n if (this.options.reverse) {\n return (this.max - value) * scalingFactor;\n }\n return (value - this.min) * scalingFactor;\n }\n getValueForDistanceFromCenter(distance) {\n if (isNullOrUndef(distance)) {\n return NaN;\n }\n const scaledDistance = distance / (this.drawingArea / (this.max - this.min));\n return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;\n }\n getPointLabelContext(index) {\n const pointLabels = this._pointLabels || [];\n if (index >= 0 && index < pointLabels.length) {\n const pointLabel = pointLabels[index];\n return createPointLabelContext(this.getContext(), index, pointLabel);\n }\n }\n getPointPosition(index, distanceFromCenter, additionalAngle = 0) {\n const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle;\n return {\n x: Math.cos(angle) * distanceFromCenter + this.xCenter,\n y: Math.sin(angle) * distanceFromCenter + this.yCenter,\n angle\n };\n }\n getPointPositionForValue(index, value) {\n return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));\n }\n getBasePosition(index) {\n return this.getPointPositionForValue(index || 0, this.getBaseValue());\n }\n getPointLabelPosition(index) {\n const {left, top, right, bottom} = this._pointLabelItems[index];\n return {\n left,\n top,\n right,\n bottom,\n };\n }\n drawBackground() {\n const {backgroundColor, grid: {circular}} = this.options;\n if (backgroundColor) {\n const ctx = this.ctx;\n ctx.save();\n ctx.beginPath();\n pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);\n ctx.closePath();\n ctx.fillStyle = backgroundColor;\n ctx.fill();\n ctx.restore();\n }\n }\n drawGrid() {\n const ctx = this.ctx;\n const opts = this.options;\n const {angleLines, grid} = opts;\n const labelCount = this._pointLabels.length;\n let i, offset, position;\n if (opts.pointLabels.display) {\n drawPointLabels(this, labelCount);\n }\n if (grid.display) {\n this.ticks.forEach((tick, index) => {\n if (index !== 0) {\n offset = this.getDistanceFromCenterForValue(tick.value);\n const optsAtIndex = grid.setContext(this.getContext(index - 1));\n drawRadiusLine(this, optsAtIndex, offset, labelCount);\n }\n });\n }\n if (angleLines.display) {\n ctx.save();\n for (i = labelCount - 1; i >= 0; i--) {\n const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));\n const {color, lineWidth} = optsAtIndex;\n if (!lineWidth || !color) {\n continue;\n }\n ctx.lineWidth = lineWidth;\n ctx.strokeStyle = color;\n ctx.setLineDash(optsAtIndex.borderDash);\n ctx.lineDashOffset = optsAtIndex.borderDashOffset;\n offset = this.getDistanceFromCenterForValue(opts.ticks.reverse ? this.min : this.max);\n position = this.getPointPosition(i, offset);\n ctx.beginPath();\n ctx.moveTo(this.xCenter, this.yCenter);\n ctx.lineTo(position.x, position.y);\n ctx.stroke();\n }\n ctx.restore();\n }\n }\n drawBorder() {}\n drawLabels() {\n const ctx = this.ctx;\n const opts = this.options;\n const tickOpts = opts.ticks;\n if (!tickOpts.display) {\n return;\n }\n const startAngle = this.getIndexAngle(0);\n let offset, width;\n ctx.save();\n ctx.translate(this.xCenter, this.yCenter);\n ctx.rotate(startAngle);\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n this.ticks.forEach((tick, index) => {\n if (index === 0 && !opts.reverse) {\n return;\n }\n const optsAtIndex = tickOpts.setContext(this.getContext(index));\n const tickFont = toFont(optsAtIndex.font);\n offset = this.getDistanceFromCenterForValue(this.ticks[index].value);\n if (optsAtIndex.showLabelBackdrop) {\n ctx.font = tickFont.string;\n width = ctx.measureText(tick.label).width;\n ctx.fillStyle = optsAtIndex.backdropColor;\n const padding = toPadding(optsAtIndex.backdropPadding);\n ctx.fillRect(\n -width / 2 - padding.left,\n -offset - tickFont.size / 2 - padding.top,\n width + padding.width,\n tickFont.size + padding.height\n );\n }\n renderText(ctx, tick.label, 0, -offset, tickFont, {\n color: optsAtIndex.color,\n });\n });\n ctx.restore();\n }\n drawTitle() {}\n}\nRadialLinearScale.id = 'radialLinear';\nRadialLinearScale.defaults = {\n display: true,\n animate: true,\n position: 'chartArea',\n angleLines: {\n display: true,\n lineWidth: 1,\n borderDash: [],\n borderDashOffset: 0.0\n },\n grid: {\n circular: false\n },\n startAngle: 0,\n ticks: {\n showLabelBackdrop: true,\n callback: Ticks.formatters.numeric\n },\n pointLabels: {\n backdropColor: undefined,\n backdropPadding: 2,\n display: true,\n font: {\n size: 10\n },\n callback(label) {\n return label;\n },\n padding: 5,\n centerPointLabels: false\n }\n};\nRadialLinearScale.defaultRoutes = {\n 'angleLines.color': 'borderColor',\n 'pointLabels.color': 'color',\n 'ticks.color': 'color'\n};\nRadialLinearScale.descriptors = {\n angleLines: {\n _fallback: 'grid'\n }\n};\n\nconst INTERVALS = {\n millisecond: {common: true, size: 1, steps: 1000},\n second: {common: true, size: 1000, steps: 60},\n minute: {common: true, size: 60000, steps: 60},\n hour: {common: true, size: 3600000, steps: 24},\n day: {common: true, size: 86400000, steps: 30},\n week: {common: false, size: 604800000, steps: 4},\n month: {common: true, size: 2.628e9, steps: 12},\n quarter: {common: false, size: 7.884e9, steps: 4},\n year: {common: true, size: 3.154e10}\n};\nconst UNITS = (Object.keys(INTERVALS));\nfunction sorter(a, b) {\n return a - b;\n}\nfunction parse(scale, input) {\n if (isNullOrUndef(input)) {\n return null;\n }\n const adapter = scale._adapter;\n const {parser, round, isoWeekday} = scale._parseOpts;\n let value = input;\n if (typeof parser === 'function') {\n value = parser(value);\n }\n if (!isNumberFinite(value)) {\n value = typeof parser === 'string'\n ? adapter.parse(value, parser)\n : adapter.parse(value);\n }\n if (value === null) {\n return null;\n }\n if (round) {\n value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true)\n ? adapter.startOf(value, 'isoWeek', isoWeekday)\n : adapter.startOf(value, round);\n }\n return +value;\n}\nfunction determineUnitForAutoTicks(minUnit, min, max, capacity) {\n const ilen = UNITS.length;\n for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {\n const interval = INTERVALS[UNITS[i]];\n const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;\n if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {\n return UNITS[i];\n }\n }\n return UNITS[ilen - 1];\n}\nfunction determineUnitForFormatting(scale, numTicks, minUnit, min, max) {\n for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {\n const unit = UNITS[i];\n if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {\n return unit;\n }\n }\n return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];\n}\nfunction determineMajorUnit(unit) {\n for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {\n if (INTERVALS[UNITS[i]].common) {\n return UNITS[i];\n }\n }\n}\nfunction addTick(ticks, time, timestamps) {\n if (!timestamps) {\n ticks[time] = true;\n } else if (timestamps.length) {\n const {lo, hi} = _lookup(timestamps, time);\n const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];\n ticks[timestamp] = true;\n }\n}\nfunction setMajorTicks(scale, ticks, map, majorUnit) {\n const adapter = scale._adapter;\n const first = +adapter.startOf(ticks[0].value, majorUnit);\n const last = ticks[ticks.length - 1].value;\n let major, index;\n for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {\n index = map[major];\n if (index >= 0) {\n ticks[index].major = true;\n }\n }\n return ticks;\n}\nfunction ticksFromTimestamps(scale, values, majorUnit) {\n const ticks = [];\n const map = {};\n const ilen = values.length;\n let i, value;\n for (i = 0; i < ilen; ++i) {\n value = values[i];\n map[value] = i;\n ticks.push({\n value,\n major: false\n });\n }\n return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);\n}\nclass TimeScale extends Scale {\n constructor(props) {\n super(props);\n this._cache = {\n data: [],\n labels: [],\n all: []\n };\n this._unit = 'day';\n this._majorUnit = undefined;\n this._offsets = {};\n this._normalized = false;\n this._parseOpts = undefined;\n }\n init(scaleOpts, opts) {\n const time = scaleOpts.time || (scaleOpts.time = {});\n const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);\n mergeIf(time.displayFormats, adapter.formats());\n this._parseOpts = {\n parser: time.parser,\n round: time.round,\n isoWeekday: time.isoWeekday\n };\n super.init(scaleOpts);\n this._normalized = opts.normalized;\n }\n parse(raw, index) {\n if (raw === undefined) {\n return null;\n }\n return parse(this, raw);\n }\n beforeLayout() {\n super.beforeLayout();\n this._cache = {\n data: [],\n labels: [],\n all: []\n };\n }\n determineDataLimits() {\n const options = this.options;\n const adapter = this._adapter;\n const unit = options.time.unit || 'day';\n let {min, max, minDefined, maxDefined} = this.getUserBounds();\n function _applyBounds(bounds) {\n if (!minDefined && !isNaN(bounds.min)) {\n min = Math.min(min, bounds.min);\n }\n if (!maxDefined && !isNaN(bounds.max)) {\n max = Math.max(max, bounds.max);\n }\n }\n if (!minDefined || !maxDefined) {\n _applyBounds(this._getLabelBounds());\n if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {\n _applyBounds(this.getMinMax(false));\n }\n }\n min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);\n max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;\n this.min = Math.min(min, max - 1);\n this.max = Math.max(min + 1, max);\n }\n _getLabelBounds() {\n const arr = this.getLabelTimestamps();\n let min = Number.POSITIVE_INFINITY;\n let max = Number.NEGATIVE_INFINITY;\n if (arr.length) {\n min = arr[0];\n max = arr[arr.length - 1];\n }\n return {min, max};\n }\n buildTicks() {\n const options = this.options;\n const timeOpts = options.time;\n const tickOpts = options.ticks;\n const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();\n if (options.bounds === 'ticks' && timestamps.length) {\n this.min = this._userMin || timestamps[0];\n this.max = this._userMax || timestamps[timestamps.length - 1];\n }\n const min = this.min;\n const max = this.max;\n const ticks = _filterBetween(timestamps, min, max);\n this._unit = timeOpts.unit || (tickOpts.autoSkip\n ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min))\n : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max));\n this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined\n : determineMajorUnit(this._unit);\n this.initOffsets(timestamps);\n if (options.reverse) {\n ticks.reverse();\n }\n return ticksFromTimestamps(this, ticks, this._majorUnit);\n }\n initOffsets(timestamps) {\n let start = 0;\n let end = 0;\n let first, last;\n if (this.options.offset && timestamps.length) {\n first = this.getDecimalForValue(timestamps[0]);\n if (timestamps.length === 1) {\n start = 1 - first;\n } else {\n start = (this.getDecimalForValue(timestamps[1]) - first) / 2;\n }\n last = this.getDecimalForValue(timestamps[timestamps.length - 1]);\n if (timestamps.length === 1) {\n end = last;\n } else {\n end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;\n }\n }\n const limit = timestamps.length < 3 ? 0.5 : 0.25;\n start = _limitValue(start, 0, limit);\n end = _limitValue(end, 0, limit);\n this._offsets = {start, end, factor: 1 / (start + 1 + end)};\n }\n _generate() {\n const adapter = this._adapter;\n const min = this.min;\n const max = this.max;\n const options = this.options;\n const timeOpts = options.time;\n const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));\n const stepSize = valueOrDefault(timeOpts.stepSize, 1);\n const weekday = minor === 'week' ? timeOpts.isoWeekday : false;\n const hasWeekday = isNumber(weekday) || weekday === true;\n const ticks = {};\n let first = min;\n let time, count;\n if (hasWeekday) {\n first = +adapter.startOf(first, 'isoWeek', weekday);\n }\n first = +adapter.startOf(first, hasWeekday ? 'day' : minor);\n if (adapter.diff(max, min, minor) > 100000 * stepSize) {\n throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);\n }\n const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();\n for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) {\n addTick(ticks, time, timestamps);\n }\n if (time === max || options.bounds === 'ticks' || count === 1) {\n addTick(ticks, time, timestamps);\n }\n return Object.keys(ticks).sort((a, b) => a - b).map(x => +x);\n }\n getLabelForValue(value) {\n const adapter = this._adapter;\n const timeOpts = this.options.time;\n if (timeOpts.tooltipFormat) {\n return adapter.format(value, timeOpts.tooltipFormat);\n }\n return adapter.format(value, timeOpts.displayFormats.datetime);\n }\n _tickFormatFunction(time, index, ticks, format) {\n const options = this.options;\n const formats = options.time.displayFormats;\n const unit = this._unit;\n const majorUnit = this._majorUnit;\n const minorFormat = unit && formats[unit];\n const majorFormat = majorUnit && formats[majorUnit];\n const tick = ticks[index];\n const major = majorUnit && majorFormat && tick && tick.major;\n const label = this._adapter.format(time, format || (major ? majorFormat : minorFormat));\n const formatter = options.ticks.callback;\n return formatter ? callback(formatter, [label, index, ticks], this) : label;\n }\n generateTickLabels(ticks) {\n let i, ilen, tick;\n for (i = 0, ilen = ticks.length; i < ilen; ++i) {\n tick = ticks[i];\n tick.label = this._tickFormatFunction(tick.value, i, ticks);\n }\n }\n getDecimalForValue(value) {\n return value === null ? NaN : (value - this.min) / (this.max - this.min);\n }\n getPixelForValue(value) {\n const offsets = this._offsets;\n const pos = this.getDecimalForValue(value);\n return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);\n }\n getValueForPixel(pixel) {\n const offsets = this._offsets;\n const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;\n return this.min + pos * (this.max - this.min);\n }\n _getLabelSize(label) {\n const ticksOpts = this.options.ticks;\n const tickLabelWidth = this.ctx.measureText(label).width;\n const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);\n const cosRotation = Math.cos(angle);\n const sinRotation = Math.sin(angle);\n const tickFontSize = this._resolveTickFontOptions(0).size;\n return {\n w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),\n h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)\n };\n }\n _getLabelCapacity(exampleTime) {\n const timeOpts = this.options.time;\n const displayFormats = timeOpts.displayFormats;\n const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;\n const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [exampleTime], this._majorUnit), format);\n const size = this._getLabelSize(exampleLabel);\n const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;\n return capacity > 0 ? capacity : 1;\n }\n getDataTimestamps() {\n let timestamps = this._cache.data || [];\n let i, ilen;\n if (timestamps.length) {\n return timestamps;\n }\n const metas = this.getMatchingVisibleMetas();\n if (this._normalized && metas.length) {\n return (this._cache.data = metas[0].controller.getAllParsedValues(this));\n }\n for (i = 0, ilen = metas.length; i < ilen; ++i) {\n timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));\n }\n return (this._cache.data = this.normalize(timestamps));\n }\n getLabelTimestamps() {\n const timestamps = this._cache.labels || [];\n let i, ilen;\n if (timestamps.length) {\n return timestamps;\n }\n const labels = this.getLabels();\n for (i = 0, ilen = labels.length; i < ilen; ++i) {\n timestamps.push(parse(this, labels[i]));\n }\n return (this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps));\n }\n normalize(values) {\n return _arrayUnique(values.sort(sorter));\n }\n}\nTimeScale.id = 'time';\nTimeScale.defaults = {\n bounds: 'data',\n adapters: {},\n time: {\n parser: false,\n unit: false,\n round: false,\n isoWeekday: false,\n minUnit: 'millisecond',\n displayFormats: {}\n },\n ticks: {\n source: 'auto',\n major: {\n enabled: false\n }\n }\n};\n\nfunction interpolate(table, val, reverse) {\n let lo = 0;\n let hi = table.length - 1;\n let prevSource, nextSource, prevTarget, nextTarget;\n if (reverse) {\n if (val >= table[lo].pos && val <= table[hi].pos) {\n ({lo, hi} = _lookupByKey(table, 'pos', val));\n }\n ({pos: prevSource, time: prevTarget} = table[lo]);\n ({pos: nextSource, time: nextTarget} = table[hi]);\n } else {\n if (val >= table[lo].time && val <= table[hi].time) {\n ({lo, hi} = _lookupByKey(table, 'time', val));\n }\n ({time: prevSource, pos: prevTarget} = table[lo]);\n ({time: nextSource, pos: nextTarget} = table[hi]);\n }\n const span = nextSource - prevSource;\n return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;\n}\nclass TimeSeriesScale extends TimeScale {\n constructor(props) {\n super(props);\n this._table = [];\n this._minPos = undefined;\n this._tableRange = undefined;\n }\n initOffsets() {\n const timestamps = this._getTimestampsForTable();\n const table = this._table = this.buildLookupTable(timestamps);\n this._minPos = interpolate(table, this.min);\n this._tableRange = interpolate(table, this.max) - this._minPos;\n super.initOffsets(timestamps);\n }\n buildLookupTable(timestamps) {\n const {min, max} = this;\n const items = [];\n const table = [];\n let i, ilen, prev, curr, next;\n for (i = 0, ilen = timestamps.length; i < ilen; ++i) {\n curr = timestamps[i];\n if (curr >= min && curr <= max) {\n items.push(curr);\n }\n }\n if (items.length < 2) {\n return [\n {time: min, pos: 0},\n {time: max, pos: 1}\n ];\n }\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n next = items[i + 1];\n prev = items[i - 1];\n curr = items[i];\n if (Math.round((next + prev) / 2) !== curr) {\n table.push({time: curr, pos: i / (ilen - 1)});\n }\n }\n return table;\n }\n _getTimestampsForTable() {\n let timestamps = this._cache.all || [];\n if (timestamps.length) {\n return timestamps;\n }\n const data = this.getDataTimestamps();\n const label = this.getLabelTimestamps();\n if (data.length && label.length) {\n timestamps = this.normalize(data.concat(label));\n } else {\n timestamps = data.length ? data : label;\n }\n timestamps = this._cache.all = timestamps;\n return timestamps;\n }\n getDecimalForValue(value) {\n return (interpolate(this._table, value) - this._minPos) / this._tableRange;\n }\n getValueForPixel(pixel) {\n const offsets = this._offsets;\n const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;\n return interpolate(this._table, decimal * this._tableRange + this._minPos, true);\n }\n}\nTimeSeriesScale.id = 'timeseries';\nTimeSeriesScale.defaults = TimeScale.defaults;\n\nvar scales = /*#__PURE__*/Object.freeze({\n__proto__: null,\nCategoryScale: CategoryScale,\nLinearScale: LinearScale,\nLogarithmicScale: LogarithmicScale,\nRadialLinearScale: RadialLinearScale,\nTimeScale: TimeScale,\nTimeSeriesScale: TimeSeriesScale\n});\n\nconst registerables = [\n controllers,\n elements,\n plugins,\n scales,\n];\n\nexport { Animation, Animations, ArcElement, BarController, BarElement, BasePlatform, BasicPlatform, BubbleController, CategoryScale, Chart, DatasetController, plugin_decimation as Decimation, DomPlatform, DoughnutController, Element, plugin_filler as Filler, Interaction, plugin_legend as Legend, LineController, LineElement, LinearScale, LogarithmicScale, PieController, PointElement, PolarAreaController, RadarController, RadialLinearScale, Scale, ScatterController, plugin_subtitle as SubTitle, Ticks, TimeScale, TimeSeriesScale, plugin_title as Title, plugin_tooltip as Tooltip, adapters as _adapters, _detectPlatform, animator, controllers, elements, layouts, plugins, registerables, registry, scales };\n","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n module.exports = _typeof = function _typeof(obj) {\n return typeof obj;\n };\n\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n } else {\n module.exports = _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n }\n\n return _typeof(obj);\n}\n\nmodule.exports = _typeof;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nimport possibleConstructorReturn from \"./possibleConstructorReturn.js\";\nexport default function _createSuper(Derived) {\n var hasNativeReflectConstruct = isNativeReflectConstruct();\n return function _createSuperInternal() {\n var Super = getPrototypeOf(Derived),\n result;\n\n if (hasNativeReflectConstruct) {\n var NewTarget = getPrototypeOf(this).constructor;\n result = Reflect.construct(Super, arguments, NewTarget);\n } else {\n result = Super.apply(this, arguments);\n }\n\n return possibleConstructorReturn(this, result);\n };\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _inherits from \"@babel/runtime/helpers/esm/inherits\";\nimport _createSuper from \"@babel/runtime/helpers/esm/createSuper\";\nimport * as React from 'react';\nimport devWarning from '../_util/devWarning';\nimport { changeConfirmLocale } from '../modal/locale';\nimport LocaleContext from './context';\nexport var ANT_MARK = 'internalMark';\n\nvar LocaleProvider = /*#__PURE__*/function (_React$Component) {\n _inherits(LocaleProvider, _React$Component);\n\n var _super = _createSuper(LocaleProvider);\n\n function LocaleProvider(props) {\n var _this;\n\n _classCallCheck(this, LocaleProvider);\n\n _this = _super.call(this, props);\n changeConfirmLocale(props.locale && props.locale.Modal);\n devWarning(props._ANT_MARK__ === ANT_MARK, 'LocaleProvider', '`LocaleProvider` is deprecated. Please use `locale` with `ConfigProvider` instead: http://u.ant.design/locale');\n return _this;\n }\n\n _createClass(LocaleProvider, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n changeConfirmLocale(this.props.locale && this.props.locale.Modal);\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate(prevProps) {\n var locale = this.props.locale;\n\n if (prevProps.locale !== locale) {\n changeConfirmLocale(locale && locale.Modal);\n }\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n changeConfirmLocale();\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$props = this.props,\n locale = _this$props.locale,\n children = _this$props.children;\n return /*#__PURE__*/React.createElement(LocaleContext.Provider, {\n value: _extends(_extends({}, locale), {\n exist: true\n })\n }, children);\n }\n }]);\n\n return LocaleProvider;\n}(React.Component);\n\nexport { LocaleProvider as default };\nLocaleProvider.defaultProps = {\n locale: {}\n};","// This icon file is generated automatically.\nvar ExclamationCircleFilled = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm-32 232c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V296zm32 440a48.01 48.01 0 010-96 48.01 48.01 0 010 96z\" } }] }, \"name\": \"exclamation-circle\", \"theme\": \"filled\" };\nexport default ExclamationCircleFilled;\n","// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\nimport * as React from 'react';\nimport ExclamationCircleFilledSvg from \"@ant-design/icons-svg/es/asn/ExclamationCircleFilled\";\nimport AntdIcon from '../components/AntdIcon';\n\nvar ExclamationCircleFilled = function ExclamationCircleFilled(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, Object.assign({}, props, {\n ref: ref,\n icon: ExclamationCircleFilledSvg\n }));\n};\n\nExclamationCircleFilled.displayName = 'ExclamationCircleFilled';\nexport default /*#__PURE__*/React.forwardRef(ExclamationCircleFilled);","// This icon file is generated automatically.\nvar CheckCircleFilled = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z\" } }] }, \"name\": \"check-circle\", \"theme\": \"filled\" };\nexport default CheckCircleFilled;\n","// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\nimport * as React from 'react';\nimport CheckCircleFilledSvg from \"@ant-design/icons-svg/es/asn/CheckCircleFilled\";\nimport AntdIcon from '../components/AntdIcon';\n\nvar CheckCircleFilled = function CheckCircleFilled(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, Object.assign({}, props, {\n ref: ref,\n icon: CheckCircleFilledSvg\n }));\n};\n\nCheckCircleFilled.displayName = 'CheckCircleFilled';\nexport default /*#__PURE__*/React.forwardRef(CheckCircleFilled);","// This icon file is generated automatically.\nvar InfoCircleFilled = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z\" } }] }, \"name\": \"info-circle\", \"theme\": \"filled\" };\nexport default InfoCircleFilled;\n","// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\nimport * as React from 'react';\nimport InfoCircleFilledSvg from \"@ant-design/icons-svg/es/asn/InfoCircleFilled\";\nimport AntdIcon from '../components/AntdIcon';\n\nvar InfoCircleFilled = function InfoCircleFilled(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, Object.assign({}, props, {\n ref: ref,\n icon: InfoCircleFilledSvg\n }));\n};\n\nInfoCircleFilled.displayName = 'InfoCircleFilled';\nexport default /*#__PURE__*/React.forwardRef(InfoCircleFilled);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport RCNotification from 'rc-notification';\nimport LoadingOutlined from \"@ant-design/icons/es/icons/LoadingOutlined\";\nimport ExclamationCircleFilled from \"@ant-design/icons/es/icons/ExclamationCircleFilled\";\nimport CloseCircleFilled from \"@ant-design/icons/es/icons/CloseCircleFilled\";\nimport CheckCircleFilled from \"@ant-design/icons/es/icons/CheckCircleFilled\";\nimport InfoCircleFilled from \"@ant-design/icons/es/icons/InfoCircleFilled\";\nimport createUseMessage from './hooks/useMessage';\nimport { globalConfig } from '../config-provider';\nvar messageInstance;\nvar defaultDuration = 3;\nvar defaultTop;\nvar key = 1;\nvar localPrefixCls = '';\nvar transitionName = 'move-up';\nvar hasTransitionName = false;\nvar getContainer;\nvar maxCount;\nvar rtl = false;\nexport function getKeyThenIncreaseKey() {\n return key++;\n}\n\nfunction setMessageConfig(options) {\n if (options.top !== undefined) {\n defaultTop = options.top;\n messageInstance = null; // delete messageInstance for new defaultTop\n }\n\n if (options.duration !== undefined) {\n defaultDuration = options.duration;\n }\n\n if (options.prefixCls !== undefined) {\n localPrefixCls = options.prefixCls;\n }\n\n if (options.getContainer !== undefined) {\n getContainer = options.getContainer;\n }\n\n if (options.transitionName !== undefined) {\n transitionName = options.transitionName;\n messageInstance = null; // delete messageInstance for new transitionName\n\n hasTransitionName = true;\n }\n\n if (options.maxCount !== undefined) {\n maxCount = options.maxCount;\n messageInstance = null;\n }\n\n if (options.rtl !== undefined) {\n rtl = options.rtl;\n }\n}\n\nfunction getRCNotificationInstance(args, callback) {\n var customizePrefixCls = args.prefixCls;\n\n var _globalConfig = globalConfig(),\n getPrefixCls = _globalConfig.getPrefixCls,\n getRootPrefixCls = _globalConfig.getRootPrefixCls;\n\n var prefixCls = getPrefixCls('message', customizePrefixCls || localPrefixCls);\n var rootPrefixCls = getRootPrefixCls(args.rootPrefixCls, prefixCls);\n\n if (messageInstance) {\n callback({\n prefixCls: prefixCls,\n rootPrefixCls: rootPrefixCls,\n instance: messageInstance\n });\n return;\n }\n\n var instanceConfig = {\n prefixCls: prefixCls,\n transitionName: hasTransitionName ? transitionName : \"\".concat(rootPrefixCls, \"-\").concat(transitionName),\n style: {\n top: defaultTop\n },\n getContainer: getContainer,\n maxCount: maxCount\n };\n RCNotification.newInstance(instanceConfig, function (instance) {\n if (messageInstance) {\n callback({\n prefixCls: prefixCls,\n rootPrefixCls: rootPrefixCls,\n instance: messageInstance\n });\n return;\n }\n\n messageInstance = instance;\n\n if (process.env.NODE_ENV === 'test') {\n messageInstance.config = instanceConfig;\n }\n\n callback({\n prefixCls: prefixCls,\n rootPrefixCls: rootPrefixCls,\n instance: instance\n });\n });\n}\n\nvar typeToIcon = {\n info: InfoCircleFilled,\n success: CheckCircleFilled,\n error: CloseCircleFilled,\n warning: ExclamationCircleFilled,\n loading: LoadingOutlined\n};\n\nfunction getRCNoticeProps(args, prefixCls) {\n var _classNames;\n\n var duration = args.duration !== undefined ? args.duration : defaultDuration;\n var IconComponent = typeToIcon[args.type];\n var messageClass = classNames(\"\".concat(prefixCls, \"-custom-content\"), (_classNames = {}, _defineProperty(_classNames, \"\".concat(prefixCls, \"-\").concat(args.type), args.type), _defineProperty(_classNames, \"\".concat(prefixCls, \"-rtl\"), rtl === true), _classNames));\n return {\n key: args.key,\n duration: duration,\n style: args.style || {},\n className: args.className,\n content: /*#__PURE__*/React.createElement(\"div\", {\n className: messageClass\n }, args.icon || IconComponent && /*#__PURE__*/React.createElement(IconComponent, null), /*#__PURE__*/React.createElement(\"span\", null, args.content)),\n onClose: args.onClose,\n onClick: args.onClick\n };\n}\n\nfunction notice(args) {\n var target = args.key || key++;\n var closePromise = new Promise(function (resolve) {\n var callback = function callback() {\n if (typeof args.onClose === 'function') {\n args.onClose();\n }\n\n return resolve(true);\n };\n\n getRCNotificationInstance(args, function (_ref) {\n var prefixCls = _ref.prefixCls,\n instance = _ref.instance;\n instance.notice(getRCNoticeProps(_extends(_extends({}, args), {\n key: target,\n onClose: callback\n }), prefixCls));\n });\n });\n\n var result = function result() {\n if (messageInstance) {\n messageInstance.removeNotice(target);\n }\n };\n\n result.then = function (filled, rejected) {\n return closePromise.then(filled, rejected);\n };\n\n result.promise = closePromise;\n return result;\n}\n\nfunction isArgsProps(content) {\n return Object.prototype.toString.call(content) === '[object Object]' && !!content.content;\n}\n\nvar api = {\n open: notice,\n config: setMessageConfig,\n destroy: function destroy(messageKey) {\n if (messageInstance) {\n if (messageKey) {\n var _messageInstance = messageInstance,\n removeNotice = _messageInstance.removeNotice;\n removeNotice(messageKey);\n } else {\n var _messageInstance2 = messageInstance,\n destroy = _messageInstance2.destroy;\n destroy();\n messageInstance = null;\n }\n }\n }\n};\nexport function attachTypeApi(originalApi, type) {\n originalApi[type] = function (content, duration, onClose) {\n if (isArgsProps(content)) {\n return originalApi.open(_extends(_extends({}, content), {\n type: type\n }));\n }\n\n if (typeof duration === 'function') {\n onClose = duration;\n duration = undefined;\n }\n\n return originalApi.open({\n content: content,\n duration: duration,\n type: type,\n onClose: onClose\n });\n };\n}\n['success', 'info', 'warning', 'error', 'loading'].forEach(function (type) {\n return attachTypeApi(api, type);\n});\napi.warn = api.warning;\napi.useMessage = createUseMessage(getRCNotificationInstance, getRCNoticeProps);\n/** @private test Only function. Not work on production */\n\nexport var getInstance = function getInstance() {\n return process.env.NODE_ENV === 'test' ? messageInstance : null;\n};\nexport default api;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport * as React from 'react';\nimport useRCNotification from \"rc-notification/es/useNotification\";\nimport { ConfigConsumer } from '../../config-provider';\nimport { attachTypeApi, getKeyThenIncreaseKey } from '..';\nexport default function createUseMessage(getRcNotificationInstance, getRCNoticeProps) {\n var useMessage = function useMessage() {\n // We can only get content by render\n var getPrefixCls; // We create a proxy to handle delay created instance\n\n var innerInstance = null;\n var proxy = {\n add: function add(noticeProps, holderCallback) {\n innerInstance === null || innerInstance === void 0 ? void 0 : innerInstance.component.add(noticeProps, holderCallback);\n }\n };\n\n var _useRCNotification = useRCNotification(proxy),\n _useRCNotification2 = _slicedToArray(_useRCNotification, 2),\n hookNotify = _useRCNotification2[0],\n holder = _useRCNotification2[1];\n\n function notify(args) {\n var customizePrefixCls = args.prefixCls;\n var mergedPrefixCls = getPrefixCls('message', customizePrefixCls);\n var rootPrefixCls = getPrefixCls();\n var target = args.key || getKeyThenIncreaseKey();\n var closePromise = new Promise(function (resolve) {\n var callback = function callback() {\n if (typeof args.onClose === 'function') {\n args.onClose();\n }\n\n return resolve(true);\n };\n\n getRcNotificationInstance(_extends(_extends({}, args), {\n prefixCls: mergedPrefixCls,\n rootPrefixCls: rootPrefixCls\n }), function (_ref) {\n var prefixCls = _ref.prefixCls,\n instance = _ref.instance;\n innerInstance = instance;\n hookNotify(getRCNoticeProps(_extends(_extends({}, args), {\n key: target,\n onClose: callback\n }), prefixCls));\n });\n });\n\n var result = function result() {\n if (innerInstance) {\n innerInstance.removeNotice(target);\n }\n };\n\n result.then = function (filled, rejected) {\n return closePromise.then(filled, rejected);\n };\n\n result.promise = closePromise;\n return result;\n } // Fill functions\n\n\n var hookApiRef = React.useRef({});\n hookApiRef.current.open = notify;\n ['success', 'info', 'warning', 'error', 'loading'].forEach(function (type) {\n return attachTypeApi(hookApiRef.current, type);\n });\n return [hookApiRef.current, /*#__PURE__*/React.createElement(ConfigConsumer, {\n key: \"holder\"\n }, function (context) {\n getPrefixCls = context.getPrefixCls;\n return holder;\n })];\n };\n\n return useMessage;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport IconContext from \"@ant-design/icons/es/components/Context\";\nimport { FormProvider as RcFormProvider } from 'rc-field-form';\nimport useMemo from \"rc-util/es/hooks/useMemo\";\nimport LocaleProvider, { ANT_MARK } from '../locale-provider';\nimport LocaleReceiver from '../locale-provider/LocaleReceiver';\nimport { ConfigConsumer, ConfigContext } from './context';\nimport SizeContext, { SizeContextProvider } from './SizeContext';\nimport message from '../message';\nimport notification from '../notification';\nimport defaultLocale from '../locale/default';\nexport { ConfigContext, ConfigConsumer };\nexport var configConsumerProps = ['getTargetContainer', 'getPopupContainer', 'rootPrefixCls', 'getPrefixCls', 'renderEmpty', 'csp', 'autoInsertSpaceInButton', 'locale', 'pageHeader']; // These props is used by `useContext` directly in sub component\n\nvar PASSED_PROPS = ['getTargetContainer', 'getPopupContainer', 'renderEmpty', 'pageHeader', 'input', 'form'];\nexport var defaultPrefixCls = 'ant';\nvar globalPrefixCls;\n\nvar setGlobalConfig = function setGlobalConfig(params) {\n if (params.prefixCls !== undefined) {\n globalPrefixCls = params.prefixCls;\n }\n};\n\nfunction getGlobalPrefixCls() {\n return globalPrefixCls || defaultPrefixCls;\n}\n\nexport var globalConfig = function globalConfig() {\n return {\n getPrefixCls: function getPrefixCls(suffixCls, customizePrefixCls) {\n if (customizePrefixCls) return customizePrefixCls;\n return suffixCls ? \"\".concat(getGlobalPrefixCls(), \"-\").concat(suffixCls) : getGlobalPrefixCls();\n },\n getRootPrefixCls: function getRootPrefixCls(rootPrefixCls, customizePrefixCls) {\n // Customize rootPrefixCls is first priority\n if (rootPrefixCls) {\n return rootPrefixCls;\n } // If Global prefixCls provided, use this\n\n\n if (globalPrefixCls) {\n return globalPrefixCls;\n } // [Legacy] If customize prefixCls provided, we cut it to get the prefixCls\n\n\n if (customizePrefixCls && customizePrefixCls.includes('-')) {\n return customizePrefixCls.replace(/^(.*)-[^-]*$/, '$1');\n } // Fallback to default prefixCls\n\n\n return getGlobalPrefixCls();\n }\n };\n};\n\nvar ProviderChildren = function ProviderChildren(props) {\n var _a, _b;\n\n var children = props.children,\n csp = props.csp,\n autoInsertSpaceInButton = props.autoInsertSpaceInButton,\n form = props.form,\n locale = props.locale,\n componentSize = props.componentSize,\n direction = props.direction,\n space = props.space,\n virtual = props.virtual,\n dropdownMatchSelectWidth = props.dropdownMatchSelectWidth,\n legacyLocale = props.legacyLocale,\n parentContext = props.parentContext,\n iconPrefixCls = props.iconPrefixCls;\n var getPrefixCls = React.useCallback(function (suffixCls, customizePrefixCls) {\n var prefixCls = props.prefixCls;\n if (customizePrefixCls) return customizePrefixCls;\n var mergedPrefixCls = prefixCls || parentContext.getPrefixCls('');\n return suffixCls ? \"\".concat(mergedPrefixCls, \"-\").concat(suffixCls) : mergedPrefixCls;\n }, [parentContext.getPrefixCls, props.prefixCls]);\n\n var config = _extends(_extends({}, parentContext), {\n csp: csp,\n autoInsertSpaceInButton: autoInsertSpaceInButton,\n locale: locale || legacyLocale,\n direction: direction,\n space: space,\n virtual: virtual,\n dropdownMatchSelectWidth: dropdownMatchSelectWidth,\n getPrefixCls: getPrefixCls\n }); // Pass the props used by `useContext` directly with child component.\n // These props should merged into `config`.\n\n\n PASSED_PROPS.forEach(function (propName) {\n var propValue = props[propName];\n\n if (propValue) {\n config[propName] = propValue;\n }\n }); // https://github.com/ant-design/ant-design/issues/27617\n\n var memoedConfig = useMemo(function () {\n return config;\n }, config, function (prevConfig, currentConfig) {\n var prevKeys = Object.keys(prevConfig);\n var currentKeys = Object.keys(currentConfig);\n return prevKeys.length !== currentKeys.length || prevKeys.some(function (key) {\n return prevConfig[key] !== currentConfig[key];\n });\n });\n var memoIconContextValue = React.useMemo(function () {\n return {\n prefixCls: iconPrefixCls,\n csp: csp\n };\n }, [iconPrefixCls]);\n var childNode = children; // Additional Form provider\n\n var validateMessages = {};\n\n if (locale) {\n validateMessages = ((_a = locale.Form) === null || _a === void 0 ? void 0 : _a.defaultValidateMessages) || ((_b = defaultLocale.Form) === null || _b === void 0 ? void 0 : _b.defaultValidateMessages) || {};\n }\n\n if (form && form.validateMessages) {\n validateMessages = _extends(_extends({}, validateMessages), form.validateMessages);\n }\n\n if (Object.keys(validateMessages).length > 0) {\n childNode = /*#__PURE__*/React.createElement(RcFormProvider, {\n validateMessages: validateMessages\n }, children);\n }\n\n if (locale) {\n childNode = /*#__PURE__*/React.createElement(LocaleProvider, {\n locale: locale,\n _ANT_MARK__: ANT_MARK\n }, childNode);\n }\n\n if (iconPrefixCls) {\n childNode = /*#__PURE__*/React.createElement(IconContext.Provider, {\n value: memoIconContextValue\n }, childNode);\n }\n\n if (componentSize) {\n childNode = /*#__PURE__*/React.createElement(SizeContextProvider, {\n size: componentSize\n }, childNode);\n }\n\n return /*#__PURE__*/React.createElement(ConfigContext.Provider, {\n value: memoedConfig\n }, childNode);\n};\n\nvar ConfigProvider = function ConfigProvider(props) {\n React.useEffect(function () {\n if (props.direction) {\n message.config({\n rtl: props.direction === 'rtl'\n });\n notification.config({\n rtl: props.direction === 'rtl'\n });\n }\n }, [props.direction]);\n return /*#__PURE__*/React.createElement(LocaleReceiver, null, function (_, __, legacyLocale) {\n return /*#__PURE__*/React.createElement(ConfigConsumer, null, function (context) {\n return /*#__PURE__*/React.createElement(ProviderChildren, _extends({\n parentContext: context,\n legacyLocale: legacyLocale\n }, props));\n });\n });\n};\n/** @private internal Usage. do not use in your production */\n\n\nConfigProvider.ConfigContext = ConfigContext;\nConfigProvider.SizeContext = SizeContext;\nConfigProvider.config = setGlobalConfig;\nexport default ConfigProvider;","var _typeof = require(\"@babel/runtime/helpers/typeof\")[\"default\"];\n\nfunction _getRequireWildcardCache(nodeInterop) {\n if (typeof WeakMap !== \"function\") return null;\n var cacheBabelInterop = new WeakMap();\n var cacheNodeInterop = new WeakMap();\n return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) {\n return nodeInterop ? cacheNodeInterop : cacheBabelInterop;\n })(nodeInterop);\n}\n\nfunction _interopRequireWildcard(obj, nodeInterop) {\n if (!nodeInterop && obj && obj.__esModule) {\n return obj;\n }\n\n if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") {\n return {\n \"default\": obj\n };\n }\n\n var cache = _getRequireWildcardCache(nodeInterop);\n\n if (cache && cache.has(obj)) {\n return cache.get(obj);\n }\n\n var newObj = {};\n var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;\n\n for (var key in obj) {\n if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;\n\n if (desc && (desc.get || desc.set)) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n\n newObj[\"default\"] = obj;\n\n if (cache) {\n cache.set(obj, newObj);\n }\n\n return newObj;\n}\n\nmodule.exports = _interopRequireWildcard;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",null,"function _extends() {\n module.exports = _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n return _extends.apply(this, arguments);\n}\n\nmodule.exports = _extends;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import * as React from 'react';\nvar isValidElement = React.isValidElement;\nexport { isValidElement };\nexport function replaceElement(element, replacement, props) {\n if (!isValidElement(element)) return replacement;\n return /*#__PURE__*/React.cloneElement(element, typeof props === 'function' ? props(element.props || {}) : props);\n}\nexport function cloneElement(element, props) {\n return replaceElement(element, element, props);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport React from 'react';\nimport SvgIcon from '../SvgIcon';\n/**\n * Private module reserved for @material-ui/x packages.\n */\n\nexport default function createSvgIcon(path, displayName) {\n var Component = function Component(props, ref) {\n return /*#__PURE__*/React.createElement(SvgIcon, _extends({\n ref: ref\n }, props), path);\n };\n\n if (process.env.NODE_ENV !== 'production') {\n // Need to set `displayName` on the inner component for React.memo.\n // React prior to 16.14 ignores `displayName` on the wrapper.\n Component.displayName = \"\".concat(displayName, \"Icon\");\n }\n\n Component.muiName = SvgIcon.muiName;\n return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));\n}","import * as React from 'react';\nimport * as PropTypes from 'prop-types';\nimport { IUtils } from '@date-io/core/IUtils';\nimport { MaterialUiPickersDate } from './typings/date';\n\nexport const MuiPickersContext = React.createContext | null>(null);\n\nexport interface MuiPickersUtilsProviderProps {\n utils: any;\n children: React.ReactNode;\n locale?: any;\n libInstance?: any;\n}\n\nexport const MuiPickersUtilsProvider: React.FC = ({\n utils: Utils,\n children,\n locale,\n libInstance,\n}) => {\n const utils = React.useMemo(() => new Utils({ locale, instance: libInstance }), [\n Utils,\n libInstance,\n locale,\n ]);\n\n return ;\n};\n\nMuiPickersUtilsProvider.propTypes = {\n utils: PropTypes.func.isRequired,\n locale: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),\n children: PropTypes.oneOfType([\n PropTypes.element.isRequired,\n PropTypes.arrayOf(PropTypes.element.isRequired),\n ]).isRequired,\n};\n\nexport default MuiPickersUtilsProvider;\n","import { useContext } from 'react';\nimport { IUtils } from '@date-io/core/IUtils';\nimport { MaterialUiPickersDate } from '../../typings/date';\nimport { MuiPickersContext } from '../../MuiPickersUtilsProvider';\n\nexport const checkUtils = (utils: IUtils | null | undefined) => {\n if (!utils) {\n // tslint:disable-next-line\n throw new Error(\n 'Can not find utils in context. You either a) forgot to wrap your component tree in MuiPickersUtilsProvider; or b) mixed named and direct file imports. Recommendation: use named imports from the module index.'\n );\n }\n};\n\nexport function useUtils() {\n const utils = useContext(MuiPickersContext);\n checkUtils(utils);\n\n return utils!;\n}\n","export default function ownerDocument(node) {\n return node && node.ownerDocument || document;\n}","import * as React from 'react';\nimport { createContext, useContext, forwardRef, createElement, Fragment } from 'react';\nimport createCache from '@emotion/cache';\nimport _extends from '@babel/runtime/helpers/esm/extends';\nimport weakMemoize from '@emotion/weak-memoize';\nimport hoistNonReactStatics from '../_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js';\nimport { getRegisteredStyles, registerStyles, insertStyles } from '@emotion/utils';\nimport { serializeStyles } from '@emotion/serialize';\n\nvar hasOwnProperty = {}.hasOwnProperty;\n\nvar EmotionCacheContext = /* #__PURE__ */createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case\n// because this module is primarily intended for the browser and node\n// but it's also required in react native and similar environments sometimes\n// and we could have a special build just for that\n// but this is much easier and the native packages\n// might use a different theme context in the future anyway\ntypeof HTMLElement !== 'undefined' ? /* #__PURE__ */createCache({\n key: 'css'\n}) : null);\n\nif (process.env.NODE_ENV !== 'production') {\n EmotionCacheContext.displayName = 'EmotionCacheContext';\n}\n\nvar CacheProvider = EmotionCacheContext.Provider;\nvar __unsafe_useEmotionCache = function useEmotionCache() {\n return useContext(EmotionCacheContext);\n};\n\nvar withEmotionCache = function withEmotionCache(func) {\n // $FlowFixMe\n return /*#__PURE__*/forwardRef(function (props, ref) {\n // the cache will never be null in the browser\n var cache = useContext(EmotionCacheContext);\n return func(props, cache, ref);\n });\n};\n\nvar ThemeContext = /* #__PURE__ */createContext({});\n\nif (process.env.NODE_ENV !== 'production') {\n ThemeContext.displayName = 'EmotionThemeContext';\n}\n\nvar useTheme = function useTheme() {\n return useContext(ThemeContext);\n};\n\nvar getTheme = function getTheme(outerTheme, theme) {\n if (typeof theme === 'function') {\n var mergedTheme = theme(outerTheme);\n\n if (process.env.NODE_ENV !== 'production' && (mergedTheme == null || typeof mergedTheme !== 'object' || Array.isArray(mergedTheme))) {\n throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!');\n }\n\n return mergedTheme;\n }\n\n if (process.env.NODE_ENV !== 'production' && (theme == null || typeof theme !== 'object' || Array.isArray(theme))) {\n throw new Error('[ThemeProvider] Please make your theme prop a plain object');\n }\n\n return _extends({}, outerTheme, theme);\n};\n\nvar createCacheWithTheme = /* #__PURE__ */weakMemoize(function (outerTheme) {\n return weakMemoize(function (theme) {\n return getTheme(outerTheme, theme);\n });\n});\nvar ThemeProvider = function ThemeProvider(props) {\n var theme = useContext(ThemeContext);\n\n if (props.theme !== theme) {\n theme = createCacheWithTheme(theme)(props.theme);\n }\n\n return /*#__PURE__*/createElement(ThemeContext.Provider, {\n value: theme\n }, props.children);\n};\nfunction withTheme(Component) {\n var componentName = Component.displayName || Component.name || 'Component';\n\n var render = function render(props, ref) {\n var theme = useContext(ThemeContext);\n return /*#__PURE__*/createElement(Component, _extends({\n theme: theme,\n ref: ref\n }, props));\n }; // $FlowFixMe\n\n\n var WithTheme = /*#__PURE__*/forwardRef(render);\n WithTheme.displayName = \"WithTheme(\" + componentName + \")\";\n return hoistNonReactStatics(WithTheme, Component);\n}\n\nvar getLastPart = function getLastPart(functionName) {\n // The match may be something like 'Object.createEmotionProps' or\n // 'Loader.prototype.render'\n var parts = functionName.split('.');\n return parts[parts.length - 1];\n};\n\nvar getFunctionNameFromStackTraceLine = function getFunctionNameFromStackTraceLine(line) {\n // V8\n var match = /^\\s+at\\s+([A-Za-z0-9$.]+)\\s/.exec(line);\n if (match) return getLastPart(match[1]); // Safari / Firefox\n\n match = /^([A-Za-z0-9$.]+)@/.exec(line);\n if (match) return getLastPart(match[1]);\n return undefined;\n};\n\nvar internalReactFunctionNames = /* #__PURE__ */new Set(['renderWithHooks', 'processChild', 'finishClassComponent', 'renderToString']); // These identifiers come from error stacks, so they have to be valid JS\n// identifiers, thus we only need to replace what is a valid character for JS,\n// but not for CSS.\n\nvar sanitizeIdentifier = function sanitizeIdentifier(identifier) {\n return identifier.replace(/\\$/g, '-');\n};\n\nvar getLabelFromStackTrace = function getLabelFromStackTrace(stackTrace) {\n if (!stackTrace) return undefined;\n var lines = stackTrace.split('\\n');\n\n for (var i = 0; i < lines.length; i++) {\n var functionName = getFunctionNameFromStackTraceLine(lines[i]); // The first line of V8 stack traces is just \"Error\"\n\n if (!functionName) continue; // If we reach one of these, we have gone too far and should quit\n\n if (internalReactFunctionNames.has(functionName)) break; // The component name is the first function in the stack that starts with an\n // uppercase letter\n\n if (/^[A-Z]/.test(functionName)) return sanitizeIdentifier(functionName);\n }\n\n return undefined;\n};\n\nvar useInsertionEffect = React['useInsertion' + 'Effect'] ? React['useInsertion' + 'Effect'] : function useInsertionEffect(create) {\n create();\n};\nfunction useInsertionEffectMaybe(create) {\n\n useInsertionEffect(create);\n}\n\nvar typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';\nvar labelPropName = '__EMOTION_LABEL_PLEASE_DO_NOT_USE__';\nvar createEmotionProps = function createEmotionProps(type, props) {\n if (process.env.NODE_ENV !== 'production' && typeof props.css === 'string' && // check if there is a css declaration\n props.css.indexOf(':') !== -1) {\n throw new Error(\"Strings are not allowed as css prop values, please wrap it in a css template literal from '@emotion/react' like this: css`\" + props.css + \"`\");\n }\n\n var newProps = {};\n\n for (var key in props) {\n if (hasOwnProperty.call(props, key)) {\n newProps[key] = props[key];\n }\n }\n\n newProps[typePropName] = type; // For performance, only call getLabelFromStackTrace in development and when\n // the label hasn't already been computed\n\n if (process.env.NODE_ENV !== 'production' && !!props.css && (typeof props.css !== 'object' || typeof props.css.name !== 'string' || props.css.name.indexOf('-') === -1)) {\n var label = getLabelFromStackTrace(new Error().stack);\n if (label) newProps[labelPropName] = label;\n }\n\n return newProps;\n};\n\nvar Insertion = function Insertion(_ref) {\n var cache = _ref.cache,\n serialized = _ref.serialized,\n isStringTag = _ref.isStringTag;\n registerStyles(cache, serialized, isStringTag);\n var rules = useInsertionEffectMaybe(function () {\n return insertStyles(cache, serialized, isStringTag);\n });\n\n return null;\n};\n\nvar Emotion = /* #__PURE__ */withEmotionCache(function (props, cache, ref) {\n var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works\n // not passing the registered cache to serializeStyles because it would\n // make certain babel optimisations not possible\n\n if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {\n cssProp = cache.registered[cssProp];\n }\n\n var WrappedComponent = props[typePropName];\n var registeredStyles = [cssProp];\n var className = '';\n\n if (typeof props.className === 'string') {\n className = getRegisteredStyles(cache.registered, registeredStyles, props.className);\n } else if (props.className != null) {\n className = props.className + \" \";\n }\n\n var serialized = serializeStyles(registeredStyles, undefined, useContext(ThemeContext));\n\n if (process.env.NODE_ENV !== 'production' && serialized.name.indexOf('-') === -1) {\n var labelFromStack = props[labelPropName];\n\n if (labelFromStack) {\n serialized = serializeStyles([serialized, 'label:' + labelFromStack + ';']);\n }\n }\n\n className += cache.key + \"-\" + serialized.name;\n var newProps = {};\n\n for (var key in props) {\n if (hasOwnProperty.call(props, key) && key !== 'css' && key !== typePropName && (process.env.NODE_ENV === 'production' || key !== labelPropName)) {\n newProps[key] = props[key];\n }\n }\n\n newProps.ref = ref;\n newProps.className = className;\n return /*#__PURE__*/createElement(Fragment, null, /*#__PURE__*/createElement(Insertion, {\n cache: cache,\n serialized: serialized,\n isStringTag: typeof WrappedComponent === 'string'\n }), /*#__PURE__*/createElement(WrappedComponent, newProps));\n});\n\nif (process.env.NODE_ENV !== 'production') {\n Emotion.displayName = 'EmotionCssPropInternal';\n}\n\nexport { CacheProvider as C, Emotion as E, ThemeContext as T, __unsafe_useEmotionCache as _, useTheme as a, ThemeProvider as b, createEmotionProps as c, withTheme as d, hasOwnProperty as h, useInsertionEffectMaybe as u, withEmotionCache as w };\n","import _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport canUseDOM from \"rc-util/es/Dom/canUseDom\"; // ================= Transition =================\n// Event wrapper. Copy from react source code\n\nfunction makePrefixMap(styleProp, eventName) {\n var prefixes = {};\n prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();\n prefixes[\"Webkit\".concat(styleProp)] = \"webkit\".concat(eventName);\n prefixes[\"Moz\".concat(styleProp)] = \"moz\".concat(eventName);\n prefixes[\"ms\".concat(styleProp)] = \"MS\".concat(eventName);\n prefixes[\"O\".concat(styleProp)] = \"o\".concat(eventName.toLowerCase());\n return prefixes;\n}\n\nexport function getVendorPrefixes(domSupport, win) {\n var prefixes = {\n animationend: makePrefixMap('Animation', 'AnimationEnd'),\n transitionend: makePrefixMap('Transition', 'TransitionEnd')\n };\n\n if (domSupport) {\n if (!('AnimationEvent' in win)) {\n delete prefixes.animationend.animation;\n }\n\n if (!('TransitionEvent' in win)) {\n delete prefixes.transitionend.transition;\n }\n }\n\n return prefixes;\n}\nvar vendorPrefixes = getVendorPrefixes(canUseDOM(), typeof window !== 'undefined' ? window : {});\nvar style = {};\n\nif (canUseDOM()) {\n var _document$createEleme = document.createElement('div');\n\n style = _document$createEleme.style;\n}\n\nvar prefixedEventNames = {};\nexport function getVendorPrefixedEventName(eventName) {\n if (prefixedEventNames[eventName]) {\n return prefixedEventNames[eventName];\n }\n\n var prefixMap = vendorPrefixes[eventName];\n\n if (prefixMap) {\n var stylePropList = Object.keys(prefixMap);\n var len = stylePropList.length;\n\n for (var i = 0; i < len; i += 1) {\n var styleProp = stylePropList[i];\n\n if (Object.prototype.hasOwnProperty.call(prefixMap, styleProp) && styleProp in style) {\n prefixedEventNames[eventName] = prefixMap[styleProp];\n return prefixedEventNames[eventName];\n }\n }\n }\n\n return '';\n}\nvar internalAnimationEndName = getVendorPrefixedEventName('animationend');\nvar internalTransitionEndName = getVendorPrefixedEventName('transitionend');\nexport var supportTransition = !!(internalAnimationEndName && internalTransitionEndName);\nexport var animationEndName = internalAnimationEndName || 'animationend';\nexport var transitionEndName = internalTransitionEndName || 'transitionend';\nexport function getTransitionName(transitionName, transitionType) {\n if (!transitionName) return null;\n\n if (_typeof(transitionName) === 'object') {\n var type = transitionType.replace(/-\\w/g, function (match) {\n return match[1].toUpperCase();\n });\n return transitionName[type];\n }\n\n return \"\".concat(transitionName, \"-\").concat(transitionType);\n}","export var STATUS_NONE = 'none';\nexport var STATUS_APPEAR = 'appear';\nexport var STATUS_ENTER = 'enter';\nexport var STATUS_LEAVE = 'leave';\nexport var STEP_NONE = 'none';\nexport var STEP_PREPARE = 'prepare';\nexport var STEP_START = 'start';\nexport var STEP_ACTIVE = 'active';\nexport var STEP_ACTIVATED = 'end';","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport { useEffect, useState, useRef } from 'react';\nexport default function useMountStatus(defaultValue) {\n var destroyRef = useRef(false);\n\n var _useState = useState(defaultValue),\n _useState2 = _slicedToArray(_useState, 2),\n val = _useState2[0],\n setVal = _useState2[1];\n\n function setValue(next) {\n if (!destroyRef.current) {\n setVal(next);\n }\n }\n\n useEffect(function () {\n return function () {\n destroyRef.current = true;\n };\n }, []);\n return [val, setValue];\n}","import { useEffect, useLayoutEffect } from 'react';\nimport canUseDom from \"rc-util/es/Dom/canUseDom\"; // It's safe to use `useLayoutEffect` but the warning is annoying\n\nvar useIsomorphicLayoutEffect = canUseDom() ? useLayoutEffect : useEffect;\nexport default useIsomorphicLayoutEffect;","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport * as React from 'react';\nimport { STEP_PREPARE, STEP_ACTIVE, STEP_START, STEP_ACTIVATED, STEP_NONE } from '../interface';\nimport useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect';\nimport useNextFrame from './useNextFrame';\nvar STEP_QUEUE = [STEP_PREPARE, STEP_START, STEP_ACTIVE, STEP_ACTIVATED];\n/** Skip current step */\n\nexport var SkipStep = false;\n/** Current step should be update in */\n\nexport var DoStep = true;\nexport function isActive(step) {\n return step === STEP_ACTIVE || step === STEP_ACTIVATED;\n}\nexport default (function (status, callback) {\n var _React$useState = React.useState(STEP_NONE),\n _React$useState2 = _slicedToArray(_React$useState, 2),\n step = _React$useState2[0],\n setStep = _React$useState2[1];\n\n var _useNextFrame = useNextFrame(),\n _useNextFrame2 = _slicedToArray(_useNextFrame, 2),\n nextFrame = _useNextFrame2[0],\n cancelNextFrame = _useNextFrame2[1];\n\n function startQueue() {\n setStep(STEP_PREPARE);\n }\n\n useIsomorphicLayoutEffect(function () {\n if (step !== STEP_NONE && step !== STEP_ACTIVATED) {\n var index = STEP_QUEUE.indexOf(step);\n var nextStep = STEP_QUEUE[index + 1];\n var result = callback(step);\n\n if (result === SkipStep) {\n // Skip when no needed\n setStep(nextStep);\n } else {\n // Do as frame for step update\n nextFrame(function (info) {\n function doNext() {\n // Skip since current queue is ood\n if (info.isCanceled()) return;\n setStep(nextStep);\n }\n\n if (result === true) {\n doNext();\n } else {\n // Only promise should be async\n Promise.resolve(result).then(doNext);\n }\n });\n }\n }\n }, [status, step]);\n React.useEffect(function () {\n return function () {\n cancelNextFrame();\n };\n }, []);\n return [startQueue, step];\n});","import * as React from 'react';\nimport raf from \"rc-util/es/raf\";\nexport default (function () {\n var nextFrameRef = React.useRef(null);\n\n function cancelNextFrame() {\n raf.cancel(nextFrameRef.current);\n }\n\n function nextFrame(callback) {\n var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;\n cancelNextFrame();\n var nextFrameId = raf(function () {\n if (delay <= 1) {\n callback({\n isCanceled: function isCanceled() {\n return nextFrameId !== nextFrameRef.current;\n }\n });\n } else {\n nextFrame(callback, delay - 1);\n }\n });\n nextFrameRef.current = nextFrameId;\n }\n\n React.useEffect(function () {\n return function () {\n cancelNextFrame();\n };\n }, []);\n return [nextFrame, cancelNextFrame];\n});","import _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport * as React from 'react';\nimport { useRef, useEffect } from 'react';\nimport { STATUS_APPEAR, STATUS_NONE, STATUS_LEAVE, STATUS_ENTER, STEP_PREPARE, STEP_START, STEP_ACTIVE } from '../interface';\nimport useState from './useState';\nimport useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect';\nimport useStepQueue, { DoStep, SkipStep, isActive } from './useStepQueue';\nimport useDomMotionEvents from './useDomMotionEvents';\nexport default function useStatus(supportMotion, visible, getElement, _ref) {\n var _ref$motionEnter = _ref.motionEnter,\n motionEnter = _ref$motionEnter === void 0 ? true : _ref$motionEnter,\n _ref$motionAppear = _ref.motionAppear,\n motionAppear = _ref$motionAppear === void 0 ? true : _ref$motionAppear,\n _ref$motionLeave = _ref.motionLeave,\n motionLeave = _ref$motionLeave === void 0 ? true : _ref$motionLeave,\n motionDeadline = _ref.motionDeadline,\n motionLeaveImmediately = _ref.motionLeaveImmediately,\n onAppearPrepare = _ref.onAppearPrepare,\n onEnterPrepare = _ref.onEnterPrepare,\n onLeavePrepare = _ref.onLeavePrepare,\n onAppearStart = _ref.onAppearStart,\n onEnterStart = _ref.onEnterStart,\n onLeaveStart = _ref.onLeaveStart,\n onAppearActive = _ref.onAppearActive,\n onEnterActive = _ref.onEnterActive,\n onLeaveActive = _ref.onLeaveActive,\n onAppearEnd = _ref.onAppearEnd,\n onEnterEnd = _ref.onEnterEnd,\n onLeaveEnd = _ref.onLeaveEnd,\n onVisibleChanged = _ref.onVisibleChanged;\n\n // Used for outer render usage to avoid `visible: false & status: none` to render nothing\n var _useState = useState(),\n _useState2 = _slicedToArray(_useState, 2),\n asyncVisible = _useState2[0],\n setAsyncVisible = _useState2[1];\n\n var _useState3 = useState(STATUS_NONE),\n _useState4 = _slicedToArray(_useState3, 2),\n status = _useState4[0],\n setStatus = _useState4[1];\n\n var _useState5 = useState(null),\n _useState6 = _slicedToArray(_useState5, 2),\n style = _useState6[0],\n setStyle = _useState6[1];\n\n var mountedRef = useRef(false);\n var deadlineRef = useRef(null);\n var destroyedRef = useRef(false); // =========================== Dom Node ===========================\n\n var cacheElementRef = useRef(null);\n\n function getDomElement() {\n var element = getElement();\n return element || cacheElementRef.current;\n } // ========================== Motion End ==========================\n\n\n var activeRef = useRef(false);\n\n function onInternalMotionEnd(event) {\n var element = getDomElement();\n\n if (event && !event.deadline && event.target !== element) {\n // event exists\n // not initiated by deadline\n // transitionEnd not fired by inner elements\n return;\n }\n\n var canEnd;\n\n if (status === STATUS_APPEAR && activeRef.current) {\n canEnd = onAppearEnd === null || onAppearEnd === void 0 ? void 0 : onAppearEnd(element, event);\n } else if (status === STATUS_ENTER && activeRef.current) {\n canEnd = onEnterEnd === null || onEnterEnd === void 0 ? void 0 : onEnterEnd(element, event);\n } else if (status === STATUS_LEAVE && activeRef.current) {\n canEnd = onLeaveEnd === null || onLeaveEnd === void 0 ? void 0 : onLeaveEnd(element, event);\n } // Only update status when `canEnd` and not destroyed\n\n\n if (canEnd !== false && !destroyedRef.current) {\n setStatus(STATUS_NONE);\n setStyle(null);\n }\n }\n\n var _useDomMotionEvents = useDomMotionEvents(onInternalMotionEnd),\n _useDomMotionEvents2 = _slicedToArray(_useDomMotionEvents, 1),\n patchMotionEvents = _useDomMotionEvents2[0]; // ============================= Step =============================\n\n\n var eventHandlers = React.useMemo(function () {\n var _ref2, _ref3, _ref4;\n\n switch (status) {\n case 'appear':\n return _ref2 = {}, _defineProperty(_ref2, STEP_PREPARE, onAppearPrepare), _defineProperty(_ref2, STEP_START, onAppearStart), _defineProperty(_ref2, STEP_ACTIVE, onAppearActive), _ref2;\n\n case 'enter':\n return _ref3 = {}, _defineProperty(_ref3, STEP_PREPARE, onEnterPrepare), _defineProperty(_ref3, STEP_START, onEnterStart), _defineProperty(_ref3, STEP_ACTIVE, onEnterActive), _ref3;\n\n case 'leave':\n return _ref4 = {}, _defineProperty(_ref4, STEP_PREPARE, onLeavePrepare), _defineProperty(_ref4, STEP_START, onLeaveStart), _defineProperty(_ref4, STEP_ACTIVE, onLeaveActive), _ref4;\n\n default:\n return {};\n }\n }, [status]);\n\n var _useStepQueue = useStepQueue(status, function (newStep) {\n // Only prepare step can be skip\n if (newStep === STEP_PREPARE) {\n var onPrepare = eventHandlers[STEP_PREPARE];\n\n if (!onPrepare) {\n return SkipStep;\n }\n\n return onPrepare(getDomElement());\n } // Rest step is sync update\n\n\n // Rest step is sync update\n if (step in eventHandlers) {\n var _eventHandlers$step;\n\n setStyle(((_eventHandlers$step = eventHandlers[step]) === null || _eventHandlers$step === void 0 ? void 0 : _eventHandlers$step.call(eventHandlers, getDomElement(), null)) || null);\n }\n\n if (step === STEP_ACTIVE) {\n // Patch events when motion needed\n patchMotionEvents(getDomElement());\n\n if (motionDeadline > 0) {\n clearTimeout(deadlineRef.current);\n deadlineRef.current = setTimeout(function () {\n onInternalMotionEnd({\n deadline: true\n });\n }, motionDeadline);\n }\n }\n\n return DoStep;\n }),\n _useStepQueue2 = _slicedToArray(_useStepQueue, 2),\n startStep = _useStepQueue2[0],\n step = _useStepQueue2[1];\n\n var active = isActive(step);\n activeRef.current = active; // ============================ Status ============================\n // Update with new status\n\n useIsomorphicLayoutEffect(function () {\n setAsyncVisible(visible);\n var isMounted = mountedRef.current;\n mountedRef.current = true;\n\n if (!supportMotion) {\n return;\n }\n\n var nextStatus; // Appear\n\n if (!isMounted && visible && motionAppear) {\n nextStatus = STATUS_APPEAR;\n } // Enter\n\n\n if (isMounted && visible && motionEnter) {\n nextStatus = STATUS_ENTER;\n } // Leave\n\n\n if (isMounted && !visible && motionLeave || !isMounted && motionLeaveImmediately && !visible && motionLeave) {\n nextStatus = STATUS_LEAVE;\n } // Update to next status\n\n\n if (nextStatus) {\n setStatus(nextStatus);\n startStep();\n }\n }, [visible]); // ============================ Effect ============================\n // Reset when motion changed\n\n useEffect(function () {\n if ( // Cancel appear\n status === STATUS_APPEAR && !motionAppear || // Cancel enter\n status === STATUS_ENTER && !motionEnter || // Cancel leave\n status === STATUS_LEAVE && !motionLeave) {\n setStatus(STATUS_NONE);\n }\n }, [motionAppear, motionEnter, motionLeave]);\n useEffect(function () {\n return function () {\n clearTimeout(deadlineRef.current);\n destroyedRef.current = true;\n };\n }, []); // Trigger `onVisibleChanged`\n\n useEffect(function () {\n if (asyncVisible !== undefined && status === STATUS_NONE) {\n onVisibleChanged === null || onVisibleChanged === void 0 ? void 0 : onVisibleChanged(asyncVisible);\n }\n }, [asyncVisible, status]); // ============================ Styles ============================\n\n var mergedStyle = style;\n\n if (eventHandlers[STEP_PREPARE] && step === STEP_START) {\n mergedStyle = _objectSpread({\n transition: 'none'\n }, mergedStyle);\n }\n\n return [status, step, mergedStyle, asyncVisible !== null && asyncVisible !== void 0 ? asyncVisible : visible];\n}","import * as React from 'react';\nimport { useRef } from 'react';\nimport { animationEndName, transitionEndName } from '../util/motion';\nexport default (function (callback) {\n var cacheElementRef = useRef(); // Cache callback\n\n var callbackRef = useRef(callback);\n callbackRef.current = callback; // Internal motion event handler\n\n var onInternalMotionEnd = React.useCallback(function (event) {\n callbackRef.current(event);\n }, []); // Remove events\n\n function removeMotionEvents(element) {\n if (element) {\n element.removeEventListener(transitionEndName, onInternalMotionEnd);\n element.removeEventListener(animationEndName, onInternalMotionEnd);\n }\n } // Patch events\n\n\n function patchMotionEvents(element) {\n if (cacheElementRef.current && cacheElementRef.current !== element) {\n removeMotionEvents(cacheElementRef.current);\n }\n\n if (element && element !== cacheElementRef.current) {\n element.addEventListener(transitionEndName, onInternalMotionEnd);\n element.addEventListener(animationEndName, onInternalMotionEnd); // Save as cache in case dom removed trigger by `motionDeadline`\n\n cacheElementRef.current = element;\n }\n } // Clean up when removed\n\n\n React.useEffect(function () {\n return function () {\n removeMotionEvents(cacheElementRef.current);\n };\n }, []);\n return [patchMotionEvents, removeMotionEvents];\n});","import _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _inherits from \"@babel/runtime/helpers/esm/inherits\";\nimport _createSuper from \"@babel/runtime/helpers/esm/createSuper\";\nimport * as React from 'react';\n\nvar DomWrapper = /*#__PURE__*/function (_React$Component) {\n _inherits(DomWrapper, _React$Component);\n\n var _super = _createSuper(DomWrapper);\n\n function DomWrapper() {\n _classCallCheck(this, DomWrapper);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(DomWrapper, [{\n key: \"render\",\n value: function render() {\n return this.props.children;\n }\n }]);\n\n return DomWrapper;\n}(React.Component);\n\nexport default DomWrapper;","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\n\n/* eslint-disable react/default-props-match-prop-types, react/no-multi-comp, react/prop-types */\nimport * as React from 'react';\nimport { useRef } from 'react';\nimport findDOMNode from \"rc-util/es/Dom/findDOMNode\";\nimport { fillRef } from \"rc-util/es/ref\";\nimport classNames from 'classnames';\nimport { getTransitionName, supportTransition } from './util/motion';\nimport { STATUS_NONE, STEP_PREPARE, STEP_START } from './interface';\nimport useStatus from './hooks/useStatus';\nimport DomWrapper from './DomWrapper';\nimport { isActive } from './hooks/useStepQueue';\n/**\n * `transitionSupport` is used for none transition test case.\n * Default we use browser transition event support check.\n */\n\nexport function genCSSMotion(config) {\n var transitionSupport = config;\n\n if (_typeof(config) === 'object') {\n transitionSupport = config.transitionSupport;\n }\n\n function isSupportTransition(props) {\n return !!(props.motionName && transitionSupport);\n }\n\n var CSSMotion = /*#__PURE__*/React.forwardRef(function (props, ref) {\n var _props$visible = props.visible,\n visible = _props$visible === void 0 ? true : _props$visible,\n _props$removeOnLeave = props.removeOnLeave,\n removeOnLeave = _props$removeOnLeave === void 0 ? true : _props$removeOnLeave,\n forceRender = props.forceRender,\n children = props.children,\n motionName = props.motionName,\n leavedClassName = props.leavedClassName,\n eventProps = props.eventProps;\n var supportMotion = isSupportTransition(props); // Ref to the react node, it may be a HTMLElement\n\n var nodeRef = useRef(); // Ref to the dom wrapper in case ref can not pass to HTMLElement\n\n var wrapperNodeRef = useRef();\n\n function getDomElement() {\n try {\n return findDOMNode(nodeRef.current || wrapperNodeRef.current);\n } catch (e) {\n // Only happen when `motionDeadline` trigger but element removed.\n return null;\n }\n }\n\n var _useStatus = useStatus(supportMotion, visible, getDomElement, props),\n _useStatus2 = _slicedToArray(_useStatus, 4),\n status = _useStatus2[0],\n statusStep = _useStatus2[1],\n statusStyle = _useStatus2[2],\n mergedVisible = _useStatus2[3]; // Record whether content has rended\n // Will return null for un-rendered even when `removeOnLeave={false}`\n\n\n var renderedRef = React.useRef(mergedVisible);\n\n if (mergedVisible) {\n renderedRef.current = true;\n } // ====================== Refs ======================\n\n\n var originRef = useRef(ref);\n originRef.current = ref;\n var setNodeRef = React.useCallback(function (node) {\n nodeRef.current = node;\n fillRef(originRef.current, node);\n }, []); // ===================== Render =====================\n\n var motionChildren;\n\n var mergedProps = _objectSpread(_objectSpread({}, eventProps), {}, {\n visible: visible\n });\n\n if (!children) {\n // No children\n motionChildren = null;\n } else if (status === STATUS_NONE || !isSupportTransition(props)) {\n // Stable children\n if (mergedVisible) {\n motionChildren = children(_objectSpread({}, mergedProps), setNodeRef);\n } else if (!removeOnLeave && renderedRef.current) {\n motionChildren = children(_objectSpread(_objectSpread({}, mergedProps), {}, {\n className: leavedClassName\n }), setNodeRef);\n } else if (forceRender) {\n motionChildren = children(_objectSpread(_objectSpread({}, mergedProps), {}, {\n style: {\n display: 'none'\n }\n }), setNodeRef);\n } else {\n motionChildren = null;\n }\n } else {\n var _classNames;\n\n // In motion\n var statusSuffix;\n\n if (statusStep === STEP_PREPARE) {\n statusSuffix = 'prepare';\n } else if (isActive(statusStep)) {\n statusSuffix = 'active';\n } else if (statusStep === STEP_START) {\n statusSuffix = 'start';\n }\n\n motionChildren = children(_objectSpread(_objectSpread({}, mergedProps), {}, {\n className: classNames(getTransitionName(motionName, status), (_classNames = {}, _defineProperty(_classNames, getTransitionName(motionName, \"\".concat(status, \"-\").concat(statusSuffix)), statusSuffix), _defineProperty(_classNames, motionName, typeof motionName === 'string'), _classNames)),\n style: statusStyle\n }), setNodeRef);\n }\n\n return /*#__PURE__*/React.createElement(DomWrapper, {\n ref: wrapperNodeRef\n }, motionChildren);\n });\n CSSMotion.displayName = 'CSSMotion';\n return CSSMotion;\n}\nexport default genCSSMotion(supportTransition);","import _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nexport var STATUS_ADD = 'add';\nexport var STATUS_KEEP = 'keep';\nexport var STATUS_REMOVE = 'remove';\nexport var STATUS_REMOVED = 'removed';\nexport function wrapKeyToObject(key) {\n var keyObj;\n\n if (key && _typeof(key) === 'object' && 'key' in key) {\n keyObj = key;\n } else {\n keyObj = {\n key: key\n };\n }\n\n return _objectSpread(_objectSpread({}, keyObj), {}, {\n key: String(keyObj.key)\n });\n}\nexport function parseKeys() {\n var keys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n return keys.map(wrapKeyToObject);\n}\nexport function diffKeys() {\n var prevKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n var currentKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n var list = [];\n var currentIndex = 0;\n var currentLen = currentKeys.length;\n var prevKeyObjects = parseKeys(prevKeys);\n var currentKeyObjects = parseKeys(currentKeys); // Check prev keys to insert or keep\n\n prevKeyObjects.forEach(function (keyObj) {\n var hit = false;\n\n for (var i = currentIndex; i < currentLen; i += 1) {\n var currentKeyObj = currentKeyObjects[i];\n\n if (currentKeyObj.key === keyObj.key) {\n // New added keys should add before current key\n if (currentIndex < i) {\n list = list.concat(currentKeyObjects.slice(currentIndex, i).map(function (obj) {\n return _objectSpread(_objectSpread({}, obj), {}, {\n status: STATUS_ADD\n });\n }));\n currentIndex = i;\n }\n\n list.push(_objectSpread(_objectSpread({}, currentKeyObj), {}, {\n status: STATUS_KEEP\n }));\n currentIndex += 1;\n hit = true;\n break;\n }\n } // If not hit, it means key is removed\n\n\n if (!hit) {\n list.push(_objectSpread(_objectSpread({}, keyObj), {}, {\n status: STATUS_REMOVE\n }));\n }\n }); // Add rest to the list\n\n if (currentIndex < currentLen) {\n list = list.concat(currentKeyObjects.slice(currentIndex).map(function (obj) {\n return _objectSpread(_objectSpread({}, obj), {}, {\n status: STATUS_ADD\n });\n }));\n }\n /**\n * Merge same key when it remove and add again:\n * [1 - add, 2 - keep, 1 - remove] -> [1 - keep, 2 - keep]\n */\n\n\n var keys = {};\n list.forEach(function (_ref) {\n var key = _ref.key;\n keys[key] = (keys[key] || 0) + 1;\n });\n var duplicatedKeys = Object.keys(keys).filter(function (key) {\n return keys[key] > 1;\n });\n duplicatedKeys.forEach(function (matchKey) {\n // Remove `STATUS_REMOVE` node.\n list = list.filter(function (_ref2) {\n var key = _ref2.key,\n status = _ref2.status;\n return key !== matchKey || status !== STATUS_REMOVE;\n }); // Update `STATUS_ADD` to `STATUS_KEEP`\n\n list.forEach(function (node) {\n if (node.key === matchKey) {\n // eslint-disable-next-line no-param-reassign\n node.status = STATUS_KEEP;\n }\n });\n });\n return list;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _inherits from \"@babel/runtime/helpers/esm/inherits\";\nimport _createSuper from \"@babel/runtime/helpers/esm/createSuper\";\n\n/* eslint react/prop-types: 0 */\nimport * as React from 'react';\nimport OriginCSSMotion from './CSSMotion';\nimport { supportTransition } from './util/motion';\nimport { STATUS_ADD, STATUS_KEEP, STATUS_REMOVE, STATUS_REMOVED, diffKeys, parseKeys } from './util/diff';\nvar MOTION_PROP_NAMES = ['eventProps', 'visible', 'children', 'motionName', 'motionAppear', 'motionEnter', 'motionLeave', 'motionLeaveImmediately', 'motionDeadline', 'removeOnLeave', 'leavedClassName', 'onAppearStart', 'onAppearActive', 'onAppearEnd', 'onEnterStart', 'onEnterActive', 'onEnterEnd', 'onLeaveStart', 'onLeaveActive', 'onLeaveEnd'];\n/**\n * Generate a CSSMotionList component with config\n * @param transitionSupport No need since CSSMotionList no longer depends on transition support\n * @param CSSMotion CSSMotion component\n */\n\nexport function genCSSMotionList(transitionSupport) {\n var CSSMotion = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : OriginCSSMotion;\n\n var CSSMotionList = /*#__PURE__*/function (_React$Component) {\n _inherits(CSSMotionList, _React$Component);\n\n var _super = _createSuper(CSSMotionList);\n\n function CSSMotionList() {\n var _this;\n\n _classCallCheck(this, CSSMotionList);\n\n _this = _super.apply(this, arguments);\n _this.state = {\n keyEntities: []\n };\n\n _this.removeKey = function (removeKey) {\n _this.setState(function (_ref) {\n var keyEntities = _ref.keyEntities;\n return {\n keyEntities: keyEntities.map(function (entity) {\n if (entity.key !== removeKey) return entity;\n return _objectSpread(_objectSpread({}, entity), {}, {\n status: STATUS_REMOVED\n });\n })\n };\n });\n };\n\n return _this;\n }\n\n _createClass(CSSMotionList, [{\n key: \"render\",\n value: function render() {\n var _this2 = this;\n\n var keyEntities = this.state.keyEntities;\n\n var _this$props = this.props,\n component = _this$props.component,\n children = _this$props.children,\n _onVisibleChanged = _this$props.onVisibleChanged,\n restProps = _objectWithoutProperties(_this$props, [\"component\", \"children\", \"onVisibleChanged\"]);\n\n var Component = component || React.Fragment;\n var motionProps = {};\n MOTION_PROP_NAMES.forEach(function (prop) {\n motionProps[prop] = restProps[prop];\n delete restProps[prop];\n });\n delete restProps.keys;\n return /*#__PURE__*/React.createElement(Component, restProps, keyEntities.map(function (_ref2) {\n var status = _ref2.status,\n eventProps = _objectWithoutProperties(_ref2, [\"status\"]);\n\n var visible = status === STATUS_ADD || status === STATUS_KEEP;\n return /*#__PURE__*/React.createElement(CSSMotion, _extends({}, motionProps, {\n key: eventProps.key,\n visible: visible,\n eventProps: eventProps,\n onVisibleChanged: function onVisibleChanged(changedVisible) {\n _onVisibleChanged === null || _onVisibleChanged === void 0 ? void 0 : _onVisibleChanged(changedVisible, {\n key: eventProps.key\n });\n\n if (!changedVisible) {\n _this2.removeKey(eventProps.key);\n }\n }\n }), children);\n }));\n }\n }], [{\n key: \"getDerivedStateFromProps\",\n value: function getDerivedStateFromProps(_ref3, _ref4) {\n var keys = _ref3.keys;\n var keyEntities = _ref4.keyEntities;\n var parsedKeyObjects = parseKeys(keys);\n var mixedKeyEntities = diffKeys(keyEntities, parsedKeyObjects);\n return {\n keyEntities: mixedKeyEntities.filter(function (entity) {\n var prevEntity = keyEntities.find(function (_ref5) {\n var key = _ref5.key;\n return entity.key === key;\n }); // Remove if already mark as removed\n\n if (prevEntity && prevEntity.status === STATUS_REMOVED && entity.status === STATUS_REMOVE) {\n return false;\n }\n\n return true;\n })\n };\n }\n }]);\n\n return CSSMotionList;\n }(React.Component);\n\n CSSMotionList.defaultProps = {\n component: 'div'\n };\n return CSSMotionList;\n}\nexport default genCSSMotionList(supportTransition);","import CSSMotion from './CSSMotion';\nimport CSSMotionList from './CSSMotionList';\nexport { CSSMotionList };\nexport default CSSMotion;","import _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport { isMemo } from 'react-is';\nexport function fillRef(ref, node) {\n if (typeof ref === 'function') {\n ref(node);\n } else if (_typeof(ref) === 'object' && ref && 'current' in ref) {\n ref.current = node;\n }\n}\n/**\n * Merge refs into one ref function to support ref passing.\n */\n\nexport function composeRef() {\n for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {\n refs[_key] = arguments[_key];\n }\n\n return function (node) {\n refs.forEach(function (ref) {\n fillRef(ref, node);\n });\n };\n}\nexport function supportRef(nodeOrComponent) {\n var _type$prototype, _nodeOrComponent$prot;\n\n var type = isMemo(nodeOrComponent) ? nodeOrComponent.type.type : nodeOrComponent.type; // Function component node\n\n if (typeof type === 'function' && !((_type$prototype = type.prototype) === null || _type$prototype === void 0 ? void 0 : _type$prototype.render)) {\n return false;\n } // Class component\n\n\n if (typeof nodeOrComponent === 'function' && !((_nodeOrComponent$prot = nodeOrComponent.prototype) === null || _nodeOrComponent$prot === void 0 ? void 0 : _nodeOrComponent$prot.render)) {\n return false;\n }\n\n return true;\n}\n/* eslint-enable */","function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nmodule.exports = _assertThisInitialized;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.hexToRgb = hexToRgb;\nexports.rgbToHex = rgbToHex;\nexports.hslToRgb = hslToRgb;\nexports.decomposeColor = decomposeColor;\nexports.recomposeColor = recomposeColor;\nexports.getContrastRatio = getContrastRatio;\nexports.getLuminance = getLuminance;\nexports.emphasize = emphasize;\nexports.fade = fade;\nexports.alpha = alpha;\nexports.darken = darken;\nexports.lighten = lighten;\n\nvar _utils = require(\"@material-ui/utils\");\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Returns a number whose value is limited to the given range.\n *\n * @param {number} value The value to be clamped\n * @param {number} min The lower boundary of the output range\n * @param {number} max The upper boundary of the output range\n * @returns {number} A number in the range [min, max]\n */\nfunction clamp(value) {\n var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (value < min || value > max) {\n console.error(\"Material-UI: The value provided \".concat(value, \" is out of range [\").concat(min, \", \").concat(max, \"].\"));\n }\n }\n\n return Math.min(Math.max(min, value), max);\n}\n/**\n * Converts a color from CSS hex format to CSS rgb format.\n *\n * @param {string} color - Hex color, i.e. #nnn or #nnnnnn\n * @returns {string} A CSS rgb color string\n */\n\n\nfunction hexToRgb(color) {\n color = color.substr(1);\n var re = new RegExp(\".{1,\".concat(color.length >= 6 ? 2 : 1, \"}\"), 'g');\n var colors = color.match(re);\n\n if (colors && colors[0].length === 1) {\n colors = colors.map(function (n) {\n return n + n;\n });\n }\n\n return colors ? \"rgb\".concat(colors.length === 4 ? 'a' : '', \"(\").concat(colors.map(function (n, index) {\n return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000;\n }).join(', '), \")\") : '';\n}\n\nfunction intToHex(int) {\n var hex = int.toString(16);\n return hex.length === 1 ? \"0\".concat(hex) : hex;\n}\n/**\n * Converts a color from CSS rgb format to CSS hex format.\n *\n * @param {string} color - RGB color, i.e. rgb(n, n, n)\n * @returns {string} A CSS rgb color string, i.e. #nnnnnn\n */\n\n\nfunction rgbToHex(color) {\n // Idempotent\n if (color.indexOf('#') === 0) {\n return color;\n }\n\n var _decomposeColor = decomposeColor(color),\n values = _decomposeColor.values;\n\n return \"#\".concat(values.map(function (n) {\n return intToHex(n);\n }).join(''));\n}\n/**\n * Converts a color from hsl format to rgb format.\n *\n * @param {string} color - HSL color values\n * @returns {string} rgb color values\n */\n\n\nfunction hslToRgb(color) {\n color = decomposeColor(color);\n var _color = color,\n values = _color.values;\n var h = values[0];\n var s = values[1] / 100;\n var l = values[2] / 100;\n var a = s * Math.min(l, 1 - l);\n\n var f = function f(n) {\n var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;\n return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n };\n\n var type = 'rgb';\n var rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];\n\n if (color.type === 'hsla') {\n type += 'a';\n rgb.push(values[3]);\n }\n\n return recomposeColor({\n type: type,\n values: rgb\n });\n}\n/**\n * Returns an object with the type and values of a color.\n *\n * Note: Does not support rgb % values.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {object} - A MUI color object: {type: string, values: number[]}\n */\n\n\nfunction decomposeColor(color) {\n // Idempotent\n if (color.type) {\n return color;\n }\n\n if (color.charAt(0) === '#') {\n return decomposeColor(hexToRgb(color));\n }\n\n var marker = color.indexOf('(');\n var type = color.substring(0, marker);\n\n if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: Unsupported `\".concat(color, \"` color.\\nWe support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().\") : (0, _utils.formatMuiErrorMessage)(3, color));\n }\n\n var values = color.substring(marker + 1, color.length - 1).split(',');\n values = values.map(function (value) {\n return parseFloat(value);\n });\n return {\n type: type,\n values: values\n };\n}\n/**\n * Converts a color object with type and values to a string.\n *\n * @param {object} color - Decomposed color\n * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'\n * @param {array} color.values - [n,n,n] or [n,n,n,n]\n * @returns {string} A CSS color string\n */\n\n\nfunction recomposeColor(color) {\n var type = color.type;\n var values = color.values;\n\n if (type.indexOf('rgb') !== -1) {\n // Only convert the first 3 values to int (i.e. not alpha)\n values = values.map(function (n, i) {\n return i < 3 ? parseInt(n, 10) : n;\n });\n } else if (type.indexOf('hsl') !== -1) {\n values[1] = \"\".concat(values[1], \"%\");\n values[2] = \"\".concat(values[2], \"%\");\n }\n\n return \"\".concat(type, \"(\").concat(values.join(', '), \")\");\n}\n/**\n * Calculates the contrast ratio between two colors.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} A contrast ratio value in the range 0 - 21.\n */\n\n\nfunction getContrastRatio(foreground, background) {\n var lumA = getLuminance(foreground);\n var lumB = getLuminance(background);\n return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n}\n/**\n * The relative brightness of any point in a color space,\n * normalized to 0 for darkest black and 1 for lightest white.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} The relative brightness of the color in the range 0 - 1\n */\n\n\nfunction getLuminance(color) {\n color = decomposeColor(color);\n var rgb = color.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : color.values;\n rgb = rgb.map(function (val) {\n val /= 255; // normalized\n\n return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);\n }); // Truncate at 3 digits\n\n return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));\n}\n/**\n * Darken or lighten a color, depending on its luminance.\n * Light colors are darkened, dark colors are lightened.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient=0.15 - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\n\nfunction emphasize(color) {\n var coefficient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.15;\n return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);\n}\n\nvar warnedOnce = false;\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha values are overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0 -1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n *\n * @deprecated\n * Use `import { alpha } from '@material-ui/core/styles'` instead.\n */\n\nfunction fade(color, value) {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n warnedOnce = true;\n console.error(['Material-UI: The `fade` color utility was renamed to `alpha` to better describe its functionality.', '', \"You should use `import { alpha } from '@material-ui/core/styles'`\"].join('\\n'));\n }\n }\n\n return alpha(color, value);\n}\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha value is overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0-1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\n\nfunction alpha(color, value) {\n color = decomposeColor(color);\n value = clamp(value);\n\n if (color.type === 'rgb' || color.type === 'hsl') {\n color.type += 'a';\n }\n\n color.values[3] = value;\n return recomposeColor(color);\n}\n/**\n * Darkens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\n\nfunction darken(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] *= 1 - coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] *= 1 - coefficient;\n }\n }\n\n return recomposeColor(color);\n}\n/**\n * Lightens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\n\nfunction lighten(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] += (100 - color.values[2]) * coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] += (255 - color.values[i]) * coefficient;\n }\n }\n\n return recomposeColor(color);\n}","import _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nexport default function omit(obj, fields) {\n var clone = _objectSpread({}, obj);\n\n if (Array.isArray(fields)) {\n fields.forEach(function (key) {\n delete clone[key];\n });\n }\n\n return clone;\n}","import devWarning, { resetWarned } from \"rc-util/es/warning\";\nexport { resetWarned };\nexport default (function (valid, component, message) {\n devWarning(valid, \"[antd: \".concat(component, \"] \").concat(message));\n});","import * as React from 'react';\nvar useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n/**\n * https://github.com/facebook/react/issues/14099#issuecomment-440013892\n *\n * @param {function} fn\n */\n\nexport default function useEventCallback(fn) {\n var ref = React.useRef(fn);\n useEnhancedEffect(function () {\n ref.current = fn;\n });\n return React.useCallback(function () {\n return (0, ref.current).apply(void 0, arguments);\n }, []);\n}","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nvar _typeof = require(\"@babel/runtime/helpers/typeof\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"ConfigConsumer\", {\n enumerable: true,\n get: function get() {\n return _context.ConfigConsumer;\n }\n});\nObject.defineProperty(exports, \"ConfigContext\", {\n enumerable: true,\n get: function get() {\n return _context.ConfigContext;\n }\n});\nexports[\"default\"] = exports.globalConfig = exports.defaultPrefixCls = exports.configConsumerProps = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar React = _interopRequireWildcard(require(\"react\"));\n\nvar _Context = _interopRequireDefault(require(\"@ant-design/icons/lib/components/Context\"));\n\nvar _rcFieldForm = require(\"rc-field-form\");\n\nvar _useMemo = _interopRequireDefault(require(\"rc-util/lib/hooks/useMemo\"));\n\nvar _localeProvider = _interopRequireWildcard(require(\"../locale-provider\"));\n\nvar _LocaleReceiver = _interopRequireDefault(require(\"../locale-provider/LocaleReceiver\"));\n\nvar _context = require(\"./context\");\n\nvar _SizeContext = _interopRequireWildcard(require(\"./SizeContext\"));\n\nvar _message = _interopRequireDefault(require(\"../message\"));\n\nvar _notification = _interopRequireDefault(require(\"../notification\"));\n\nvar _default2 = _interopRequireDefault(require(\"../locale/default\"));\n\nfunction _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== \"function\") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }\n\nfunction _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") { return { \"default\": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj[\"default\"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\n\nvar configConsumerProps = ['getTargetContainer', 'getPopupContainer', 'rootPrefixCls', 'getPrefixCls', 'renderEmpty', 'csp', 'autoInsertSpaceInButton', 'locale', 'pageHeader']; // These props is used by `useContext` directly in sub component\n\nexports.configConsumerProps = configConsumerProps;\nvar PASSED_PROPS = ['getTargetContainer', 'getPopupContainer', 'renderEmpty', 'pageHeader', 'input', 'form'];\nvar defaultPrefixCls = 'ant';\nexports.defaultPrefixCls = defaultPrefixCls;\nvar globalPrefixCls;\n\nvar setGlobalConfig = function setGlobalConfig(params) {\n if (params.prefixCls !== undefined) {\n globalPrefixCls = params.prefixCls;\n }\n};\n\nfunction getGlobalPrefixCls() {\n return globalPrefixCls || defaultPrefixCls;\n}\n\nvar globalConfig = function globalConfig() {\n return {\n getPrefixCls: function getPrefixCls(suffixCls, customizePrefixCls) {\n if (customizePrefixCls) return customizePrefixCls;\n return suffixCls ? \"\".concat(getGlobalPrefixCls(), \"-\").concat(suffixCls) : getGlobalPrefixCls();\n },\n getRootPrefixCls: function getRootPrefixCls(rootPrefixCls, customizePrefixCls) {\n // Customize rootPrefixCls is first priority\n if (rootPrefixCls) {\n return rootPrefixCls;\n } // If Global prefixCls provided, use this\n\n\n if (globalPrefixCls) {\n return globalPrefixCls;\n } // [Legacy] If customize prefixCls provided, we cut it to get the prefixCls\n\n\n if (customizePrefixCls && customizePrefixCls.includes('-')) {\n return customizePrefixCls.replace(/^(.*)-[^-]*$/, '$1');\n } // Fallback to default prefixCls\n\n\n return getGlobalPrefixCls();\n }\n };\n};\n\nexports.globalConfig = globalConfig;\n\nvar ProviderChildren = function ProviderChildren(props) {\n var _a, _b;\n\n var children = props.children,\n csp = props.csp,\n autoInsertSpaceInButton = props.autoInsertSpaceInButton,\n form = props.form,\n locale = props.locale,\n componentSize = props.componentSize,\n direction = props.direction,\n space = props.space,\n virtual = props.virtual,\n dropdownMatchSelectWidth = props.dropdownMatchSelectWidth,\n legacyLocale = props.legacyLocale,\n parentContext = props.parentContext,\n iconPrefixCls = props.iconPrefixCls;\n var getPrefixCls = React.useCallback(function (suffixCls, customizePrefixCls) {\n var prefixCls = props.prefixCls;\n if (customizePrefixCls) return customizePrefixCls;\n var mergedPrefixCls = prefixCls || parentContext.getPrefixCls('');\n return suffixCls ? \"\".concat(mergedPrefixCls, \"-\").concat(suffixCls) : mergedPrefixCls;\n }, [parentContext.getPrefixCls, props.prefixCls]);\n var config = (0, _extends2[\"default\"])((0, _extends2[\"default\"])({}, parentContext), {\n csp: csp,\n autoInsertSpaceInButton: autoInsertSpaceInButton,\n locale: locale || legacyLocale,\n direction: direction,\n space: space,\n virtual: virtual,\n dropdownMatchSelectWidth: dropdownMatchSelectWidth,\n getPrefixCls: getPrefixCls\n }); // Pass the props used by `useContext` directly with child component.\n // These props should merged into `config`.\n\n PASSED_PROPS.forEach(function (propName) {\n var propValue = props[propName];\n\n if (propValue) {\n config[propName] = propValue;\n }\n }); // https://github.com/ant-design/ant-design/issues/27617\n\n var memoedConfig = (0, _useMemo[\"default\"])(function () {\n return config;\n }, config, function (prevConfig, currentConfig) {\n var prevKeys = Object.keys(prevConfig);\n var currentKeys = Object.keys(currentConfig);\n return prevKeys.length !== currentKeys.length || prevKeys.some(function (key) {\n return prevConfig[key] !== currentConfig[key];\n });\n });\n var memoIconContextValue = React.useMemo(function () {\n return {\n prefixCls: iconPrefixCls,\n csp: csp\n };\n }, [iconPrefixCls]);\n var childNode = children; // Additional Form provider\n\n var validateMessages = {};\n\n if (locale) {\n validateMessages = ((_a = locale.Form) === null || _a === void 0 ? void 0 : _a.defaultValidateMessages) || ((_b = _default2[\"default\"].Form) === null || _b === void 0 ? void 0 : _b.defaultValidateMessages) || {};\n }\n\n if (form && form.validateMessages) {\n validateMessages = (0, _extends2[\"default\"])((0, _extends2[\"default\"])({}, validateMessages), form.validateMessages);\n }\n\n if (Object.keys(validateMessages).length > 0) {\n childNode = /*#__PURE__*/React.createElement(_rcFieldForm.FormProvider, {\n validateMessages: validateMessages\n }, children);\n }\n\n if (locale) {\n childNode = /*#__PURE__*/React.createElement(_localeProvider[\"default\"], {\n locale: locale,\n _ANT_MARK__: _localeProvider.ANT_MARK\n }, childNode);\n }\n\n if (iconPrefixCls) {\n childNode = /*#__PURE__*/React.createElement(_Context[\"default\"].Provider, {\n value: memoIconContextValue\n }, childNode);\n }\n\n if (componentSize) {\n childNode = /*#__PURE__*/React.createElement(_SizeContext.SizeContextProvider, {\n size: componentSize\n }, childNode);\n }\n\n return /*#__PURE__*/React.createElement(_context.ConfigContext.Provider, {\n value: memoedConfig\n }, childNode);\n};\n\nvar ConfigProvider = function ConfigProvider(props) {\n React.useEffect(function () {\n if (props.direction) {\n _message[\"default\"].config({\n rtl: props.direction === 'rtl'\n });\n\n _notification[\"default\"].config({\n rtl: props.direction === 'rtl'\n });\n }\n }, [props.direction]);\n return /*#__PURE__*/React.createElement(_LocaleReceiver[\"default\"], null, function (_, __, legacyLocale) {\n return /*#__PURE__*/React.createElement(_context.ConfigConsumer, null, function (context) {\n return /*#__PURE__*/React.createElement(ProviderChildren, (0, _extends2[\"default\"])({\n parentContext: context,\n legacyLocale: legacyLocale\n }, props));\n });\n });\n};\n/** @private internal Usage. do not use in your production */\n\n\nConfigProvider.ConfigContext = _context.ConfigContext;\nConfigProvider.SizeContext = _SizeContext[\"default\"];\nConfigProvider.config = setGlobalConfig;\nvar _default = ConfigProvider;\nexports[\"default\"] = _default;","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","import React from 'react';\nimport { isFragment } from 'react-is';\nexport default function toArray(children) {\n var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var ret = [];\n React.Children.forEach(children, function (child) {\n if ((child === undefined || child === null) && !option.keepEmpty) {\n return;\n }\n\n if (Array.isArray(child)) {\n ret = ret.concat(toArray(child));\n } else if (isFragment(child) && child.props) {\n ret = ret.concat(toArray(child.props.children, option));\n } else {\n ret.push(child);\n }\n });\n return ret;\n}","import { useTheme as useThemeWithoutDefault } from '@material-ui/styles';\nimport React from 'react';\nimport defaultTheme from './defaultTheme';\nexport default function useTheme() {\n var theme = useThemeWithoutDefault() || defaultTheme;\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(theme);\n }\n\n return theme;\n}","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport * as React from 'react';\nexport default function useControlledState(defaultStateValue, option) {\n var _ref = option || {},\n defaultValue = _ref.defaultValue,\n value = _ref.value,\n onChange = _ref.onChange,\n postState = _ref.postState;\n\n var _React$useState = React.useState(function () {\n if (value !== undefined) {\n return value;\n }\n\n if (defaultValue !== undefined) {\n return typeof defaultValue === 'function' ? defaultValue() : defaultValue;\n }\n\n return typeof defaultStateValue === 'function' ? defaultStateValue() : defaultStateValue;\n }),\n _React$useState2 = _slicedToArray(_React$useState, 2),\n innerValue = _React$useState2[0],\n setInnerValue = _React$useState2[1];\n\n var mergedValue = value !== undefined ? value : innerValue;\n\n if (postState) {\n mergedValue = postState(mergedValue);\n }\n\n function triggerChange(newValue) {\n setInnerValue(newValue);\n\n if (mergedValue !== newValue && onChange) {\n onChange(newValue, mergedValue);\n }\n } // Effect of reset value to `undefined`\n\n\n var firstRenderRef = React.useRef(true);\n React.useEffect(function () {\n if (firstRenderRef.current) {\n firstRenderRef.current = false;\n return;\n }\n\n if (value === undefined) {\n setInnerValue(value);\n }\n }, [value]);\n return [mergedValue, triggerChange];\n}","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\n// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves\n// to learn the context in which each easing should be used.\nexport var easing = {\n // This is the most common easing curve.\n easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',\n // Objects enter the screen at full velocity from off-screen and\n // slowly decelerate to a resting point.\n easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)',\n // Objects leave the screen at full velocity. They do not decelerate when off-screen.\n easeIn: 'cubic-bezier(0.4, 0, 1, 1)',\n // The sharp curve is used by objects that may return to the screen at any time.\n sharp: 'cubic-bezier(0.4, 0, 0.6, 1)'\n}; // Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations\n// to learn when use what timing\n\nexport var duration = {\n shortest: 150,\n shorter: 200,\n short: 250,\n // most basic recommended timing\n standard: 300,\n // this is to be used in complex animations\n complex: 375,\n // recommended when something is entering screen\n enteringScreen: 225,\n // recommended when something is leaving screen\n leavingScreen: 195\n};\n\nfunction formatMs(milliseconds) {\n return \"\".concat(Math.round(milliseconds), \"ms\");\n}\n/**\n * @param {string|Array} props\n * @param {object} param\n * @param {string} param.prop\n * @param {number} param.duration\n * @param {string} param.easing\n * @param {number} param.delay\n */\n\n\nexport default {\n easing: easing,\n duration: duration,\n create: function create() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['all'];\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n var _options$duration = options.duration,\n durationOption = _options$duration === void 0 ? duration.standard : _options$duration,\n _options$easing = options.easing,\n easingOption = _options$easing === void 0 ? easing.easeInOut : _options$easing,\n _options$delay = options.delay,\n delay = _options$delay === void 0 ? 0 : _options$delay,\n other = _objectWithoutProperties(options, [\"duration\", \"easing\", \"delay\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n var isString = function isString(value) {\n return typeof value === 'string';\n };\n\n var isNumber = function isNumber(value) {\n return !isNaN(parseFloat(value));\n };\n\n if (!isString(props) && !Array.isArray(props)) {\n console.error('Material-UI: Argument \"props\" must be a string or Array.');\n }\n\n if (!isNumber(durationOption) && !isString(durationOption)) {\n console.error(\"Material-UI: Argument \\\"duration\\\" must be a number or a string but found \".concat(durationOption, \".\"));\n }\n\n if (!isString(easingOption)) {\n console.error('Material-UI: Argument \"easing\" must be a string.');\n }\n\n if (!isNumber(delay) && !isString(delay)) {\n console.error('Material-UI: Argument \"delay\" must be a number or a string.');\n }\n\n if (Object.keys(other).length !== 0) {\n console.error(\"Material-UI: Unrecognized argument(s) [\".concat(Object.keys(other).join(','), \"].\"));\n }\n }\n\n return (Array.isArray(props) ? props : [props]).map(function (animatedProp) {\n return \"\".concat(animatedProp, \" \").concat(typeof durationOption === 'string' ? durationOption : formatMs(durationOption), \" \").concat(easingOption, \" \").concat(typeof delay === 'string' ? delay : formatMs(delay));\n }).join(',');\n },\n getAutoHeightDuration: function getAutoHeightDuration(height) {\n if (!height) {\n return 0;\n }\n\n var constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10\n\n return Math.round((4 + 15 * Math.pow(constant, 0.25) + constant / 5) * 10);\n }\n};","'use strict';\n\nvar bind = require('./helpers/bind');\n\n/*global toString:true*/\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (toString.call(val) !== '[object Object]') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.replace(/^\\s*/, '').replace(/\\s*$/, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM\n};\n","var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","// Corresponds to 10 frames at 60 Hz.\n// A few bytes payload overhead when lodash/debounce is ~3 kB and debounce ~300 B.\nexport default function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","export default function canUseDom() {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}","\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = Loader;\n\nvar _react = _interopRequireWildcard(require(\"react\"));\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _loader = require(\"./loader\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\nfunction _getRequireWildcardCache() { if (typeof WeakMap !== \"function\") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") { return { \"default\": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj[\"default\"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\n\nfunction 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; }\n\nfunction _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; }\n\nfunction _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; }\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _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); }\n\nfunction _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; }\n\nfunction _iterableToArrayLimit(arr, i) { if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return; 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; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar componentNames = [\"Audio\", \"BallTriangle\", \"Bars\", \"Circles\", \"Grid\", \"Hearts\", \"Oval\", \"Puff\", \"Rings\", \"TailSpin\", \"ThreeDots\", \"Watch\", \"RevolvingDot\", \"Triangle\", \"Plane\", \"MutatingDots\", \"CradleLoader\"];\n\nfunction componentName(type) {\n if (componentNames.includes(type)) {\n return _loader.Spinner[type];\n }\n\n return _loader.Spinner.Audio;\n}\n/**\n * @return {null}\n */\n\n\nfunction Loader(props) {\n var _useState = (0, _react.useState)(true),\n _useState2 = _slicedToArray(_useState, 2),\n display = _useState2[0],\n setDisplay = _useState2[1];\n\n (0, _react.useEffect)(function () {\n var timer;\n\n if (props.timeout && props.timeout > 0) {\n timer = setTimeout(function () {\n setDisplay(false);\n }, props.timeout);\n }\n\n return function () {\n if (timer) clearTimeout(timer);\n };\n });\n\n if (!props.visible || props.visible === \"false\") {\n return null;\n }\n\n return display ? /*#__PURE__*/_react[\"default\"].createElement(\"div\", {\n \"aria-busy\": \"true\",\n className: props.className,\n style: props.style\n }, /*#__PURE__*/_react[\"default\"].createElement(componentName(props.type), _objectSpread({}, props))) : null;\n}\n\nLoader.propTypes = {\n type: _propTypes[\"default\"].oneOf([].concat(componentNames)),\n style: _propTypes[\"default\"].objectOf(_propTypes[\"default\"].string),\n className: _propTypes[\"default\"].string,\n visible: _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].bool, _propTypes[\"default\"].string]),\n timeout: _propTypes[\"default\"].number\n};\nLoader.defaultProps = {\n type: \"Audio\",\n style: {},\n className: \"\",\n visible: true,\n timeout: 0\n};","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport * as React from 'react';\nimport useMemo from \"rc-util/es/hooks/useMemo\";\nimport shallowEqual from 'shallowequal';\nexport var MenuContext = /*#__PURE__*/React.createContext(null);\n\nfunction mergeProps(origin, target) {\n var clone = _objectSpread({}, origin);\n\n Object.keys(target).forEach(function (key) {\n var value = target[key];\n\n if (value !== undefined) {\n clone[key] = value;\n }\n });\n return clone;\n}\n\nexport default function InheritableContextProvider(_ref) {\n var children = _ref.children,\n locked = _ref.locked,\n restProps = _objectWithoutProperties(_ref, [\"children\", \"locked\"]);\n\n var context = React.useContext(MenuContext);\n var inheritableContext = useMemo(function () {\n return mergeProps(context, restProps);\n }, [context, restProps], function (prev, next) {\n return !locked && (prev[0] !== next[0] || !shallowEqual(prev[1], next[1]));\n });\n return /*#__PURE__*/React.createElement(MenuContext.Provider, {\n value: inheritableContext\n }, children);\n}","import * as React from 'react';\nimport { MenuContext } from '../context/MenuContext';\nexport default function useActive(eventKey, disabled, onMouseEnter, onMouseLeave) {\n var _React$useContext = React.useContext(MenuContext),\n activeKey = _React$useContext.activeKey,\n onActive = _React$useContext.onActive,\n onInactive = _React$useContext.onInactive;\n\n var ret = {\n active: activeKey === eventKey\n }; // Skip when disabled\n\n if (!disabled) {\n ret.onMouseEnter = function (domEvent) {\n onMouseEnter === null || onMouseEnter === void 0 ? void 0 : onMouseEnter({\n key: eventKey,\n domEvent: domEvent\n });\n onActive(eventKey);\n };\n\n ret.onMouseLeave = function (domEvent) {\n onMouseLeave === null || onMouseLeave === void 0 ? void 0 : onMouseLeave({\n key: eventKey,\n domEvent: domEvent\n });\n onInactive(eventKey);\n };\n }\n\n return ret;\n}","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport warning from \"rc-util/es/warning\";\n/**\n * `onClick` event return `info.item` which point to react node directly.\n * We should warning this since it will not work on FC.\n */\n\nexport function warnItemProp(_ref) {\n var item = _ref.item,\n restInfo = _objectWithoutProperties(_ref, [\"item\"]);\n\n Object.defineProperty(restInfo, 'item', {\n get: function get() {\n warning(false, '`info.item` is deprecated since we will move to function component that not provides React Node instance in future.');\n return item;\n }\n });\n return restInfo;\n}","import _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport * as React from 'react';\nexport default function Icon(_ref) {\n var icon = _ref.icon,\n props = _ref.props,\n children = _ref.children;\n var iconNode;\n\n if (typeof icon === 'function') {\n iconNode = /*#__PURE__*/React.createElement(icon, _objectSpread({}, props));\n } else {\n // Compatible for origin definition\n iconNode = icon;\n }\n\n return iconNode || children || null;\n}","import * as React from 'react';\nimport { MenuContext } from '../context/MenuContext';\nexport default function useDirectionStyle(level) {\n var _React$useContext = React.useContext(MenuContext),\n mode = _React$useContext.mode,\n rtl = _React$useContext.rtl,\n inlineIndent = _React$useContext.inlineIndent;\n\n if (mode !== 'inline') {\n return null;\n }\n\n var len = level;\n return rtl ? {\n paddingRight: len * inlineIndent\n } : {\n paddingLeft: len * inlineIndent\n };\n}","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport * as React from 'react';\nvar EmptyList = [];\nexport var PathRegisterContext = /*#__PURE__*/React.createContext(null);\nexport function useMeasure() {\n return React.useContext(PathRegisterContext);\n} // ========================= Path Tracker ==========================\n\nexport var PathTrackerContext = /*#__PURE__*/React.createContext(EmptyList);\nexport function useFullPath(eventKey) {\n var parentKeyPath = React.useContext(PathTrackerContext);\n return React.useMemo(function () {\n return eventKey !== undefined ? [].concat(_toConsumableArray(parentKeyPath), [eventKey]) : parentKeyPath;\n }, [parentKeyPath, eventKey]);\n}\nexport var PathUserContext = /*#__PURE__*/React.createContext(null);","import * as React from 'react';\nexport var IdContext = /*#__PURE__*/React.createContext(null);\nexport function getMenuId(uuid, eventKey) {\n if (uuid === undefined) {\n return null;\n }\n\n return \"\".concat(uuid, \"-\").concat(eventKey);\n}\n/**\n * Get `data-menu-id`\n */\n\nexport function useMenuId(eventKey) {\n var id = React.useContext(IdContext);\n return getMenuId(id, eventKey);\n}","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _inherits from \"@babel/runtime/helpers/esm/inherits\";\nimport _createSuper from \"@babel/runtime/helpers/esm/createSuper\";\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport Overflow from 'rc-overflow';\nimport warning from \"rc-util/es/warning\";\nimport KeyCode from \"rc-util/es/KeyCode\";\nimport omit from \"rc-util/es/omit\";\nimport { MenuContext } from './context/MenuContext';\nimport useActive from './hooks/useActive';\nimport { warnItemProp } from './utils/warnUtil';\nimport Icon from './Icon';\nimport useDirectionStyle from './hooks/useDirectionStyle';\nimport { useFullPath, useMeasure } from './context/PathContext';\nimport { useMenuId } from './context/IdContext'; // Since Menu event provide the `info.item` which point to the MenuItem node instance.\n// We have to use class component here.\n// This should be removed from doc & api in future.\n\nvar LegacyMenuItem = /*#__PURE__*/function (_React$Component) {\n _inherits(LegacyMenuItem, _React$Component);\n\n var _super = _createSuper(LegacyMenuItem);\n\n function LegacyMenuItem() {\n _classCallCheck(this, LegacyMenuItem);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(LegacyMenuItem, [{\n key: \"render\",\n value: function render() {\n var _this$props = this.props,\n title = _this$props.title,\n attribute = _this$props.attribute,\n elementRef = _this$props.elementRef,\n restProps = _objectWithoutProperties(_this$props, [\"title\", \"attribute\", \"elementRef\"]);\n\n var passedProps = omit(restProps, ['eventKey']);\n warning(!attribute, '`attribute` of Menu.Item is deprecated. Please pass attribute directly.');\n return /*#__PURE__*/React.createElement(Overflow.Item, _extends({}, attribute, {\n title: typeof title === 'string' ? title : undefined\n }, passedProps, {\n ref: elementRef\n }));\n }\n }]);\n\n return LegacyMenuItem;\n}(React.Component);\n/**\n * Real Menu Item component\n */\n\n\nvar InternalMenuItem = function InternalMenuItem(props) {\n var _classNames;\n\n var style = props.style,\n className = props.className,\n eventKey = props.eventKey,\n warnKey = props.warnKey,\n disabled = props.disabled,\n itemIcon = props.itemIcon,\n children = props.children,\n role = props.role,\n onMouseEnter = props.onMouseEnter,\n onMouseLeave = props.onMouseLeave,\n onClick = props.onClick,\n onKeyDown = props.onKeyDown,\n onFocus = props.onFocus,\n restProps = _objectWithoutProperties(props, [\"style\", \"className\", \"eventKey\", \"warnKey\", \"disabled\", \"itemIcon\", \"children\", \"role\", \"onMouseEnter\", \"onMouseLeave\", \"onClick\", \"onKeyDown\", \"onFocus\"]);\n\n var domDataId = useMenuId(eventKey);\n\n var _React$useContext = React.useContext(MenuContext),\n prefixCls = _React$useContext.prefixCls,\n onItemClick = _React$useContext.onItemClick,\n contextDisabled = _React$useContext.disabled,\n overflowDisabled = _React$useContext.overflowDisabled,\n contextItemIcon = _React$useContext.itemIcon,\n selectedKeys = _React$useContext.selectedKeys,\n onActive = _React$useContext.onActive;\n\n var itemCls = \"\".concat(prefixCls, \"-item\");\n var legacyMenuItemRef = React.useRef();\n var elementRef = React.useRef();\n var mergedDisabled = contextDisabled || disabled;\n var connectedKeys = useFullPath(eventKey); // ================================ Warn ================================\n\n if (process.env.NODE_ENV !== 'production' && warnKey) {\n warning(false, 'MenuItem should not leave undefined `key`.');\n } // ============================= Info =============================\n\n\n var getEventInfo = function getEventInfo(e) {\n return {\n key: eventKey,\n // Note: For legacy code is reversed which not like other antd component\n keyPath: _toConsumableArray(connectedKeys).reverse(),\n item: legacyMenuItemRef.current,\n domEvent: e\n };\n }; // ============================= Icon =============================\n\n\n var mergedItemIcon = itemIcon || contextItemIcon; // ============================ Active ============================\n\n var _useActive = useActive(eventKey, mergedDisabled, onMouseEnter, onMouseLeave),\n active = _useActive.active,\n activeProps = _objectWithoutProperties(_useActive, [\"active\"]); // ============================ Select ============================\n\n\n var selected = selectedKeys.includes(eventKey); // ======================== DirectionStyle ========================\n\n var directionStyle = useDirectionStyle(connectedKeys.length); // ============================ Events ============================\n\n var onInternalClick = function onInternalClick(e) {\n if (mergedDisabled) {\n return;\n }\n\n var info = getEventInfo(e);\n onClick === null || onClick === void 0 ? void 0 : onClick(warnItemProp(info));\n onItemClick(info);\n };\n\n var onInternalKeyDown = function onInternalKeyDown(e) {\n onKeyDown === null || onKeyDown === void 0 ? void 0 : onKeyDown(e);\n\n if (e.which === KeyCode.ENTER) {\n var info = getEventInfo(e); // Legacy. Key will also trigger click event\n\n onClick === null || onClick === void 0 ? void 0 : onClick(warnItemProp(info));\n onItemClick(info);\n }\n };\n /**\n * Used for accessibility. Helper will focus element without key board.\n * We should manually trigger an active\n */\n\n\n var onInternalFocus = function onInternalFocus(e) {\n onActive(eventKey);\n onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);\n }; // ============================ Render ============================\n\n\n var optionRoleProps = {};\n\n if (props.role === 'option') {\n optionRoleProps['aria-selected'] = selected;\n }\n\n return /*#__PURE__*/React.createElement(LegacyMenuItem, _extends({\n ref: legacyMenuItemRef,\n elementRef: elementRef,\n role: role === null ? 'none' : role || 'menuitem',\n tabIndex: disabled ? null : -1,\n \"data-menu-id\": overflowDisabled && domDataId ? null : domDataId\n }, restProps, activeProps, optionRoleProps, {\n component: \"li\",\n \"aria-disabled\": disabled,\n style: _objectSpread(_objectSpread({}, directionStyle), style),\n className: classNames(itemCls, (_classNames = {}, _defineProperty(_classNames, \"\".concat(itemCls, \"-active\"), active), _defineProperty(_classNames, \"\".concat(itemCls, \"-selected\"), selected), _defineProperty(_classNames, \"\".concat(itemCls, \"-disabled\"), mergedDisabled), _classNames), className),\n onClick: onInternalClick,\n onKeyDown: onInternalKeyDown,\n onFocus: onInternalFocus\n }), children, /*#__PURE__*/React.createElement(Icon, {\n props: _objectSpread(_objectSpread({}, props), {}, {\n isSelected: selected\n }),\n icon: mergedItemIcon\n }));\n};\n\nfunction MenuItem(props) {\n var eventKey = props.eventKey; // ==================== Record KeyPath ====================\n\n var measure = useMeasure();\n var connectedKeyPath = useFullPath(eventKey); // eslint-disable-next-line consistent-return\n\n React.useEffect(function () {\n if (measure) {\n measure.registerPath(eventKey, connectedKeyPath);\n return function () {\n measure.unregisterPath(eventKey, connectedKeyPath);\n };\n }\n }, [connectedKeyPath]);\n\n if (measure) {\n return null;\n } // ======================== Render ========================\n\n\n return /*#__PURE__*/React.createElement(InternalMenuItem, props);\n}\n\nexport default MenuItem;","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport * as React from 'react';\nimport toArray from \"rc-util/es/Children/toArray\";\nexport function parseChildren(children, keyPath) {\n return toArray(children).map(function (child, index) {\n if ( /*#__PURE__*/React.isValidElement(child)) {\n var _child$props$eventKey, _child$props;\n\n var key = child.key;\n var eventKey = (_child$props$eventKey = (_child$props = child.props) === null || _child$props === void 0 ? void 0 : _child$props.eventKey) !== null && _child$props$eventKey !== void 0 ? _child$props$eventKey : key;\n var emptyKey = eventKey === null || eventKey === undefined;\n\n if (emptyKey) {\n eventKey = \"tmp_key-\".concat([].concat(_toConsumableArray(keyPath), [index]).join('-'));\n }\n\n var cloneProps = {\n key: eventKey,\n eventKey: eventKey\n };\n\n if (process.env.NODE_ENV !== 'production' && emptyKey) {\n cloneProps.warnKey = true;\n }\n\n return /*#__PURE__*/React.cloneElement(child, cloneProps);\n }\n\n return child;\n });\n}","import * as React from 'react';\n/**\n * Cache callback function that always return same ref instead.\n * This is used for context optimization.\n */\n\nexport default function useMemoCallback(func) {\n var funRef = React.useRef(func);\n funRef.current = func;\n var callback = React.useCallback(function () {\n var _funRef$current;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return (_funRef$current = funRef.current) === null || _funRef$current === void 0 ? void 0 : _funRef$current.call.apply(_funRef$current, [funRef].concat(args));\n }, []);\n return func ? callback : undefined;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport { MenuContext } from '../context/MenuContext';\n\nvar InternalSubMenuList = function InternalSubMenuList(_ref, ref) {\n var className = _ref.className,\n children = _ref.children,\n restProps = _objectWithoutProperties(_ref, [\"className\", \"children\"]);\n\n var _React$useContext = React.useContext(MenuContext),\n prefixCls = _React$useContext.prefixCls,\n mode = _React$useContext.mode;\n\n return /*#__PURE__*/React.createElement(\"ul\", _extends({\n className: classNames(prefixCls, \"\".concat(prefixCls, \"-sub\"), \"\".concat(prefixCls, \"-\").concat(mode === 'inline' ? 'inline' : 'vertical'), className)\n }, restProps, {\n \"data-menu-list\": true,\n ref: ref\n }), children);\n};\n\nvar SubMenuList = /*#__PURE__*/React.forwardRef(InternalSubMenuList);\nSubMenuList.displayName = 'SubMenuList';\nexport default SubMenuList;","var autoAdjustOverflow = {\n adjustX: 1,\n adjustY: 1\n};\nexport var placements = {\n topLeft: {\n points: ['bl', 'tl'],\n overflow: autoAdjustOverflow,\n offset: [0, -7]\n },\n bottomLeft: {\n points: ['tl', 'bl'],\n overflow: autoAdjustOverflow,\n offset: [0, 7]\n },\n leftTop: {\n points: ['tr', 'tl'],\n overflow: autoAdjustOverflow,\n offset: [-4, 0]\n },\n rightTop: {\n points: ['tl', 'tr'],\n overflow: autoAdjustOverflow,\n offset: [4, 0]\n }\n};\nexport var placementsRtl = {\n topLeft: {\n points: ['bl', 'tl'],\n overflow: autoAdjustOverflow,\n offset: [0, -7]\n },\n bottomLeft: {\n points: ['tl', 'bl'],\n overflow: autoAdjustOverflow,\n offset: [0, 7]\n },\n rightTop: {\n points: ['tr', 'tl'],\n overflow: autoAdjustOverflow,\n offset: [-4, 0]\n },\n leftTop: {\n points: ['tl', 'tr'],\n overflow: autoAdjustOverflow,\n offset: [4, 0]\n }\n};\nexport default placements;","export function getMotion(mode, motion, defaultMotions) {\n if (motion) {\n return motion;\n }\n\n if (defaultMotions) {\n return defaultMotions[mode] || defaultMotions.other;\n }\n\n return undefined;\n}","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport * as React from 'react';\nimport Trigger from 'rc-trigger';\nimport classNames from 'classnames';\nimport raf from \"rc-util/es/raf\";\nimport { MenuContext } from '../context/MenuContext';\nimport { placements, placementsRtl } from '../placements';\nimport { getMotion } from '../utils/motionUtil';\nvar popupPlacementMap = {\n horizontal: 'bottomLeft',\n vertical: 'rightTop',\n 'vertical-left': 'rightTop',\n 'vertical-right': 'leftTop'\n};\nexport default function PopupTrigger(_ref) {\n var prefixCls = _ref.prefixCls,\n visible = _ref.visible,\n children = _ref.children,\n popup = _ref.popup,\n popupClassName = _ref.popupClassName,\n popupOffset = _ref.popupOffset,\n disabled = _ref.disabled,\n mode = _ref.mode,\n onVisibleChange = _ref.onVisibleChange;\n\n var _React$useContext = React.useContext(MenuContext),\n getPopupContainer = _React$useContext.getPopupContainer,\n rtl = _React$useContext.rtl,\n subMenuOpenDelay = _React$useContext.subMenuOpenDelay,\n subMenuCloseDelay = _React$useContext.subMenuCloseDelay,\n builtinPlacements = _React$useContext.builtinPlacements,\n triggerSubMenuAction = _React$useContext.triggerSubMenuAction,\n forceSubMenuRender = _React$useContext.forceSubMenuRender,\n motion = _React$useContext.motion,\n defaultMotions = _React$useContext.defaultMotions;\n\n var _React$useState = React.useState(false),\n _React$useState2 = _slicedToArray(_React$useState, 2),\n innerVisible = _React$useState2[0],\n setInnerVisible = _React$useState2[1];\n\n var placement = rtl ? _objectSpread(_objectSpread({}, placementsRtl), builtinPlacements) : _objectSpread(_objectSpread({}, placements), builtinPlacements);\n var popupPlacement = popupPlacementMap[mode];\n var targetMotion = getMotion(mode, motion, defaultMotions);\n\n var mergedMotion = _objectSpread(_objectSpread({}, targetMotion), {}, {\n leavedClassName: \"\".concat(prefixCls, \"-hidden\"),\n removeOnLeave: false,\n motionAppear: true\n }); // Delay to change visible\n\n\n var visibleRef = React.useRef();\n React.useEffect(function () {\n visibleRef.current = raf(function () {\n setInnerVisible(visible);\n });\n return function () {\n raf.cancel(visibleRef.current);\n };\n }, [visible]);\n return /*#__PURE__*/React.createElement(Trigger, {\n prefixCls: prefixCls,\n popupClassName: classNames(\"\".concat(prefixCls, \"-popup\"), _defineProperty({}, \"\".concat(prefixCls, \"-rtl\"), rtl), popupClassName),\n stretch: mode === 'horizontal' ? 'minWidth' : null,\n getPopupContainer: getPopupContainer,\n builtinPlacements: placement,\n popupPlacement: popupPlacement,\n popupVisible: innerVisible,\n popup: popup,\n popupAlign: popupOffset && {\n offset: popupOffset\n },\n action: disabled ? [] : [triggerSubMenuAction],\n mouseEnterDelay: subMenuOpenDelay,\n mouseLeaveDelay: subMenuCloseDelay,\n onPopupVisibleChange: onVisibleChange,\n forceRender: forceSubMenuRender,\n popupMotion: mergedMotion\n }, children);\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport * as React from 'react';\nimport CSSMotion from 'rc-motion';\nimport { getMotion } from '../utils/motionUtil';\nimport MenuContextProvider, { MenuContext } from '../context/MenuContext';\nimport SubMenuList from './SubMenuList';\nexport default function InlineSubMenuList(_ref) {\n var id = _ref.id,\n open = _ref.open,\n keyPath = _ref.keyPath,\n children = _ref.children;\n var fixedMode = 'inline';\n\n var _React$useContext = React.useContext(MenuContext),\n prefixCls = _React$useContext.prefixCls,\n forceSubMenuRender = _React$useContext.forceSubMenuRender,\n motion = _React$useContext.motion,\n defaultMotions = _React$useContext.defaultMotions,\n mode = _React$useContext.mode; // Always use latest mode check\n\n\n var sameModeRef = React.useRef(false);\n sameModeRef.current = mode === fixedMode; // We record `destroy` mark here since when mode change from `inline` to others.\n // The inline list should remove when motion end.\n\n var _React$useState = React.useState(!sameModeRef.current),\n _React$useState2 = _slicedToArray(_React$useState, 2),\n destroy = _React$useState2[0],\n setDestroy = _React$useState2[1];\n\n var mergedOpen = sameModeRef.current ? open : false; // ================================= Effect =================================\n // Reset destroy state when mode change back\n\n React.useEffect(function () {\n if (sameModeRef.current) {\n setDestroy(false);\n }\n }, [mode]); // ================================= Render =================================\n\n var mergedMotion = _objectSpread({}, getMotion(fixedMode, motion, defaultMotions)); // No need appear since nest inlineCollapse changed\n\n\n if (keyPath.length > 1) {\n mergedMotion.motionAppear = false;\n } // Hide inline list when mode changed and motion end\n\n\n var originOnVisibleChanged = mergedMotion.onVisibleChanged;\n\n mergedMotion.onVisibleChanged = function (newVisible) {\n if (!sameModeRef.current && !newVisible) {\n setDestroy(true);\n }\n\n return originOnVisibleChanged === null || originOnVisibleChanged === void 0 ? void 0 : originOnVisibleChanged(newVisible);\n };\n\n if (destroy) {\n return null;\n }\n\n return /*#__PURE__*/React.createElement(MenuContextProvider, {\n mode: fixedMode,\n locked: !sameModeRef.current\n }, /*#__PURE__*/React.createElement(CSSMotion, _extends({\n visible: mergedOpen\n }, mergedMotion, {\n forceRender: forceSubMenuRender,\n removeOnLeave: false,\n leavedClassName: \"\".concat(prefixCls, \"-hidden\")\n }), function (_ref2) {\n var motionClassName = _ref2.className,\n motionStyle = _ref2.style;\n return /*#__PURE__*/React.createElement(SubMenuList, {\n id: id,\n className: motionClassName,\n style: motionStyle\n }, children);\n }));\n}","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport Overflow from 'rc-overflow';\nimport warning from \"rc-util/es/warning\";\nimport SubMenuList from './SubMenuList';\nimport { parseChildren } from '../utils/nodeUtil';\nimport MenuContextProvider, { MenuContext } from '../context/MenuContext';\nimport useMemoCallback from '../hooks/useMemoCallback';\nimport PopupTrigger from './PopupTrigger';\nimport Icon from '../Icon';\nimport useActive from '../hooks/useActive';\nimport { warnItemProp } from '../utils/warnUtil';\nimport useDirectionStyle from '../hooks/useDirectionStyle';\nimport InlineSubMenuList from './InlineSubMenuList';\nimport { PathTrackerContext, PathUserContext, useFullPath, useMeasure } from '../context/PathContext';\nimport { useMenuId } from '../context/IdContext';\n\nvar InternalSubMenu = function InternalSubMenu(props) {\n var _classNames;\n\n var style = props.style,\n className = props.className,\n title = props.title,\n eventKey = props.eventKey,\n warnKey = props.warnKey,\n disabled = props.disabled,\n internalPopupClose = props.internalPopupClose,\n children = props.children,\n itemIcon = props.itemIcon,\n expandIcon = props.expandIcon,\n popupClassName = props.popupClassName,\n popupOffset = props.popupOffset,\n onClick = props.onClick,\n onMouseEnter = props.onMouseEnter,\n onMouseLeave = props.onMouseLeave,\n onTitleClick = props.onTitleClick,\n onTitleMouseEnter = props.onTitleMouseEnter,\n onTitleMouseLeave = props.onTitleMouseLeave,\n restProps = _objectWithoutProperties(props, [\"style\", \"className\", \"title\", \"eventKey\", \"warnKey\", \"disabled\", \"internalPopupClose\", \"children\", \"itemIcon\", \"expandIcon\", \"popupClassName\", \"popupOffset\", \"onClick\", \"onMouseEnter\", \"onMouseLeave\", \"onTitleClick\", \"onTitleMouseEnter\", \"onTitleMouseLeave\"]);\n\n var domDataId = useMenuId(eventKey);\n\n var _React$useContext = React.useContext(MenuContext),\n prefixCls = _React$useContext.prefixCls,\n mode = _React$useContext.mode,\n openKeys = _React$useContext.openKeys,\n contextDisabled = _React$useContext.disabled,\n overflowDisabled = _React$useContext.overflowDisabled,\n activeKey = _React$useContext.activeKey,\n selectedKeys = _React$useContext.selectedKeys,\n contextItemIcon = _React$useContext.itemIcon,\n contextExpandIcon = _React$useContext.expandIcon,\n onItemClick = _React$useContext.onItemClick,\n onOpenChange = _React$useContext.onOpenChange,\n onActive = _React$useContext.onActive;\n\n var _React$useContext2 = React.useContext(PathUserContext),\n isSubPathKey = _React$useContext2.isSubPathKey;\n\n var connectedPath = useFullPath();\n var subMenuPrefixCls = \"\".concat(prefixCls, \"-submenu\");\n var mergedDisabled = contextDisabled || disabled;\n var elementRef = React.useRef();\n var popupRef = React.useRef(); // ================================ Warn ================================\n\n if (process.env.NODE_ENV !== 'production' && warnKey) {\n warning(false, 'SubMenu should not leave undefined `key`.');\n } // ================================ Icon ================================\n\n\n var mergedItemIcon = itemIcon || contextItemIcon;\n var mergedExpandIcon = expandIcon || contextExpandIcon; // ================================ Open ================================\n\n var originOpen = openKeys.includes(eventKey);\n var open = !overflowDisabled && originOpen; // =============================== Select ===============================\n\n var childrenSelected = isSubPathKey(selectedKeys, eventKey); // =============================== Active ===============================\n\n var _useActive = useActive(eventKey, mergedDisabled, onTitleMouseEnter, onTitleMouseLeave),\n active = _useActive.active,\n activeProps = _objectWithoutProperties(_useActive, [\"active\"]); // Fallback of active check to avoid hover on menu title or disabled item\n\n\n var _React$useState = React.useState(false),\n _React$useState2 = _slicedToArray(_React$useState, 2),\n childrenActive = _React$useState2[0],\n setChildrenActive = _React$useState2[1];\n\n var triggerChildrenActive = function triggerChildrenActive(newActive) {\n if (!mergedDisabled) {\n setChildrenActive(newActive);\n }\n };\n\n var onInternalMouseEnter = function onInternalMouseEnter(domEvent) {\n triggerChildrenActive(true);\n onMouseEnter === null || onMouseEnter === void 0 ? void 0 : onMouseEnter({\n key: eventKey,\n domEvent: domEvent\n });\n };\n\n var onInternalMouseLeave = function onInternalMouseLeave(domEvent) {\n triggerChildrenActive(false);\n onMouseLeave === null || onMouseLeave === void 0 ? void 0 : onMouseLeave({\n key: eventKey,\n domEvent: domEvent\n });\n };\n\n var mergedActive = React.useMemo(function () {\n if (active) {\n return active;\n }\n\n if (mode !== 'inline') {\n return childrenActive || isSubPathKey([activeKey], eventKey);\n }\n\n return false;\n }, [mode, active, activeKey, childrenActive, eventKey, isSubPathKey]); // ========================== DirectionStyle ==========================\n\n var directionStyle = useDirectionStyle(connectedPath.length); // =============================== Events ===============================\n // >>>> Title click\n\n var onInternalTitleClick = function onInternalTitleClick(e) {\n // Skip if disabled\n if (mergedDisabled) {\n return;\n }\n\n onTitleClick === null || onTitleClick === void 0 ? void 0 : onTitleClick({\n key: eventKey,\n domEvent: e\n }); // Trigger open by click when mode is `inline`\n\n if (mode === 'inline') {\n onOpenChange(eventKey, !originOpen);\n }\n }; // >>>> Context for children click\n\n\n var onMergedItemClick = useMemoCallback(function (info) {\n onClick === null || onClick === void 0 ? void 0 : onClick(warnItemProp(info));\n onItemClick(info);\n }); // >>>>> Visible change\n\n var onPopupVisibleChange = function onPopupVisibleChange(newVisible) {\n if (mode !== 'inline') {\n onOpenChange(eventKey, newVisible);\n }\n };\n /**\n * Used for accessibility. Helper will focus element without key board.\n * We should manually trigger an active\n */\n\n\n var onInternalFocus = function onInternalFocus() {\n onActive(eventKey);\n }; // =============================== Render ===============================\n\n\n var popupId = domDataId && \"\".concat(domDataId, \"-popup\"); // >>>>> Title\n\n var titleNode = /*#__PURE__*/React.createElement(\"div\", _extends({\n role: \"menuitem\",\n style: directionStyle,\n className: \"\".concat(subMenuPrefixCls, \"-title\"),\n tabIndex: mergedDisabled ? null : -1,\n ref: elementRef,\n title: typeof title === 'string' ? title : null,\n \"data-menu-id\": overflowDisabled && domDataId ? null : domDataId,\n \"aria-expanded\": open,\n \"aria-haspopup\": true,\n \"aria-controls\": popupId,\n \"aria-disabled\": mergedDisabled,\n onClick: onInternalTitleClick,\n onFocus: onInternalFocus\n }, activeProps), title, /*#__PURE__*/React.createElement(Icon, {\n icon: mode !== 'horizontal' ? mergedExpandIcon : null,\n props: _objectSpread(_objectSpread({}, props), {}, {\n isOpen: open,\n // [Legacy] Not sure why need this mark\n isSubMenu: true\n })\n }, /*#__PURE__*/React.createElement(\"i\", {\n className: \"\".concat(subMenuPrefixCls, \"-arrow\")\n }))); // Cache mode if it change to `inline` which do not have popup motion\n\n var triggerModeRef = React.useRef(mode);\n\n if (mode !== 'inline') {\n triggerModeRef.current = connectedPath.length > 1 ? 'vertical' : mode;\n }\n\n if (!overflowDisabled) {\n var triggerMode = triggerModeRef.current; // Still wrap with Trigger here since we need avoid react re-mount dom node\n // Which makes motion failed\n\n titleNode = /*#__PURE__*/React.createElement(PopupTrigger, {\n mode: triggerMode,\n prefixCls: subMenuPrefixCls,\n visible: !internalPopupClose && open && mode !== 'inline',\n popupClassName: popupClassName,\n popupOffset: popupOffset,\n popup: /*#__PURE__*/React.createElement(MenuContextProvider // Special handle of horizontal mode\n , {\n mode: triggerMode === 'horizontal' ? 'vertical' : triggerMode\n }, /*#__PURE__*/React.createElement(SubMenuList, {\n id: popupId,\n ref: popupRef\n }, children)),\n disabled: mergedDisabled,\n onVisibleChange: onPopupVisibleChange\n }, titleNode);\n } // >>>>> Render\n\n\n return /*#__PURE__*/React.createElement(MenuContextProvider, {\n onItemClick: onMergedItemClick,\n mode: mode === 'horizontal' ? 'vertical' : mode,\n itemIcon: mergedItemIcon,\n expandIcon: mergedExpandIcon\n }, /*#__PURE__*/React.createElement(Overflow.Item, _extends({\n role: \"none\"\n }, restProps, {\n component: \"li\",\n style: style,\n className: classNames(subMenuPrefixCls, \"\".concat(subMenuPrefixCls, \"-\").concat(mode), className, (_classNames = {}, _defineProperty(_classNames, \"\".concat(subMenuPrefixCls, \"-open\"), open), _defineProperty(_classNames, \"\".concat(subMenuPrefixCls, \"-active\"), mergedActive), _defineProperty(_classNames, \"\".concat(subMenuPrefixCls, \"-selected\"), childrenSelected), _defineProperty(_classNames, \"\".concat(subMenuPrefixCls, \"-disabled\"), mergedDisabled), _classNames)),\n onMouseEnter: onInternalMouseEnter,\n onMouseLeave: onInternalMouseLeave\n }), titleNode, !overflowDisabled && /*#__PURE__*/React.createElement(InlineSubMenuList, {\n id: popupId,\n open: open,\n keyPath: connectedPath\n }, children)));\n};\n\nexport default function SubMenu(props) {\n var eventKey = props.eventKey,\n children = props.children;\n var connectedKeyPath = useFullPath(eventKey);\n var childList = parseChildren(children, connectedKeyPath); // ==================== Record KeyPath ====================\n\n var measure = useMeasure(); // eslint-disable-next-line consistent-return\n\n React.useEffect(function () {\n if (measure) {\n measure.registerPath(eventKey, connectedKeyPath);\n return function () {\n measure.unregisterPath(eventKey, connectedKeyPath);\n };\n }\n }, [connectedKeyPath]);\n var renderNode; // ======================== Render ========================\n\n if (measure) {\n renderNode = childList;\n } else {\n renderNode = /*#__PURE__*/React.createElement(InternalSubMenu, props, childList);\n }\n\n return /*#__PURE__*/React.createElement(PathTrackerContext.Provider, {\n value: connectedKeyPath\n }, renderNode);\n}","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport isVisible from './isVisible';\n\nfunction focusable(node) {\n var includePositive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n if (isVisible(node)) {\n var nodeName = node.nodeName.toLowerCase();\n var isFocusableElement = // Focusable element\n ['input', 'select', 'textarea', 'button'].includes(nodeName) || // Editable element\n node.isContentEditable || // Anchor with href element\n nodeName === 'a' && !!node.getAttribute('href'); // Get tabIndex\n\n var tabIndexAttr = node.getAttribute('tabindex');\n var tabIndexNum = Number(tabIndexAttr); // Parse as number if validate\n\n var tabIndex = null;\n\n if (tabIndexAttr && !Number.isNaN(tabIndexNum)) {\n tabIndex = tabIndexNum;\n } else if (isFocusableElement && tabIndex === null) {\n tabIndex = 0;\n } // Block focusable if disabled\n\n\n if (isFocusableElement && node.disabled) {\n tabIndex = null;\n }\n\n return tabIndex !== null && (tabIndex >= 0 || includePositive && tabIndex < 0);\n }\n\n return false;\n}\n\nexport function getFocusNodeList(node) {\n var includePositive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var res = _toConsumableArray(node.querySelectorAll('*')).filter(function (child) {\n return focusable(child, includePositive);\n });\n\n if (focusable(node, includePositive)) {\n res.unshift(node);\n }\n\n return res;\n}\nvar lastFocusElement = null;\n/** @deprecated Do not use since this may failed when used in async */\n\nexport function saveLastFocusNode() {\n lastFocusElement = document.activeElement;\n}\n/** @deprecated Do not use since this may failed when used in async */\n\nexport function clearLastFocusNode() {\n lastFocusElement = null;\n}\n/** @deprecated Do not use since this may failed when used in async */\n\nexport function backLastFocusNode() {\n if (lastFocusElement) {\n try {\n // 元素可能已经被移动了\n lastFocusElement.focus();\n /* eslint-disable no-empty */\n } catch (e) {// empty\n }\n /* eslint-enable no-empty */\n\n }\n}\nexport function limitTabRange(node, e) {\n if (e.keyCode === 9) {\n var tabNodeList = getFocusNodeList(node);\n var lastTabNode = tabNodeList[e.shiftKey ? 0 : tabNodeList.length - 1];\n var leavingTab = lastTabNode === document.activeElement || node === document.activeElement;\n\n if (leavingTab) {\n var target = tabNodeList[e.shiftKey ? tabNodeList.length - 1 : 0];\n target.focus();\n e.preventDefault();\n }\n }\n}","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport * as React from 'react';\nimport KeyCode from \"rc-util/es/KeyCode\";\nimport raf from \"rc-util/es/raf\";\nimport { getFocusNodeList } from \"rc-util/es/Dom/focus\";\nimport { getMenuId } from '../context/IdContext'; // destruct to reduce minify size\n\nvar LEFT = KeyCode.LEFT,\n RIGHT = KeyCode.RIGHT,\n UP = KeyCode.UP,\n DOWN = KeyCode.DOWN,\n ENTER = KeyCode.ENTER,\n ESC = KeyCode.ESC;\nvar ArrowKeys = [UP, DOWN, LEFT, RIGHT];\n\nfunction getOffset(mode, isRootLevel, isRtl, which) {\n var _inline, _horizontal, _vertical, _offsets$;\n\n var prev = 'prev';\n var next = 'next';\n var children = 'children';\n var parent = 'parent'; // Inline enter is special that we use unique operation\n\n if (mode === 'inline' && which === ENTER) {\n return {\n inlineTrigger: true\n };\n }\n\n var inline = (_inline = {}, _defineProperty(_inline, UP, prev), _defineProperty(_inline, DOWN, next), _inline);\n var horizontal = (_horizontal = {}, _defineProperty(_horizontal, LEFT, isRtl ? next : prev), _defineProperty(_horizontal, RIGHT, isRtl ? prev : next), _defineProperty(_horizontal, DOWN, children), _defineProperty(_horizontal, ENTER, children), _horizontal);\n var vertical = (_vertical = {}, _defineProperty(_vertical, UP, prev), _defineProperty(_vertical, DOWN, next), _defineProperty(_vertical, ENTER, children), _defineProperty(_vertical, ESC, parent), _defineProperty(_vertical, LEFT, isRtl ? children : parent), _defineProperty(_vertical, RIGHT, isRtl ? parent : children), _vertical);\n var offsets = {\n inline: inline,\n horizontal: horizontal,\n vertical: vertical,\n inlineSub: inline,\n horizontalSub: vertical,\n verticalSub: vertical\n };\n var type = (_offsets$ = offsets[\"\".concat(mode).concat(isRootLevel ? '' : 'Sub')]) === null || _offsets$ === void 0 ? void 0 : _offsets$[which];\n\n switch (type) {\n case prev:\n return {\n offset: -1,\n sibling: true\n };\n\n case next:\n return {\n offset: 1,\n sibling: true\n };\n\n case parent:\n return {\n offset: -1,\n sibling: false\n };\n\n case children:\n return {\n offset: 1,\n sibling: false\n };\n\n default:\n return null;\n }\n}\n\nfunction findContainerUL(element) {\n var current = element;\n\n while (current) {\n if (current.getAttribute('data-menu-list')) {\n return current;\n }\n\n current = current.parentElement;\n } // Normally should not reach this line\n\n /* istanbul ignore next */\n\n\n return null;\n}\n/**\n * Find focused element within element set provided\n */\n\n\nfunction getFocusElement(activeElement, elements) {\n var current = activeElement || document.activeElement;\n\n while (current) {\n if (elements.has(current)) {\n return current;\n }\n\n current = current.parentElement;\n }\n\n return null;\n}\n/**\n * Get focusable elements from the element set under provided container\n */\n\n\nfunction getFocusableElements(container, elements) {\n var list = getFocusNodeList(container, true);\n return list.filter(function (ele) {\n return elements.has(ele);\n });\n}\n\nfunction getNextFocusElement(parentQueryContainer, elements, focusMenuElement) {\n var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;\n\n // Key on the menu item will not get validate parent container\n if (!parentQueryContainer) {\n return null;\n } // List current level menu item elements\n\n\n var sameLevelFocusableMenuElementList = getFocusableElements(parentQueryContainer, elements); // Find next focus index\n\n var count = sameLevelFocusableMenuElementList.length;\n var focusIndex = sameLevelFocusableMenuElementList.findIndex(function (ele) {\n return focusMenuElement === ele;\n });\n\n if (offset < 0) {\n if (focusIndex === -1) {\n focusIndex = count - 1;\n } else {\n focusIndex -= 1;\n }\n } else if (offset > 0) {\n focusIndex += 1;\n }\n\n focusIndex = (focusIndex + count) % count; // Focus menu item\n\n return sameLevelFocusableMenuElementList[focusIndex];\n}\n\nexport default function useAccessibility(mode, activeKey, isRtl, id, containerRef, getKeys, getKeyPath, triggerActiveKey, triggerAccessibilityOpen, originOnKeyDown) {\n var rafRef = React.useRef();\n var activeRef = React.useRef();\n activeRef.current = activeKey;\n\n var cleanRaf = function cleanRaf() {\n raf.cancel(rafRef.current);\n };\n\n React.useEffect(function () {\n return function () {\n cleanRaf();\n };\n }, []);\n return function (e) {\n var which = e.which;\n\n if ([].concat(ArrowKeys, [ENTER, ESC]).includes(which)) {\n // Convert key to elements\n var elements;\n var key2element;\n var element2key; // >>> Wrap as function since we use raf for some case\n\n var refreshElements = function refreshElements() {\n elements = new Set();\n key2element = new Map();\n element2key = new Map();\n var keys = getKeys();\n keys.forEach(function (key) {\n var element = document.querySelector(\"[data-menu-id='\".concat(getMenuId(id, key), \"']\"));\n\n if (element) {\n elements.add(element);\n element2key.set(element, key);\n key2element.set(key, element);\n }\n });\n return elements;\n };\n\n refreshElements(); // First we should find current focused MenuItem/SubMenu element\n\n var activeElement = key2element.get(activeKey);\n var focusMenuElement = getFocusElement(activeElement, elements);\n var focusMenuKey = element2key.get(focusMenuElement);\n var offsetObj = getOffset(mode, getKeyPath(focusMenuKey, true).length === 1, isRtl, which); // Some mode do not have fully arrow operation like inline\n\n if (!offsetObj) {\n return;\n } // Arrow prevent default to avoid page scroll\n\n\n if (ArrowKeys.includes(which)) {\n e.preventDefault();\n }\n\n var tryFocus = function tryFocus(menuElement) {\n if (menuElement) {\n var focusTargetElement = menuElement; // Focus to link instead of menu item if possible\n\n var link = menuElement.querySelector('a');\n\n if (link === null || link === void 0 ? void 0 : link.getAttribute('href')) {\n focusTargetElement = link;\n }\n\n var targetKey = element2key.get(menuElement);\n triggerActiveKey(targetKey);\n /**\n * Do not `useEffect` here since `tryFocus` may trigger async\n * which makes React sync update the `activeKey`\n * that force render before `useRef` set the next activeKey\n */\n\n cleanRaf();\n rafRef.current = raf(function () {\n if (activeRef.current === targetKey) {\n focusTargetElement.focus();\n }\n });\n }\n };\n\n if (offsetObj.sibling || !focusMenuElement) {\n // ========================== Sibling ==========================\n // Find walkable focus menu element container\n var parentQueryContainer;\n\n if (!focusMenuElement || mode === 'inline') {\n parentQueryContainer = containerRef.current;\n } else {\n parentQueryContainer = findContainerUL(focusMenuElement);\n } // Get next focus element\n\n\n var targetElement = getNextFocusElement(parentQueryContainer, elements, focusMenuElement, offsetObj.offset); // Focus menu item\n\n tryFocus(targetElement); // ======================= InlineTrigger =======================\n } else if (offsetObj.inlineTrigger) {\n // Inline trigger no need switch to sub menu item\n triggerAccessibilityOpen(focusMenuKey); // =========================== Level ===========================\n } else if (offsetObj.offset > 0) {\n triggerAccessibilityOpen(focusMenuKey, true);\n cleanRaf();\n rafRef.current = raf(function () {\n // Async should resync elements\n refreshElements();\n var controlId = focusMenuElement.getAttribute('aria-controls');\n var subQueryContainer = document.getElementById(controlId); // Get sub focusable menu item\n\n var targetElement = getNextFocusElement(subQueryContainer, elements); // Focus menu item\n\n tryFocus(targetElement);\n }, 5);\n } else if (offsetObj.offset < 0) {\n var keyPath = getKeyPath(focusMenuKey, true);\n var parentKey = keyPath[keyPath.length - 2];\n var parentMenuElement = key2element.get(parentKey); // Focus menu item\n\n triggerAccessibilityOpen(parentKey, false);\n tryFocus(parentMenuElement);\n }\n } // Pass origin key down event\n\n\n originOnKeyDown === null || originOnKeyDown === void 0 ? void 0 : originOnKeyDown(e);\n };\n}","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport * as React from 'react';\nimport useMergedState from \"rc-util/es/hooks/useMergedState\";\nvar uniquePrefix = Math.random().toFixed(5).toString().slice(2);\nvar internalId = 0;\nexport default function useUUID(id) {\n var _useMergedState = useMergedState(id, {\n value: id\n }),\n _useMergedState2 = _slicedToArray(_useMergedState, 2),\n uuid = _useMergedState2[0],\n setUUID = _useMergedState2[1];\n\n React.useEffect(function () {\n internalId += 1;\n var newId = process.env.NODE_ENV === 'test' ? 'test' : \"\".concat(uniquePrefix, \"-\").concat(internalId);\n setUUID(\"rc-menu-uuid-\".concat(newId));\n }, []);\n return uuid;\n}","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport * as React from 'react';\nimport { useRef, useCallback } from 'react';\nimport warning from \"rc-util/es/warning\";\nimport { nextSlice } from '../utils/timeUtil';\nvar PATH_SPLIT = '__RC_UTIL_PATH_SPLIT__';\n\nvar getPathStr = function getPathStr(keyPath) {\n return keyPath.join(PATH_SPLIT);\n};\n\nvar getPathKeys = function getPathKeys(keyPathStr) {\n return keyPathStr.split(PATH_SPLIT);\n};\n\nexport var OVERFLOW_KEY = 'rc-menu-more';\nexport default function useKeyRecords() {\n var _React$useState = React.useState({}),\n _React$useState2 = _slicedToArray(_React$useState, 2),\n internalForceUpdate = _React$useState2[1];\n\n var key2pathRef = useRef(new Map());\n var path2keyRef = useRef(new Map());\n\n var _React$useState3 = React.useState([]),\n _React$useState4 = _slicedToArray(_React$useState3, 2),\n overflowKeys = _React$useState4[0],\n setOverflowKeys = _React$useState4[1];\n\n var updateRef = useRef(0);\n var destroyRef = useRef(false);\n\n var forceUpdate = function forceUpdate() {\n if (!destroyRef.current) {\n internalForceUpdate({});\n }\n };\n\n var registerPath = useCallback(function (key, keyPath) {\n // Warning for invalidate or duplicated `key`\n if (process.env.NODE_ENV !== 'production') {\n warning(!key2pathRef.current.has(key), \"Duplicated key '\".concat(key, \"' used in Menu by path [\").concat(keyPath.join(' > '), \"]\"));\n } // Fill map\n\n\n var connectedPath = getPathStr(keyPath);\n path2keyRef.current.set(connectedPath, key);\n key2pathRef.current.set(key, connectedPath);\n updateRef.current += 1;\n var id = updateRef.current;\n nextSlice(function () {\n if (id === updateRef.current) {\n forceUpdate();\n }\n });\n }, []);\n var unregisterPath = useCallback(function (key, keyPath) {\n var connectedPath = getPathStr(keyPath);\n path2keyRef.current.delete(connectedPath);\n key2pathRef.current.delete(key);\n }, []);\n var refreshOverflowKeys = useCallback(function (keys) {\n setOverflowKeys(keys);\n }, []);\n var getKeyPath = useCallback(function (eventKey, includeOverflow) {\n var fullPath = key2pathRef.current.get(eventKey) || '';\n var keys = getPathKeys(fullPath);\n\n if (includeOverflow && overflowKeys.includes(keys[0])) {\n keys.unshift(OVERFLOW_KEY);\n }\n\n return keys;\n }, [overflowKeys]);\n var isSubPathKey = useCallback(function (pathKeys, eventKey) {\n return pathKeys.some(function (pathKey) {\n var pathKeyList = getKeyPath(pathKey, true);\n return pathKeyList.includes(eventKey);\n });\n }, [getKeyPath]);\n\n var getKeys = function getKeys() {\n var keys = _toConsumableArray(key2pathRef.current.keys());\n\n if (overflowKeys.length) {\n keys.push(OVERFLOW_KEY);\n }\n\n return keys;\n };\n /**\n * Find current key related child path keys\n */\n\n\n var getSubPathKeys = useCallback(function (key) {\n var connectedPath = \"\".concat(key2pathRef.current.get(key)).concat(PATH_SPLIT);\n var pathKeys = new Set();\n\n _toConsumableArray(path2keyRef.current.keys()).forEach(function (pathKey) {\n if (pathKey.startsWith(connectedPath)) {\n pathKeys.add(path2keyRef.current.get(pathKey));\n }\n });\n\n return pathKeys;\n }, []);\n React.useEffect(function () {\n return function () {\n destroyRef.current = true;\n };\n }, []);\n return {\n // Register\n registerPath: registerPath,\n unregisterPath: unregisterPath,\n refreshOverflowKeys: refreshOverflowKeys,\n // Util\n isSubPathKey: isSubPathKey,\n getKeyPath: getKeyPath,\n getKeys: getKeys,\n getSubPathKeys: getSubPathKeys\n };\n}","export function nextSlice(callback) {\n /* istanbul ignore next */\n Promise.resolve().then(callback);\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport shallowEqual from 'shallowequal';\nimport useMergedState from \"rc-util/es/hooks/useMergedState\";\nimport warning from \"rc-util/es/warning\";\nimport Overflow from 'rc-overflow';\nimport MenuItem from './MenuItem';\nimport { parseChildren } from './utils/nodeUtil';\nimport MenuContextProvider from './context/MenuContext';\nimport useMemoCallback from './hooks/useMemoCallback';\nimport { warnItemProp } from './utils/warnUtil';\nimport SubMenu from './SubMenu';\nimport useAccessibility from './hooks/useAccessibility';\nimport useUUID from './hooks/useUUID';\nimport { PathRegisterContext, PathUserContext } from './context/PathContext';\nimport useKeyRecords, { OVERFLOW_KEY } from './hooks/useKeyRecords';\nimport { IdContext } from './context/IdContext';\n/**\n * Menu modify after refactor:\n * ## Add\n * - disabled\n *\n * ## Remove\n * - openTransitionName\n * - openAnimation\n * - onDestroy\n * - siderCollapsed: Seems antd do not use this prop (Need test in antd)\n * - collapsedWidth: Seems this logic should be handle by antd Layout.Sider\n */\n// optimize for render\n\nvar EMPTY_LIST = [];\n\nvar Menu = function Menu(props) {\n var _childList$, _classNames;\n\n var _props$prefixCls = props.prefixCls,\n prefixCls = _props$prefixCls === void 0 ? 'rc-menu' : _props$prefixCls,\n style = props.style,\n className = props.className,\n _props$tabIndex = props.tabIndex,\n tabIndex = _props$tabIndex === void 0 ? 0 : _props$tabIndex,\n children = props.children,\n direction = props.direction,\n id = props.id,\n _props$mode = props.mode,\n mode = _props$mode === void 0 ? 'vertical' : _props$mode,\n inlineCollapsed = props.inlineCollapsed,\n disabled = props.disabled,\n disabledOverflow = props.disabledOverflow,\n _props$subMenuOpenDel = props.subMenuOpenDelay,\n subMenuOpenDelay = _props$subMenuOpenDel === void 0 ? 0.1 : _props$subMenuOpenDel,\n _props$subMenuCloseDe = props.subMenuCloseDelay,\n subMenuCloseDelay = _props$subMenuCloseDe === void 0 ? 0.1 : _props$subMenuCloseDe,\n forceSubMenuRender = props.forceSubMenuRender,\n defaultOpenKeys = props.defaultOpenKeys,\n openKeys = props.openKeys,\n activeKey = props.activeKey,\n defaultActiveFirst = props.defaultActiveFirst,\n _props$selectable = props.selectable,\n selectable = _props$selectable === void 0 ? true : _props$selectable,\n _props$multiple = props.multiple,\n multiple = _props$multiple === void 0 ? false : _props$multiple,\n defaultSelectedKeys = props.defaultSelectedKeys,\n selectedKeys = props.selectedKeys,\n onSelect = props.onSelect,\n onDeselect = props.onDeselect,\n _props$inlineIndent = props.inlineIndent,\n inlineIndent = _props$inlineIndent === void 0 ? 24 : _props$inlineIndent,\n motion = props.motion,\n defaultMotions = props.defaultMotions,\n _props$triggerSubMenu = props.triggerSubMenuAction,\n triggerSubMenuAction = _props$triggerSubMenu === void 0 ? 'hover' : _props$triggerSubMenu,\n builtinPlacements = props.builtinPlacements,\n itemIcon = props.itemIcon,\n expandIcon = props.expandIcon,\n _props$overflowedIndi = props.overflowedIndicator,\n overflowedIndicator = _props$overflowedIndi === void 0 ? '...' : _props$overflowedIndi,\n overflowedIndicatorPopupClassName = props.overflowedIndicatorPopupClassName,\n getPopupContainer = props.getPopupContainer,\n onClick = props.onClick,\n onOpenChange = props.onOpenChange,\n onKeyDown = props.onKeyDown,\n openAnimation = props.openAnimation,\n openTransitionName = props.openTransitionName,\n restProps = _objectWithoutProperties(props, [\"prefixCls\", \"style\", \"className\", \"tabIndex\", \"children\", \"direction\", \"id\", \"mode\", \"inlineCollapsed\", \"disabled\", \"disabledOverflow\", \"subMenuOpenDelay\", \"subMenuCloseDelay\", \"forceSubMenuRender\", \"defaultOpenKeys\", \"openKeys\", \"activeKey\", \"defaultActiveFirst\", \"selectable\", \"multiple\", \"defaultSelectedKeys\", \"selectedKeys\", \"onSelect\", \"onDeselect\", \"inlineIndent\", \"motion\", \"defaultMotions\", \"triggerSubMenuAction\", \"builtinPlacements\", \"itemIcon\", \"expandIcon\", \"overflowedIndicator\", \"overflowedIndicatorPopupClassName\", \"getPopupContainer\", \"onClick\", \"onOpenChange\", \"onKeyDown\", \"openAnimation\", \"openTransitionName\"]);\n\n var childList = parseChildren(children, EMPTY_LIST);\n\n var _React$useState = React.useState(false),\n _React$useState2 = _slicedToArray(_React$useState, 2),\n mounted = _React$useState2[0],\n setMounted = _React$useState2[1];\n\n var containerRef = React.useRef();\n var uuid = useUUID(id);\n var isRtl = direction === 'rtl'; // ========================= Warn =========================\n\n if (process.env.NODE_ENV !== 'production') {\n warning(!openAnimation && !openTransitionName, '`openAnimation` and `openTransitionName` is removed. Please use `motion` or `defaultMotion` instead.');\n } // ========================= Mode =========================\n\n\n var _React$useMemo = React.useMemo(function () {\n if ((mode === 'inline' || mode === 'vertical') && inlineCollapsed) {\n return ['vertical', inlineCollapsed];\n }\n\n return [mode, false];\n }, [mode, inlineCollapsed]),\n _React$useMemo2 = _slicedToArray(_React$useMemo, 2),\n mergedMode = _React$useMemo2[0],\n mergedInlineCollapsed = _React$useMemo2[1]; // ====================== Responsive ======================\n\n\n var _React$useState3 = React.useState(0),\n _React$useState4 = _slicedToArray(_React$useState3, 2),\n lastVisibleIndex = _React$useState4[0],\n setLastVisibleIndex = _React$useState4[1];\n\n var allVisible = lastVisibleIndex >= childList.length - 1 || mergedMode !== 'horizontal' || disabledOverflow; // ========================= Open =========================\n\n var _useMergedState = useMergedState(defaultOpenKeys, {\n value: openKeys,\n postState: function postState(keys) {\n return keys || EMPTY_LIST;\n }\n }),\n _useMergedState2 = _slicedToArray(_useMergedState, 2),\n mergedOpenKeys = _useMergedState2[0],\n setMergedOpenKeys = _useMergedState2[1];\n\n var triggerOpenKeys = function triggerOpenKeys(keys) {\n setMergedOpenKeys(keys);\n onOpenChange === null || onOpenChange === void 0 ? void 0 : onOpenChange(keys);\n }; // >>>>> Cache & Reset open keys when inlineCollapsed changed\n\n\n var _React$useState5 = React.useState(mergedOpenKeys),\n _React$useState6 = _slicedToArray(_React$useState5, 2),\n inlineCacheOpenKeys = _React$useState6[0],\n setInlineCacheOpenKeys = _React$useState6[1];\n\n var isInlineMode = mergedMode === 'inline';\n var mountRef = React.useRef(false); // Cache\n\n React.useEffect(function () {\n if (isInlineMode) {\n setInlineCacheOpenKeys(mergedOpenKeys);\n }\n }, [mergedOpenKeys]); // Restore\n\n React.useEffect(function () {\n if (!mountRef.current) {\n mountRef.current = true;\n return;\n }\n\n if (isInlineMode) {\n setMergedOpenKeys(inlineCacheOpenKeys);\n } else {\n // Trigger open event in case its in control\n triggerOpenKeys(EMPTY_LIST);\n }\n }, [isInlineMode]); // ========================= Path =========================\n\n var _useKeyRecords = useKeyRecords(),\n registerPath = _useKeyRecords.registerPath,\n unregisterPath = _useKeyRecords.unregisterPath,\n refreshOverflowKeys = _useKeyRecords.refreshOverflowKeys,\n isSubPathKey = _useKeyRecords.isSubPathKey,\n getKeyPath = _useKeyRecords.getKeyPath,\n getKeys = _useKeyRecords.getKeys,\n getSubPathKeys = _useKeyRecords.getSubPathKeys;\n\n var registerPathContext = React.useMemo(function () {\n return {\n registerPath: registerPath,\n unregisterPath: unregisterPath\n };\n }, [registerPath, unregisterPath]);\n var pathUserContext = React.useMemo(function () {\n return {\n isSubPathKey: isSubPathKey\n };\n }, [isSubPathKey]);\n React.useEffect(function () {\n refreshOverflowKeys(allVisible ? EMPTY_LIST : childList.slice(lastVisibleIndex + 1).map(function (child) {\n return child.key;\n }));\n }, [lastVisibleIndex, allVisible]); // ======================== Active ========================\n\n var _useMergedState3 = useMergedState(activeKey || defaultActiveFirst && ((_childList$ = childList[0]) === null || _childList$ === void 0 ? void 0 : _childList$.key), {\n value: activeKey\n }),\n _useMergedState4 = _slicedToArray(_useMergedState3, 2),\n mergedActiveKey = _useMergedState4[0],\n setMergedActiveKey = _useMergedState4[1];\n\n var onActive = useMemoCallback(function (key) {\n setMergedActiveKey(key);\n });\n var onInactive = useMemoCallback(function () {\n setMergedActiveKey(undefined);\n }); // ======================== Select ========================\n // >>>>> Select keys\n\n var _useMergedState5 = useMergedState(defaultSelectedKeys || [], {\n value: selectedKeys,\n // Legacy convert key to array\n postState: function postState(keys) {\n if (Array.isArray(keys)) {\n return keys;\n }\n\n if (keys === null || keys === undefined) {\n return EMPTY_LIST;\n }\n\n return [keys];\n }\n }),\n _useMergedState6 = _slicedToArray(_useMergedState5, 2),\n mergedSelectKeys = _useMergedState6[0],\n setMergedSelectKeys = _useMergedState6[1]; // >>>>> Trigger select\n\n\n var triggerSelection = function triggerSelection(info) {\n if (selectable) {\n // Insert or Remove\n var targetKey = info.key;\n var exist = mergedSelectKeys.includes(targetKey);\n var newSelectKeys;\n\n if (multiple) {\n if (exist) {\n newSelectKeys = mergedSelectKeys.filter(function (key) {\n return key !== targetKey;\n });\n } else {\n newSelectKeys = [].concat(_toConsumableArray(mergedSelectKeys), [targetKey]);\n }\n } else {\n newSelectKeys = [targetKey];\n }\n\n setMergedSelectKeys(newSelectKeys); // Trigger event\n\n var selectInfo = _objectSpread(_objectSpread({}, info), {}, {\n selectedKeys: newSelectKeys\n });\n\n if (exist) {\n onDeselect === null || onDeselect === void 0 ? void 0 : onDeselect(selectInfo);\n } else {\n onSelect === null || onSelect === void 0 ? void 0 : onSelect(selectInfo);\n }\n } // Whatever selectable, always close it\n\n\n if (!multiple && mergedOpenKeys.length && mergedMode !== 'inline') {\n triggerOpenKeys(EMPTY_LIST);\n }\n }; // ========================= Open =========================\n\n /**\n * Click for item. SubMenu do not have selection status\n */\n\n\n var onInternalClick = useMemoCallback(function (info) {\n onClick === null || onClick === void 0 ? void 0 : onClick(warnItemProp(info));\n triggerSelection(info);\n });\n var onInternalOpenChange = useMemoCallback(function (key, open) {\n var newOpenKeys = mergedOpenKeys.filter(function (k) {\n return k !== key;\n });\n\n if (open) {\n newOpenKeys.push(key);\n } else if (mergedMode !== 'inline') {\n // We need find all related popup to close\n var subPathKeys = getSubPathKeys(key);\n newOpenKeys = newOpenKeys.filter(function (k) {\n return !subPathKeys.has(k);\n });\n }\n\n if (!shallowEqual(mergedOpenKeys, newOpenKeys)) {\n triggerOpenKeys(newOpenKeys);\n }\n });\n var getInternalPopupContainer = useMemoCallback(getPopupContainer); // ==================== Accessibility =====================\n\n var triggerAccessibilityOpen = function triggerAccessibilityOpen(key, open) {\n var nextOpen = open !== null && open !== void 0 ? open : !mergedOpenKeys.includes(key);\n onInternalOpenChange(key, nextOpen);\n };\n\n var onInternalKeyDown = useAccessibility(mergedMode, mergedActiveKey, isRtl, uuid, containerRef, getKeys, getKeyPath, setMergedActiveKey, triggerAccessibilityOpen, onKeyDown); // ======================== Effect ========================\n\n React.useEffect(function () {\n setMounted(true);\n }, []); // ======================== Render ========================\n // >>>>> Children\n\n var wrappedChildList = mergedMode !== 'horizontal' || disabledOverflow ? childList : // Need wrap for overflow dropdown that do not response for open\n childList.map(function (child, index) {\n return (\n /*#__PURE__*/\n // Always wrap provider to avoid sub node re-mount\n React.createElement(MenuContextProvider, {\n key: child.key,\n overflowDisabled: index > lastVisibleIndex\n }, child)\n );\n }); // >>>>> Container\n\n var container = /*#__PURE__*/React.createElement(Overflow, _extends({\n id: id,\n ref: containerRef,\n prefixCls: \"\".concat(prefixCls, \"-overflow\"),\n component: \"ul\",\n itemComponent: MenuItem,\n className: classNames(prefixCls, \"\".concat(prefixCls, \"-root\"), \"\".concat(prefixCls, \"-\").concat(mergedMode), className, (_classNames = {}, _defineProperty(_classNames, \"\".concat(prefixCls, \"-inline-collapsed\"), mergedInlineCollapsed), _defineProperty(_classNames, \"\".concat(prefixCls, \"-rtl\"), isRtl), _classNames)),\n dir: direction,\n style: style,\n role: \"menu\",\n tabIndex: tabIndex,\n data: wrappedChildList,\n renderRawItem: function renderRawItem(node) {\n return node;\n },\n renderRawRest: function renderRawRest(omitItems) {\n // We use origin list since wrapped list use context to prevent open\n var len = omitItems.length;\n var originOmitItems = len ? childList.slice(-len) : null;\n return /*#__PURE__*/React.createElement(SubMenu, {\n eventKey: OVERFLOW_KEY,\n title: overflowedIndicator,\n disabled: allVisible,\n internalPopupClose: len === 0,\n popupClassName: overflowedIndicatorPopupClassName\n }, originOmitItems);\n },\n maxCount: mergedMode !== 'horizontal' || disabledOverflow ? Overflow.INVALIDATE : Overflow.RESPONSIVE,\n ssr: \"full\",\n \"data-menu-list\": true,\n onVisibleChange: function onVisibleChange(newLastIndex) {\n setLastVisibleIndex(newLastIndex);\n },\n onKeyDown: onInternalKeyDown\n }, restProps)); // >>>>> Render\n\n return /*#__PURE__*/React.createElement(IdContext.Provider, {\n value: uuid\n }, /*#__PURE__*/React.createElement(MenuContextProvider, {\n prefixCls: prefixCls,\n mode: mergedMode,\n openKeys: mergedOpenKeys,\n rtl: isRtl // Disabled\n ,\n disabled: disabled // Motion\n ,\n motion: mounted ? motion : null,\n defaultMotions: mounted ? defaultMotions : null // Active\n ,\n activeKey: mergedActiveKey,\n onActive: onActive,\n onInactive: onInactive // Selection\n ,\n selectedKeys: mergedSelectKeys // Level\n ,\n inlineIndent: inlineIndent // Popup\n ,\n subMenuOpenDelay: subMenuOpenDelay,\n subMenuCloseDelay: subMenuCloseDelay,\n forceSubMenuRender: forceSubMenuRender,\n builtinPlacements: builtinPlacements,\n triggerSubMenuAction: triggerSubMenuAction,\n getPopupContainer: getInternalPopupContainer // Icon\n ,\n itemIcon: itemIcon,\n expandIcon: expandIcon // Events\n ,\n onItemClick: onInternalClick,\n onOpenChange: onInternalOpenChange\n }, /*#__PURE__*/React.createElement(PathUserContext.Provider, {\n value: pathUserContext\n }, container), /*#__PURE__*/React.createElement(\"div\", {\n style: {\n display: 'none'\n },\n \"aria-hidden\": true\n }, /*#__PURE__*/React.createElement(PathRegisterContext.Provider, {\n value: registerPathContext\n }, childList))));\n};\n\nexport default Menu;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport omit from \"rc-util/es/omit\";\nimport { parseChildren } from './utils/nodeUtil';\nimport { MenuContext } from './context/MenuContext';\nimport { useFullPath, useMeasure } from './context/PathContext';\n\nvar InternalMenuItemGroup = function InternalMenuItemGroup(_ref) {\n var className = _ref.className,\n title = _ref.title,\n eventKey = _ref.eventKey,\n children = _ref.children,\n restProps = _objectWithoutProperties(_ref, [\"className\", \"title\", \"eventKey\", \"children\"]);\n\n var _React$useContext = React.useContext(MenuContext),\n prefixCls = _React$useContext.prefixCls;\n\n var groupPrefixCls = \"\".concat(prefixCls, \"-item-group\");\n return /*#__PURE__*/React.createElement(\"li\", _extends({}, restProps, {\n onClick: function onClick(e) {\n return e.stopPropagation();\n },\n className: classNames(groupPrefixCls, className)\n }), /*#__PURE__*/React.createElement(\"div\", {\n className: \"\".concat(groupPrefixCls, \"-title\"),\n title: typeof title === 'string' ? title : undefined\n }, title), /*#__PURE__*/React.createElement(\"ul\", {\n className: \"\".concat(groupPrefixCls, \"-list\")\n }, children));\n};\n\nexport default function MenuItemGroup(_ref2) {\n var children = _ref2.children,\n props = _objectWithoutProperties(_ref2, [\"children\"]);\n\n var connectedKeyPath = useFullPath(props.eventKey);\n var childList = parseChildren(children, connectedKeyPath);\n var measure = useMeasure();\n\n if (measure) {\n return childList;\n }\n\n return /*#__PURE__*/React.createElement(InternalMenuItemGroup, omit(props, ['warnKey']), childList);\n}","import * as React from 'react';\nimport classNames from 'classnames';\nimport { MenuContext } from './context/MenuContext';\nimport { useMeasure } from './context/PathContext';\nexport default function Divider(_ref) {\n var className = _ref.className,\n style = _ref.style;\n\n var _React$useContext = React.useContext(MenuContext),\n prefixCls = _React$useContext.prefixCls;\n\n var measure = useMeasure();\n\n if (measure) {\n return null;\n }\n\n return /*#__PURE__*/React.createElement(\"li\", {\n className: classNames(\"\".concat(prefixCls, \"-item-divider\"), className),\n style: style\n });\n}","import Menu from './Menu';\nimport MenuItem from './MenuItem';\nimport SubMenu from './SubMenu';\nimport MenuItemGroup from './MenuItemGroup';\nimport { useFullPath as useOriginFullPath } from './context/PathContext';\nimport Divider from './Divider';\n/** @private Only used for antd internal. Do not use in your production. */\n\nvar useFullPath = useOriginFullPath;\nexport { SubMenu, MenuItem as Item, MenuItem, MenuItemGroup, MenuItemGroup as ItemGroup, Divider, useFullPath };\nvar ExportMenu = Menu;\nExportMenu.Item = MenuItem;\nExportMenu.SubMenu = SubMenu;\nExportMenu.ItemGroup = MenuItemGroup;\nExportMenu.Divider = Divider;\nexport default ExportMenu;","export default function formControlState(_ref) {\n var props = _ref.props,\n states = _ref.states,\n muiFormControl = _ref.muiFormControl;\n return states.reduce(function (acc, state) {\n acc[state] = props[state];\n\n if (muiFormControl) {\n if (typeof props[state] === 'undefined') {\n acc[state] = muiFormControl[state];\n }\n }\n\n return acc;\n }, {});\n}","import * as React from 'react';\nimport FormControlContext from './FormControlContext';\nexport default function useFormControl() {\n return React.useContext(FormControlContext);\n}","// ================== Collapse Motion ==================\nvar getCollapsedHeight = function getCollapsedHeight() {\n return {\n height: 0,\n opacity: 0\n };\n};\n\nvar getRealHeight = function getRealHeight(node) {\n return {\n height: node.scrollHeight,\n opacity: 1\n };\n};\n\nvar getCurrentHeight = function getCurrentHeight(node) {\n return {\n height: node.offsetHeight\n };\n};\n\nvar skipOpacityTransition = function skipOpacityTransition(_, event) {\n return (event === null || event === void 0 ? void 0 : event.deadline) === true || event.propertyName === 'height';\n};\n\nvar collapseMotion = {\n motionName: 'ant-motion-collapse',\n onAppearStart: getCollapsedHeight,\n onEnterStart: getCollapsedHeight,\n onAppearActive: getRealHeight,\n onEnterActive: getRealHeight,\n onLeaveStart: getCurrentHeight,\n onLeaveActive: getCollapsedHeight,\n onAppearEnd: skipOpacityTransition,\n onEnterEnd: skipOpacityTransition,\n onLeaveEnd: skipOpacityTransition,\n motionDeadline: 500\n};\n\nvar getTransitionName = function getTransitionName(rootPrefixCls, motion, transitionName) {\n if (transitionName !== undefined) {\n return transitionName;\n }\n\n return \"\".concat(rootPrefixCls, \"-\").concat(motion);\n};\n\nexport { getTransitionName };\nexport default collapseMotion;","import defaultMoment from 'moment';\n\nvar MomentUtils = /** @class */ (function () {\n function MomentUtils(_a) {\n var _b = _a === void 0 ? {} : _a, locale = _b.locale, instance = _b.instance, moment = _b.moment;\n this.yearFormat = \"YYYY\";\n this.yearMonthFormat = \"MMMM YYYY\";\n this.dateTime12hFormat = \"MMMM Do hh:mm a\";\n this.dateTime24hFormat = \"MMMM Do HH:mm\";\n this.time12hFormat = \"hh:mm A\";\n this.time24hFormat = \"HH:mm\";\n this.dateFormat = \"MMMM Do\";\n this.moment = instance || moment || defaultMoment;\n this.locale = locale;\n }\n MomentUtils.prototype.parse = function (value, format) {\n if (value === \"\") {\n return null;\n }\n return this.moment(value, format, true);\n };\n MomentUtils.prototype.date = function (value) {\n if (value === null) {\n return null;\n }\n var moment = this.moment(value);\n moment.locale(this.locale);\n return moment;\n };\n MomentUtils.prototype.isValid = function (value) {\n return this.moment(value).isValid();\n };\n MomentUtils.prototype.isNull = function (date) {\n return date === null;\n };\n MomentUtils.prototype.getDiff = function (date, comparing) {\n return date.diff(comparing);\n };\n MomentUtils.prototype.isAfter = function (date, value) {\n return date.isAfter(value);\n };\n MomentUtils.prototype.isBefore = function (date, value) {\n return date.isBefore(value);\n };\n MomentUtils.prototype.isAfterDay = function (date, value) {\n return date.isAfter(value, \"day\");\n };\n MomentUtils.prototype.isBeforeDay = function (date, value) {\n return date.isBefore(value, \"day\");\n };\n MomentUtils.prototype.isBeforeYear = function (date, value) {\n return date.isBefore(value, \"year\");\n };\n MomentUtils.prototype.isAfterYear = function (date, value) {\n return date.isAfter(value, \"year\");\n };\n MomentUtils.prototype.startOfDay = function (date) {\n return date.clone().startOf(\"day\");\n };\n MomentUtils.prototype.endOfDay = function (date) {\n return date.clone().endOf(\"day\");\n };\n MomentUtils.prototype.format = function (date, formatString) {\n date.locale(this.locale);\n return date.format(formatString);\n };\n MomentUtils.prototype.formatNumber = function (numberToFormat) {\n return numberToFormat;\n };\n MomentUtils.prototype.getHours = function (date) {\n return date.get(\"hours\");\n };\n MomentUtils.prototype.addDays = function (date, count) {\n return count < 0\n ? date.clone().subtract(Math.abs(count), \"days\")\n : date.clone().add(count, \"days\");\n };\n MomentUtils.prototype.setHours = function (date, count) {\n return date.clone().hours(count);\n };\n MomentUtils.prototype.getMinutes = function (date) {\n return date.get(\"minutes\");\n };\n MomentUtils.prototype.setMinutes = function (date, count) {\n return date.clone().minutes(count);\n };\n MomentUtils.prototype.getSeconds = function (date) {\n return date.get(\"seconds\");\n };\n MomentUtils.prototype.setSeconds = function (date, count) {\n return date.clone().seconds(count);\n };\n MomentUtils.prototype.getMonth = function (date) {\n return date.get(\"month\");\n };\n MomentUtils.prototype.isSameDay = function (date, comparing) {\n return date.isSame(comparing, \"day\");\n };\n MomentUtils.prototype.isSameMonth = function (date, comparing) {\n return date.isSame(comparing, \"month\");\n };\n MomentUtils.prototype.isSameYear = function (date, comparing) {\n return date.isSame(comparing, \"year\");\n };\n MomentUtils.prototype.isSameHour = function (date, comparing) {\n return date.isSame(comparing, \"hour\");\n };\n MomentUtils.prototype.setMonth = function (date, count) {\n return date.clone().month(count);\n };\n MomentUtils.prototype.getMeridiemText = function (ampm) {\n return ampm === \"am\" ? \"AM\" : \"PM\";\n };\n MomentUtils.prototype.startOfMonth = function (date) {\n return date.clone().startOf(\"month\");\n };\n MomentUtils.prototype.endOfMonth = function (date) {\n return date.clone().endOf(\"month\");\n };\n MomentUtils.prototype.getNextMonth = function (date) {\n return date.clone().add(1, \"month\");\n };\n MomentUtils.prototype.getPreviousMonth = function (date) {\n return date.clone().subtract(1, \"month\");\n };\n MomentUtils.prototype.getMonthArray = function (date) {\n var firstMonth = date.clone().startOf(\"year\");\n var monthArray = [firstMonth];\n while (monthArray.length < 12) {\n var prevMonth = monthArray[monthArray.length - 1];\n monthArray.push(this.getNextMonth(prevMonth));\n }\n return monthArray;\n };\n MomentUtils.prototype.getYear = function (date) {\n return date.get(\"year\");\n };\n MomentUtils.prototype.setYear = function (date, year) {\n return date.clone().set(\"year\", year);\n };\n MomentUtils.prototype.mergeDateAndTime = function (date, time) {\n return this.setMinutes(this.setHours(date, this.getHours(time)), this.getMinutes(time));\n };\n MomentUtils.prototype.getWeekdays = function () {\n return this.moment.weekdaysShort(true);\n };\n MomentUtils.prototype.isEqual = function (value, comparing) {\n if (value === null && comparing === null) {\n return true;\n }\n return this.moment(value).isSame(comparing);\n };\n MomentUtils.prototype.getWeekArray = function (date) {\n var start = date\n .clone()\n .startOf(\"month\")\n .startOf(\"week\");\n var end = date\n .clone()\n .endOf(\"month\")\n .endOf(\"week\");\n var count = 0;\n var current = start;\n var nestedWeeks = [];\n while (current.isBefore(end)) {\n var weekNumber = Math.floor(count / 7);\n nestedWeeks[weekNumber] = nestedWeeks[weekNumber] || [];\n nestedWeeks[weekNumber].push(current);\n current = current.clone().add(1, \"day\");\n count += 1;\n }\n return nestedWeeks;\n };\n MomentUtils.prototype.getYearRange = function (start, end) {\n var startDate = this.moment(start).startOf(\"year\");\n var endDate = this.moment(end).endOf(\"year\");\n var years = [];\n var current = startDate;\n while (current.isBefore(endDate)) {\n years.push(current);\n current = current.clone().add(1, \"year\");\n }\n return years;\n };\n // displaying methods\n MomentUtils.prototype.getCalendarHeaderText = function (date) {\n return this.format(date, this.yearMonthFormat);\n };\n MomentUtils.prototype.getYearText = function (date) {\n return this.format(date, \"YYYY\");\n };\n MomentUtils.prototype.getDatePickerHeaderText = function (date) {\n return this.format(date, \"ddd, MMM D\");\n };\n MomentUtils.prototype.getDateTimePickerHeaderText = function (date) {\n return this.format(date, \"MMM D\");\n };\n MomentUtils.prototype.getMonthText = function (date) {\n return this.format(date, \"MMMM\");\n };\n MomentUtils.prototype.getDayText = function (date) {\n return this.format(date, \"D\");\n };\n MomentUtils.prototype.getHourText = function (date, ampm) {\n return this.format(date, ampm ? \"hh\" : \"HH\");\n };\n MomentUtils.prototype.getMinuteText = function (date) {\n return this.format(date, \"mm\");\n };\n MomentUtils.prototype.getSecondText = function (date) {\n return this.format(date, \"ss\");\n };\n return MomentUtils;\n}());\n\nexport default MomentUtils;\n","// https://stackoverflow.com/questions/46176165/ways-to-get-string-literal-type-of-array-values-without-enum-overhead\nexport var tuple = function tuple() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return args;\n};\nexport var tupleNum = function tupleNum() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return args;\n};","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nexport function toArray(value) {\n if (Array.isArray(value)) {\n return value;\n }\n\n return value !== undefined ? [value] : [];\n}\n/**\n * Convert outer props value into internal value\n */\n\nexport function toInnerValue(value, _ref) {\n var labelInValue = _ref.labelInValue,\n combobox = _ref.combobox;\n var valueMap = new Map();\n\n if (value === undefined || value === '' && combobox) {\n return [[], valueMap];\n }\n\n var values = Array.isArray(value) ? value : [value];\n var rawValues = values;\n\n if (labelInValue) {\n rawValues = values.filter(function (item) {\n return item !== null;\n }).map(function (itemValue) {\n var key = itemValue.key,\n val = itemValue.value;\n var finalVal = val !== undefined ? val : key;\n valueMap.set(finalVal, itemValue);\n return finalVal;\n });\n }\n\n return [rawValues, valueMap];\n}\n/**\n * Convert internal value into out event value\n */\n\nexport function toOuterValues(valueList, _ref2) {\n var optionLabelProp = _ref2.optionLabelProp,\n labelInValue = _ref2.labelInValue,\n prevValueMap = _ref2.prevValueMap,\n options = _ref2.options,\n getLabeledValue = _ref2.getLabeledValue;\n var values = valueList;\n\n if (labelInValue) {\n values = values.map(function (val) {\n return getLabeledValue(val, {\n options: options,\n prevValueMap: prevValueMap,\n labelInValue: labelInValue,\n optionLabelProp: optionLabelProp\n });\n });\n }\n\n return values;\n}\nexport function removeLastEnabledValue(measureValues, values) {\n var newValues = _toConsumableArray(values);\n\n var removeIndex;\n\n for (removeIndex = measureValues.length - 1; removeIndex >= 0; removeIndex -= 1) {\n if (!measureValues[removeIndex].disabled) {\n break;\n }\n }\n\n var removedValue = null;\n\n if (removeIndex !== -1) {\n removedValue = newValues[removeIndex];\n newValues.splice(removeIndex, 1);\n }\n\n return {\n values: newValues,\n removedValue: removedValue\n };\n}\nexport var isClient = typeof window !== 'undefined' && window.document && window.document.documentElement;\n/** Is client side and not jsdom */\n\nexport var isBrowserClient = process.env.NODE_ENV !== 'test' && isClient;\nvar uuid = 0;\n/** Get unique id for accessibility usage */\n\nexport function getUUID() {\n var retId; // Test never reach\n\n /* istanbul ignore if */\n\n if (isBrowserClient) {\n retId = uuid;\n uuid += 1;\n } else {\n retId = 'TEST_OR_SSR';\n }\n\n return retId;\n}","export var reflow = function reflow(node) {\n return node.scrollTop;\n};\nexport function getTransitionProps(props, options) {\n var timeout = props.timeout,\n _props$style = props.style,\n style = _props$style === void 0 ? {} : _props$style;\n return {\n duration: style.transitionDuration || typeof timeout === 'number' ? timeout : timeout[options.mode] || 0,\n delay: style.transitionDelay\n };\n}","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import * as React from 'react';\nvar SizeContext = /*#__PURE__*/React.createContext(undefined);\nexport var SizeContextProvider = function SizeContextProvider(_ref) {\n var children = _ref.children,\n size = _ref.size;\n return /*#__PURE__*/React.createElement(SizeContext.Consumer, null, function (originSize) {\n return /*#__PURE__*/React.createElement(SizeContext.Provider, {\n value: size || originSize\n }, children);\n });\n};\nexport default SizeContext;","import toDate from \"../../toDate/index.js\";\nimport requiredArgs from \"../requiredArgs/index.js\";\nimport toInteger from \"../toInteger/index.js\"; // This function will be a part of public API when UTC function will be implemented.\n// See issue: https://github.com/date-fns/date-fns/issues/376\n\nexport default function startOfUTCWeek(dirtyDate, dirtyOptions) {\n requiredArgs(1, arguments);\n var options = dirtyOptions || {};\n var locale = options.locale;\n var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;\n var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);\n var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN\n\n if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {\n throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');\n }\n\n var date = toDate(dirtyDate);\n var day = date.getUTCDay();\n var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;\n date.setUTCDate(date.getUTCDate() - diff);\n date.setUTCHours(0, 0, 0, 0);\n return date;\n}","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\n\nfunction _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\n });\n };\n}\n\nmodule.exports = _asyncToGenerator;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\n\nvar __rest = this && this.__rest || function (s, e) {\n var t = {};\n\n for (var p in s) {\n if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];\n }\n\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];\n }\n return t;\n};\n\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport RowContext from './RowContext';\nimport { ConfigContext } from '../config-provider';\n\nfunction parseFlex(flex) {\n if (typeof flex === 'number') {\n return \"\".concat(flex, \" \").concat(flex, \" auto\");\n }\n\n if (/^\\d+(\\.\\d+)?(px|em|rem|%)$/.test(flex)) {\n return \"0 0 \".concat(flex);\n }\n\n return flex;\n}\n\nvar sizes = ['xs', 'sm', 'md', 'lg', 'xl', 'xxl'];\nvar Col = /*#__PURE__*/React.forwardRef(function (props, ref) {\n var _classNames;\n\n var _React$useContext = React.useContext(ConfigContext),\n getPrefixCls = _React$useContext.getPrefixCls,\n direction = _React$useContext.direction;\n\n var _React$useContext2 = React.useContext(RowContext),\n gutter = _React$useContext2.gutter,\n wrap = _React$useContext2.wrap,\n supportFlexGap = _React$useContext2.supportFlexGap;\n\n var customizePrefixCls = props.prefixCls,\n span = props.span,\n order = props.order,\n offset = props.offset,\n push = props.push,\n pull = props.pull,\n className = props.className,\n children = props.children,\n flex = props.flex,\n style = props.style,\n others = __rest(props, [\"prefixCls\", \"span\", \"order\", \"offset\", \"push\", \"pull\", \"className\", \"children\", \"flex\", \"style\"]);\n\n var prefixCls = getPrefixCls('col', customizePrefixCls);\n var sizeClassObj = {};\n sizes.forEach(function (size) {\n var _extends2;\n\n var sizeProps = {};\n var propSize = props[size];\n\n if (typeof propSize === 'number') {\n sizeProps.span = propSize;\n } else if (_typeof(propSize) === 'object') {\n sizeProps = propSize || {};\n }\n\n delete others[size];\n sizeClassObj = _extends(_extends({}, sizeClassObj), (_extends2 = {}, _defineProperty(_extends2, \"\".concat(prefixCls, \"-\").concat(size, \"-\").concat(sizeProps.span), sizeProps.span !== undefined), _defineProperty(_extends2, \"\".concat(prefixCls, \"-\").concat(size, \"-order-\").concat(sizeProps.order), sizeProps.order || sizeProps.order === 0), _defineProperty(_extends2, \"\".concat(prefixCls, \"-\").concat(size, \"-offset-\").concat(sizeProps.offset), sizeProps.offset || sizeProps.offset === 0), _defineProperty(_extends2, \"\".concat(prefixCls, \"-\").concat(size, \"-push-\").concat(sizeProps.push), sizeProps.push || sizeProps.push === 0), _defineProperty(_extends2, \"\".concat(prefixCls, \"-\").concat(size, \"-pull-\").concat(sizeProps.pull), sizeProps.pull || sizeProps.pull === 0), _defineProperty(_extends2, \"\".concat(prefixCls, \"-rtl\"), direction === 'rtl'), _extends2));\n });\n var classes = classNames(prefixCls, (_classNames = {}, _defineProperty(_classNames, \"\".concat(prefixCls, \"-\").concat(span), span !== undefined), _defineProperty(_classNames, \"\".concat(prefixCls, \"-order-\").concat(order), order), _defineProperty(_classNames, \"\".concat(prefixCls, \"-offset-\").concat(offset), offset), _defineProperty(_classNames, \"\".concat(prefixCls, \"-push-\").concat(push), push), _defineProperty(_classNames, \"\".concat(prefixCls, \"-pull-\").concat(pull), pull), _classNames), className, sizeClassObj);\n var mergedStyle = {}; // Horizontal gutter use padding\n\n if (gutter && gutter[0] > 0) {\n var horizontalGutter = gutter[0] / 2;\n mergedStyle.paddingLeft = horizontalGutter;\n mergedStyle.paddingRight = horizontalGutter;\n } // Vertical gutter use padding when gap not support\n\n\n if (gutter && gutter[1] > 0 && !supportFlexGap) {\n var verticalGutter = gutter[1] / 2;\n mergedStyle.paddingTop = verticalGutter;\n mergedStyle.paddingBottom = verticalGutter;\n }\n\n if (flex) {\n mergedStyle.flex = parseFlex(flex); // Hack for Firefox to avoid size issue\n // https://github.com/ant-design/ant-design/pull/20023#issuecomment-564389553\n\n if (flex === 'auto' && wrap === false && !mergedStyle.minWidth) {\n mergedStyle.minWidth = 0;\n }\n }\n\n return /*#__PURE__*/React.createElement(\"div\", _extends({}, others, {\n style: _extends(_extends({}, mergedStyle), style),\n className: classes,\n ref: ref\n }), children);\n});\nCol.displayName = 'Col';\nexport default Col;","import { Col } from '../grid';\nexport default Col;","export default function deprecatedPropType(validator, reason) {\n if (process.env.NODE_ENV === 'production') {\n return function () {\n return null;\n };\n }\n\n return function (props, propName, componentName, location, propFullName) {\n var componentNameSafe = componentName || '<>';\n var propFullNameSafe = propFullName || propName;\n\n if (typeof props[propName] !== 'undefined') {\n return new Error(\"The \".concat(location, \" `\").concat(propFullNameSafe, \"` of \") + \"`\".concat(componentNameSafe, \"` is deprecated. \").concat(reason));\n }\n\n return null;\n };\n}","\"use strict\";\n\nvar _interopRequireWildcard = require(\"@babel/runtime/helpers/interopRequireWildcard\");\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _slicedToArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/slicedToArray\"));\n\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\nvar React = _interopRequireWildcard(require(\"react\"));\n\nvar _classnames = _interopRequireDefault(require(\"classnames\"));\n\nvar _Context = _interopRequireDefault(require(\"./Context\"));\n\nvar _IconBase = _interopRequireDefault(require(\"./IconBase\"));\n\nvar _twoTonePrimaryColor = require(\"./twoTonePrimaryColor\");\n\nvar _utils = require(\"../utils\");\n\n// Initial setting\n// should move it to antd main repo?\n(0, _twoTonePrimaryColor.setTwoToneColor)('#1890ff');\nvar Icon = /*#__PURE__*/React.forwardRef(function (props, ref) {\n var _classNames;\n\n var className = props.className,\n icon = props.icon,\n spin = props.spin,\n rotate = props.rotate,\n tabIndex = props.tabIndex,\n onClick = props.onClick,\n twoToneColor = props.twoToneColor,\n restProps = (0, _objectWithoutProperties2.default)(props, [\"className\", \"icon\", \"spin\", \"rotate\", \"tabIndex\", \"onClick\", \"twoToneColor\"]);\n\n var _React$useContext = React.useContext(_Context.default),\n _React$useContext$pre = _React$useContext.prefixCls,\n prefixCls = _React$useContext$pre === void 0 ? 'anticon' : _React$useContext$pre;\n\n var classString = (0, _classnames.default)(prefixCls, (_classNames = {}, (0, _defineProperty2.default)(_classNames, \"\".concat(prefixCls, \"-\").concat(icon.name), !!icon.name), (0, _defineProperty2.default)(_classNames, \"\".concat(prefixCls, \"-spin\"), !!spin || icon.name === 'loading'), _classNames), className);\n var iconTabIndex = tabIndex;\n\n if (iconTabIndex === undefined && onClick) {\n iconTabIndex = -1;\n }\n\n var svgStyle = rotate ? {\n msTransform: \"rotate(\".concat(rotate, \"deg)\"),\n transform: \"rotate(\".concat(rotate, \"deg)\")\n } : undefined;\n\n var _normalizeTwoToneColo = (0, _utils.normalizeTwoToneColors)(twoToneColor),\n _normalizeTwoToneColo2 = (0, _slicedToArray2.default)(_normalizeTwoToneColo, 2),\n primaryColor = _normalizeTwoToneColo2[0],\n secondaryColor = _normalizeTwoToneColo2[1];\n\n return /*#__PURE__*/React.createElement(\"span\", Object.assign({\n role: \"img\",\n \"aria-label\": icon.name\n }, restProps, {\n ref: ref,\n tabIndex: iconTabIndex,\n onClick: onClick,\n className: classString\n }), /*#__PURE__*/React.createElement(_IconBase.default, {\n icon: icon,\n primaryColor: primaryColor,\n secondaryColor: secondaryColor,\n style: svgStyle\n }));\n});\nIcon.displayName = 'AntdIcon';\nIcon.getTwoToneColor = _twoTonePrimaryColor.getTwoToneColor;\nIcon.setTwoToneColor = _twoTonePrimaryColor.setTwoToneColor;\nvar _default = Icon;\nexports.default = _default;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","// TODO v5: consider to make it private\nexport default function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}","var Class = function Class () {};\n\nexport default Class;\n","var UNDEFINED = \"undefined\";\n\nexport default function defined(value) {\n return typeof value !== UNDEFINED;\n}","var DEG_TO_RAD = Math.PI / 180;\nvar MAX_NUM = Number.MAX_VALUE;\nvar MIN_NUM = -Number.MAX_VALUE;\n\nexport { DEG_TO_RAD, MAX_NUM, MIN_NUM };","import { DEG_TO_RAD } from './constants';\n\nexport default function rad(degrees) {\n return degrees * DEG_TO_RAD;\n}\n","function pow(p) {\n if (p) {\n return Math.pow(10, p);\n }\n\n return 1;\n}\n\nexport default function round(value, precision) {\n var power = pow(precision);\n return Math.round(value * power) / power;\n}","import { Class } from '../common';\nimport defined from '../util/defined';\nimport rad from '../util/rad';\nimport round from '../util/round';\n\nvar Matrix = (function (Class) {\n function Matrix(a, b, c, d, e, f) {\n if ( a === void 0 ) a = 0;\n if ( b === void 0 ) b = 0;\n if ( c === void 0 ) c = 0;\n if ( d === void 0 ) d = 0;\n if ( e === void 0 ) e = 0;\n if ( f === void 0 ) f = 0;\n\n Class.call(this);\n\n this.a = a;\n this.b = b;\n this.c = c;\n this.d = d;\n this.e = e;\n this.f = f;\n }\n\n if ( Class ) Matrix.__proto__ = Class;\n Matrix.prototype = Object.create( Class && Class.prototype );\n Matrix.prototype.constructor = Matrix;\n\n Matrix.prototype.multiplyCopy = function multiplyCopy (matrix) {\n return new Matrix(\n this.a * matrix.a + this.c * matrix.b,\n this.b * matrix.a + this.d * matrix.b,\n this.a * matrix.c + this.c * matrix.d,\n this.b * matrix.c + this.d * matrix.d,\n this.a * matrix.e + this.c * matrix.f + this.e,\n this.b * matrix.e + this.d * matrix.f + this.f\n );\n };\n\n Matrix.prototype.invert = function invert () {\n var ref = this;\n var a = ref.a;\n var b = ref.b;\n var d = ref.c;\n var e = ref.d;\n var g = ref.e;\n var h = ref.f;\n var det = a * e - b * d;\n\n if (det === 0) {\n return null;\n }\n\n return new Matrix(e / det, -b / det, -d / det, a / det,\n (d * h - e * g) / det, (b * g - a * h) / det);\n };\n\n Matrix.prototype.clone = function clone () {\n return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);\n };\n\n Matrix.prototype.equals = function equals (other) {\n if (!other) {\n return false;\n }\n\n return this.a === other.a && this.b === other.b &&\n this.c === other.c && this.d === other.d &&\n this.e === other.e && this.f === other.f;\n };\n\n Matrix.prototype.round = function round$1 (precision) {\n this.a = round(this.a, precision);\n this.b = round(this.b, precision);\n this.c = round(this.c, precision);\n this.d = round(this.d, precision);\n this.e = round(this.e, precision);\n this.f = round(this.f, precision);\n\n return this;\n };\n\n Matrix.prototype.toArray = function toArray (precision) {\n var result = [ this.a, this.b, this.c, this.d, this.e, this.f ];\n\n if (defined(precision)) {\n for (var i = 0; i < result.length; i++) {\n result[i] = round(result[i], precision);\n }\n }\n\n return result;\n };\n\n Matrix.prototype.toString = function toString (precision, separator) {\n if ( separator === void 0 ) separator = \",\";\n\n return this.toArray(precision).join(separator);\n };\n\n Matrix.translate = function translate (x, y) {\n return new Matrix(1, 0, 0, 1, x, y);\n };\n\n Matrix.unit = function unit () {\n return new Matrix(1, 0, 0, 1, 0, 0);\n };\n\n Matrix.rotate = function rotate (angle, x, y) {\n var matrix = new Matrix();\n matrix.a = Math.cos(rad(angle));\n matrix.b = Math.sin(rad(angle));\n matrix.c = -matrix.b;\n matrix.d = matrix.a;\n matrix.e = (x - x * matrix.a + y * matrix.b) || 0;\n matrix.f = (y - y * matrix.a - x * matrix.b) || 0;\n\n return matrix;\n };\n\n Matrix.scale = function scale (scaleX, scaleY) {\n return new Matrix(scaleX, 0, 0, scaleY, 0, 0);\n };\n\n return Matrix;\n}(Class));\n\nMatrix.IDENTITY = Matrix.unit();\n\nexport default Matrix;\n","import { Class } from '../common';\n\nvar HasObservers = (function (Class) {\n function HasObservers () {\n Class.apply(this, arguments);\n }\n\n if ( Class ) HasObservers.__proto__ = Class;\n HasObservers.prototype = Object.create( Class && Class.prototype );\n HasObservers.prototype.constructor = HasObservers;\n\n HasObservers.prototype.observers = function observers () {\n this._observers = this._observers || [];\n return this._observers;\n };\n\n HasObservers.prototype.addObserver = function addObserver (element) {\n if (!this._observers) {\n this._observers = [ element ];\n } else {\n this._observers.push(element);\n }\n return this;\n };\n\n HasObservers.prototype.removeObserver = function removeObserver (element) {\n var observers = this.observers();\n var index = observers.indexOf(element);\n if (index !== -1) {\n observers.splice(index, 1);\n }\n return this;\n };\n\n HasObservers.prototype.trigger = function trigger (methodName, event) {\n var observers = this._observers;\n\n if (observers && !this._suspended) {\n for (var idx = 0; idx < observers.length; idx++) {\n var observer = observers[idx];\n if (observer[methodName]) {\n observer[methodName](event);\n }\n }\n }\n return this;\n };\n\n HasObservers.prototype.optionsChange = function optionsChange (e) {\n if ( e === void 0 ) e = {};\n\n e.element = this;\n this.trigger(\"optionsChange\", e);\n };\n\n HasObservers.prototype.geometryChange = function geometryChange () {\n this.trigger(\"geometryChange\", {\n element: this\n });\n };\n\n HasObservers.prototype.suspend = function suspend () {\n this._suspended = (this._suspended || 0) + 1;\n return this;\n };\n\n HasObservers.prototype.resume = function resume () {\n this._suspended = Math.max((this._suspended || 0) - 1, 0);\n return this;\n };\n\n HasObservers.prototype._observerField = function _observerField (field, value) {\n if (this[field]) {\n this[field].removeObserver(this);\n }\n this[field] = value;\n value.addObserver(this);\n };\n\n return HasObservers;\n}(Class));\n\nexport default HasObservers;\n\n","function setAccessor(field) {\n return function(value) {\n if (this[field] !== value) {\n this[field] = value;\n this.geometryChange();\n }\n\n return this;\n };\n}\n\nfunction getAccessor(field) {\n return function() {\n return this[field];\n };\n}\n\nfunction defineAccessors(fn, fields) {\n for (var i = 0; i < fields.length; i++) {\n var name = fields[i];\n var capitalized = name.charAt(0).toUpperCase() +\n name.substring(1, name.length);\n\n fn[\"set\" + capitalized] = setAccessor(name);\n fn[\"get\" + capitalized] = getAccessor(name);\n }\n}\n\nvar withAccessors = function (TBase, names) {\n var result = (function (TBase) {\n function result () {\n TBase.apply(this, arguments);\n }if ( TBase ) result.__proto__ = TBase;\n result.prototype = Object.create( TBase && TBase.prototype );\n result.prototype.constructor = result;\n\n \n\n return result;\n }(TBase));\n defineAccessors(result.prototype, names);\n\n return result;\n};\n\nexport default withAccessors;\n","export default function toMatrix(transformation) {\n if (transformation && typeof transformation.matrix === \"function\") {\n return transformation.matrix();\n }\n\n return transformation;\n}","import withAccessors from '../mixins/with-accessors';\nimport HasObservers from '../core/has-observers';\nimport { defined, MIN_NUM, MAX_NUM, round } from '../util';\nimport Matrix from './matrix';\nimport toMatrix from './to-matrix';\n\n\nvar Point = (function (superclass) {\n function Point(x, y) {\n superclass.call(this);\n\n this.x = x || 0;\n this.y = y || 0;\n }\n\n if ( superclass ) Point.__proto__ = superclass;\n Point.prototype = Object.create( superclass && superclass.prototype );\n Point.prototype.constructor = Point;\n\n var staticAccessors = { ZERO: { configurable: true } };\n\n Point.prototype.equals = function equals (other) {\n return other && other.x === this.x && other.y === this.y;\n };\n\n Point.prototype.clone = function clone () {\n return new Point(this.x, this.y);\n };\n\n Point.prototype.rotate = function rotate (angle, origin) {\n var originPoint = Point.create(origin) || Point.ZERO;\n\n return this.transform(Matrix.rotate(angle, originPoint.x, originPoint.y));\n };\n\n Point.prototype.translate = function translate (x, y) {\n this.x += x;\n this.y += y;\n\n this.geometryChange();\n\n return this;\n };\n\n Point.prototype.translateWith = function translateWith (point) {\n return this.translate(point.x, point.y);\n };\n\n Point.prototype.move = function move (x, y) {\n this.x = this.y = 0;\n return this.translate(x, y);\n };\n\n Point.prototype.scale = function scale (scaleX, scaleY) {\n if ( scaleY === void 0 ) scaleY = scaleX;\n\n this.x *= scaleX;\n this.y *= scaleY;\n\n this.geometryChange();\n\n return this;\n };\n\n Point.prototype.scaleCopy = function scaleCopy (scaleX, scaleY) {\n return this.clone().scale(scaleX, scaleY);\n };\n\n Point.prototype.transform = function transform (transformation) {\n var matrix = toMatrix(transformation);\n var ref = this;\n var x = ref.x;\n var y = ref.y;\n\n this.x = matrix.a * x + matrix.c * y + matrix.e;\n this.y = matrix.b * x + matrix.d * y + matrix.f;\n\n this.geometryChange();\n\n return this;\n };\n\n Point.prototype.transformCopy = function transformCopy (transformation) {\n var point = this.clone();\n\n if (transformation) {\n point.transform(transformation);\n }\n\n return point;\n };\n\n Point.prototype.distanceTo = function distanceTo (point) {\n var dx = this.x - point.x;\n var dy = this.y - point.y;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n\n Point.prototype.round = function round$1 (digits) {\n this.x = round(this.x, digits);\n this.y = round(this.y, digits);\n\n this.geometryChange();\n\n return this;\n };\n\n Point.prototype.toArray = function toArray (digits) {\n var doRound = defined(digits);\n var x = doRound ? round(this.x, digits) : this.x;\n var y = doRound ? round(this.y, digits) : this.y;\n\n return [ x, y ];\n };\n\n Point.prototype.toString = function toString (digits, separator) {\n if ( separator === void 0 ) separator = \" \";\n\n var ref = this;\n var x = ref.x;\n var y = ref.y;\n\n if (defined(digits)) {\n x = round(x, digits);\n y = round(y, digits);\n }\n\n return x + separator + y;\n };\n\n Point.create = function create (arg0, arg1) {\n if (defined(arg0)) {\n if (arg0 instanceof Point) {\n return arg0;\n } else if (arguments.length === 1 && arg0.length === 2) {\n return new Point(arg0[0], arg0[1]);\n }\n\n return new Point(arg0, arg1);\n }\n };\n\n Point.min = function min () {\n var arguments$1 = arguments;\n\n var minX = MAX_NUM;\n var minY = MAX_NUM;\n\n for (var i = 0; i < arguments.length; i++) {\n var point = arguments$1[i];\n minX = Math.min(point.x, minX);\n minY = Math.min(point.y, minY);\n }\n\n return new Point(minX, minY);\n };\n\n Point.max = function max () {\n var arguments$1 = arguments;\n\n var maxX = MIN_NUM;\n var maxY = MIN_NUM;\n\n for (var i = 0; i < arguments.length; i++) {\n var point = arguments$1[i];\n maxX = Math.max(point.x, maxX);\n maxY = Math.max(point.y, maxY);\n }\n\n return new Point(maxX, maxY);\n };\n\n Point.minPoint = function minPoint () {\n return new Point(MIN_NUM, MIN_NUM);\n };\n\n Point.maxPoint = function maxPoint () {\n return new Point(MAX_NUM, MAX_NUM);\n };\n\n staticAccessors.ZERO.get = function () {\n return new Point(0, 0);\n };\n\n Object.defineProperties( Point, staticAccessors );\n\n return Point;\n}(withAccessors(HasObservers, [ \"x\", \"y\" ])));\n\nexport default Point;\n","import HasObservers from '../core/has-observers';\nimport withAccessors from '../mixins/with-accessors';\nimport { defined, round } from '../util';\n\n\nvar Size = (function (superclass) {\n function Size(width, height) {\n superclass.call(this);\n\n this.width = width || 0;\n this.height = height || 0;\n }\n\n if ( superclass ) Size.__proto__ = superclass;\n Size.prototype = Object.create( superclass && superclass.prototype );\n Size.prototype.constructor = Size;\n\n var staticAccessors = { ZERO: { configurable: true } };\n\n Size.prototype.equals = function equals (other) {\n return other && other.width === this.width && other.height === this.height;\n };\n\n Size.prototype.clone = function clone () {\n return new Size(this.width, this.height);\n };\n\n Size.prototype.toArray = function toArray (digits) {\n var doRound = defined(digits);\n var width = doRound ? round(this.width, digits) : this.width;\n var height = doRound ? round(this.height, digits) : this.height;\n\n return [ width, height ];\n };\n\n Size.create = function create (arg0, arg1) {\n if (defined(arg0)) {\n if (arg0 instanceof Size) {\n return arg0;\n } else if (arguments.length === 1 && arg0.length === 2) {\n return new Size(arg0[0], arg0[1]);\n }\n\n return new Size(arg0, arg1);\n }\n };\n\n staticAccessors.ZERO.get = function () {\n return new Size(0, 0);\n };\n\n Object.defineProperties( Size, staticAccessors );\n\n return Size;\n}(withAccessors(HasObservers, [ \"width\", \"height\" ])));\n\nexport default Size;\n","import HasObservers from '../core/has-observers';\nimport Point from './point';\nimport Size from './size';\n\nvar Rect = (function (HasObservers) {\n function Rect(origin, size, cornerRadius) {\n if ( origin === void 0 ) origin = new Point();\n if ( size === void 0 ) size = new Size();\n if ( cornerRadius === void 0 ) cornerRadius = 0;\n\n HasObservers.call(this);\n\n this.setOrigin(origin);\n this.setSize(size);\n this.setCornerRadius(cornerRadius);\n }\n\n if ( HasObservers ) Rect.__proto__ = HasObservers;\n Rect.prototype = Object.create( HasObservers && HasObservers.prototype );\n Rect.prototype.constructor = Rect;\n\n Rect.prototype.clone = function clone () {\n return new Rect(\n this.origin.clone(),\n this.size.clone()\n );\n };\n\n Rect.prototype.equals = function equals (other) {\n return other &&\n other.origin.equals(this.origin) &&\n other.size.equals(this.size);\n };\n\n Rect.prototype.setOrigin = function setOrigin (value) {\n this._observerField(\"origin\", Point.create(value));\n this.geometryChange();\n return this;\n };\n\n Rect.prototype.getOrigin = function getOrigin () {\n return this.origin;\n };\n\n Rect.prototype.setCornerRadius = function setCornerRadius (radius) {\n this.cornerRadius = Array.isArray(radius) ? radius : [ radius, radius ];\n\n this.geometryChange();\n return this;\n };\n\n Rect.prototype.getCornerRadius = function getCornerRadius () {\n return this.cornerRadius;\n };\n\n Rect.prototype.setSize = function setSize (value) {\n this._observerField(\"size\", Size.create(value));\n this.geometryChange();\n return this;\n };\n\n Rect.prototype.getSize = function getSize () {\n return this.size;\n };\n\n Rect.prototype.width = function width () {\n return this.size.width;\n };\n\n Rect.prototype.height = function height () {\n return this.size.height;\n };\n\n Rect.prototype.topLeft = function topLeft () {\n return this.origin.clone();\n };\n\n Rect.prototype.bottomRight = function bottomRight () {\n return this.origin.clone().translate(this.width(), this.height());\n };\n\n Rect.prototype.topRight = function topRight () {\n return this.origin.clone().translate(this.width(), 0);\n };\n\n Rect.prototype.bottomLeft = function bottomLeft () {\n return this.origin.clone().translate(0, this.height());\n };\n\n Rect.prototype.center = function center () {\n return this.origin.clone().translate(this.width() / 2, this.height() / 2);\n };\n\n Rect.prototype.bbox = function bbox (matrix) {\n var tl = this.topLeft().transformCopy(matrix);\n var tr = this.topRight().transformCopy(matrix);\n var br = this.bottomRight().transformCopy(matrix);\n var bl = this.bottomLeft().transformCopy(matrix);\n\n return Rect.fromPoints(tl, tr, br, bl);\n };\n\n Rect.prototype.transformCopy = function transformCopy (m) {\n return Rect.fromPoints(\n this.topLeft().transform(m),\n this.bottomRight().transform(m)\n );\n };\n\n Rect.prototype.expand = function expand (x, y) {\n if ( y === void 0 ) y = x;\n\n\n this.size.width += 2 * x;\n this.size.height += 2 * y;\n\n this.origin.translate(-x, -y);\n\n return this;\n };\n\n Rect.prototype.expandCopy = function expandCopy (x, y) {\n return this.clone().expand(x, y);\n };\n\n Rect.prototype.containsPoint = function containsPoint (point) {\n var origin = this.origin;\n var bottomRight = this.bottomRight();\n return !(point.x < origin.x || point.y < origin.y || bottomRight.x < point.x || bottomRight.y < point.y);\n };\n\n Rect.prototype._isOnPath = function _isOnPath (point, width) {\n var rectOuter = this.expandCopy(width, width);\n var rectInner = this.expandCopy(-width, -width);\n\n return rectOuter.containsPoint(point) && !rectInner.containsPoint(point);\n };\n\n Rect.fromPoints = function fromPoints () {\n var topLeft = Point.min.apply(null, arguments);\n var bottomRight = Point.max.apply(null, arguments);\n var size = new Size(\n bottomRight.x - topLeft.x,\n bottomRight.y - topLeft.y\n );\n\n return new Rect(topLeft, size);\n };\n\n Rect.union = function union (a, b) {\n return Rect.fromPoints(\n Point.min(a.topLeft(), b.topLeft()),\n Point.max(a.bottomRight(), b.bottomRight())\n );\n };\n\n Rect.intersect = function intersect (a, b) {\n var rect1 = {\n left: a.topLeft().x,\n top: a.topLeft().y,\n right: a.bottomRight().x,\n bottom: a.bottomRight().y\n };\n\n var rect2 = {\n left: b.topLeft().x,\n top: b.topLeft().y,\n right: b.bottomRight().x,\n bottom: b.bottomRight().y\n };\n\n if (rect1.left <= rect2.right &&\n rect2.left <= rect1.right &&\n rect1.top <= rect2.bottom &&\n rect2.top <= rect1.bottom) {\n return Rect.fromPoints(\n new Point(Math.max(rect1.left, rect2.left), Math.max(rect1.top, rect2.top)),\n new Point(Math.min(rect1.right, rect2.right), Math.min(rect1.bottom, rect2.bottom))\n );\n }\n };\n\n return Rect;\n}(HasObservers));\n\nexport default Rect;\n","import { DEG_TO_RAD } from './constants';\n\nexport default function deg(radians) {\n return radians / DEG_TO_RAD;\n}","var PRECISION = 10;\n\nexport { PRECISION };","import { PRECISION } from '../constants';\n\nimport { round } from '../../util';\n\nexport default function close(a, b, tolerance) {\n if ( tolerance === void 0 ) tolerance = PRECISION;\n\n return round(Math.abs(a - b), tolerance) === 0;\n}","import close from './close';\n\nexport default function closeOrLess(a, b, tolerance) {\n return a < b || close(a, b, tolerance);\n}","export default function ellipseExtremeAngles(center, rx, ry, matrix) {\n var extremeX = 0;\n var extremeY = 0;\n\n if (matrix) {\n extremeX = Math.atan2(matrix.c * ry, matrix.a * rx);\n if (matrix.b !== 0) {\n extremeY = Math.atan2(matrix.d * ry, matrix.b * rx);\n }\n }\n\n return {\n x: extremeX,\n y: extremeY\n };\n}","import HasObservers from '../core/has-observers';\nimport toMatrix from './to-matrix';\nimport Matrix from './matrix';\nimport Point from './point';\n\nvar Transformation = (function (HasObservers) {\n function Transformation(matrix) {\n if ( matrix === void 0 ) matrix = Matrix.unit();\n\n HasObservers.call(this);\n\n this._matrix = matrix;\n }\n\n if ( HasObservers ) Transformation.__proto__ = HasObservers;\n Transformation.prototype = Object.create( HasObservers && HasObservers.prototype );\n Transformation.prototype.constructor = Transformation;\n\n Transformation.prototype.clone = function clone () {\n return new Transformation(\n this._matrix.clone()\n );\n };\n\n Transformation.prototype.equals = function equals (other) {\n return other &&\n other._matrix.equals(this._matrix);\n };\n\n Transformation.prototype.translate = function translate (x, y) {\n this._matrix = this._matrix.multiplyCopy(Matrix.translate(x, y));\n\n this._optionsChange();\n return this;\n };\n\n Transformation.prototype.scale = function scale (scaleX, scaleY, origin) {\n if ( scaleY === void 0 ) scaleY = scaleX;\n if ( origin === void 0 ) origin = null;\n\n var originPoint = origin;\n\n if (originPoint) {\n originPoint = Point.create(originPoint);\n this._matrix = this._matrix.multiplyCopy(Matrix.translate(originPoint.x, originPoint.y));\n }\n\n this._matrix = this._matrix.multiplyCopy(Matrix.scale(scaleX, scaleY));\n\n if (originPoint) {\n this._matrix = this._matrix.multiplyCopy(Matrix.translate(-originPoint.x, -originPoint.y));\n }\n\n this._optionsChange();\n return this;\n };\n\n Transformation.prototype.rotate = function rotate (angle, origin) {\n var originPoint = Point.create(origin) || Point.ZERO;\n\n this._matrix = this._matrix.multiplyCopy(Matrix.rotate(angle, originPoint.x, originPoint.y));\n\n this._optionsChange();\n return this;\n };\n\n Transformation.prototype.multiply = function multiply (transformation) {\n var matrix = toMatrix(transformation);\n\n this._matrix = this._matrix.multiplyCopy(matrix);\n\n this._optionsChange();\n return this;\n };\n\n Transformation.prototype.matrix = function matrix (value) {\n if (value) {\n this._matrix = value;\n this._optionsChange();\n return this;\n }\n\n return this._matrix;\n };\n\n Transformation.prototype._optionsChange = function _optionsChange () {\n this.optionsChange({\n field: \"transform\",\n value: this\n });\n };\n\n return Transformation;\n}(HasObservers));\n\nexport default Transformation;\n","import Transformation from './transformation';\n\nexport default function transform(matrix) {\n if (matrix === null) {\n return null;\n }\n\n if (matrix instanceof Transformation) {\n return matrix;\n }\n\n return new Transformation(matrix);\n}","import HasObservers from '../core/has-observers';\nimport { deg, rad, round } from '../util';\nimport withAccessors from '../mixins/with-accessors';\n\nimport closeOrLess from './math/close-or-less';\nimport lineIntersection from './math/line-intersection';\nimport ellipseExtremeAngles from './math/ellipse-extreme-angles';\n\nimport { PRECISION } from './constants';\nimport Point from './point';\nimport Rect from './rect';\nimport transform from './transform';\n\n\nvar MAX_INTERVAL = 45;\nvar pow = Math.pow;\nvar accessors = [ \"radiusX\", \"radiusY\", \"startAngle\", \"endAngle\", \"anticlockwise\" ];\n\nvar Arc = (function (superclass) {\n function Arc(center, options) {\n if ( center === void 0 ) center = new Point();\n if ( options === void 0 ) options = {};\n\n superclass.call(this);\n\n this.setCenter(center);\n\n this.radiusX = options.radiusX;\n this.radiusY = options.radiusY || options.radiusX;\n this.startAngle = options.startAngle;\n this.endAngle = options.endAngle;\n this.anticlockwise = options.anticlockwise || false;\n this.xRotation = options.xRotation;\n }\n\n if ( superclass ) Arc.__proto__ = superclass;\n Arc.prototype = Object.create( superclass && superclass.prototype );\n Arc.prototype.constructor = Arc;\n\n Arc.prototype.clone = function clone () {\n return new Arc(this.center, {\n radiusX: this.radiusX,\n radiusY: this.radiusY,\n startAngle: this.startAngle,\n endAngle: this.endAngle,\n anticlockwise: this.anticlockwise\n });\n };\n\n Arc.prototype.setCenter = function setCenter (value) {\n this._observerField(\"center\", Point.create(value));\n this.geometryChange();\n return this;\n };\n\n Arc.prototype.getCenter = function getCenter () {\n return this.center;\n };\n\n Arc.prototype.pointAt = function pointAt (angle) {\n var center = this.center;\n var radian = rad(angle);\n\n return new Point(\n center.x + this.radiusX * Math.cos(radian),\n center.y + this.radiusY * Math.sin(radian)\n );\n };\n\n Arc.prototype.curvePoints = function curvePoints () {\n var this$1 = this;\n\n var startAngle = this.startAngle;\n var dir = this.anticlockwise ? -1 : 1;\n var curvePoints = [ this.pointAt(startAngle) ];\n var interval = this._arcInterval();\n var intervalAngle = interval.endAngle - interval.startAngle;\n var subIntervalsCount = Math.ceil(intervalAngle / MAX_INTERVAL);\n var subIntervalAngle = intervalAngle / subIntervalsCount;\n var currentAngle = startAngle;\n var transformation;\n if (this.xRotation) {\n transformation = transform().rotate(this.xRotation, this.center);\n }\n\n for (var i = 1; i <= subIntervalsCount; i++) {\n var nextAngle = currentAngle + dir * subIntervalAngle;\n var points = this$1._intervalCurvePoints(currentAngle, nextAngle, transformation);\n\n curvePoints.push(points.cp1, points.cp2, points.p2);\n currentAngle = nextAngle;\n }\n\n return curvePoints;\n };\n\n Arc.prototype.bbox = function bbox (matrix) {\n var this$1 = this;\n\n var interval = this._arcInterval();\n var startAngle = interval.startAngle;\n var endAngle = interval.endAngle;\n var extremeAngles = ellipseExtremeAngles(this.center, this.radiusX, this.radiusY, matrix);\n var extremeX = deg(extremeAngles.x);\n var extremeY = deg(extremeAngles.y);\n var endPoint = this.pointAt(endAngle).transformCopy(matrix);\n var currentAngleX = bboxStartAngle(extremeX, startAngle);\n var currentAngleY = bboxStartAngle(extremeY, startAngle);\n var currentPoint = this.pointAt(startAngle).transformCopy(matrix);\n var minPoint = Point.min(currentPoint, endPoint);\n var maxPoint = Point.max(currentPoint, endPoint);\n\n while (currentAngleX < endAngle || currentAngleY < endAngle) {\n var currentPointX = (void 0);\n if (currentAngleX < endAngle) {\n currentPointX = this$1.pointAt(currentAngleX).transformCopy(matrix);\n currentAngleX += 90;\n }\n\n var currentPointY = (void 0);\n if (currentAngleY < endAngle) {\n currentPointY = this$1.pointAt(currentAngleY).transformCopy(matrix);\n currentAngleY += 90;\n }\n\n currentPoint = new Point(currentPointX.x, currentPointY.y);\n minPoint = Point.min(minPoint, currentPoint);\n maxPoint = Point.max(maxPoint, currentPoint);\n }\n\n return Rect.fromPoints(minPoint, maxPoint);\n };\n\n Arc.prototype._arcInterval = function _arcInterval () {\n var ref = this;\n var startAngle = ref.startAngle;\n var endAngle = ref.endAngle;\n var anticlockwise = ref.anticlockwise;\n\n if (anticlockwise) {\n var oldStart = startAngle;\n startAngle = endAngle;\n endAngle = oldStart;\n }\n\n if (startAngle > endAngle || (anticlockwise && startAngle === endAngle)) {\n endAngle += 360;\n }\n\n return {\n startAngle: startAngle,\n endAngle: endAngle\n };\n };\n\n Arc.prototype._intervalCurvePoints = function _intervalCurvePoints (startAngle, endAngle, transformation) {\n var p1 = this.pointAt(startAngle);\n var p2 = this.pointAt(endAngle);\n var p1Derivative = this._derivativeAt(startAngle);\n var p2Derivative = this._derivativeAt(endAngle);\n var t = (rad(endAngle) - rad(startAngle)) / 3;\n var cp1 = new Point(p1.x + t * p1Derivative.x, p1.y + t * p1Derivative.y);\n var cp2 = new Point(p2.x - t * p2Derivative.x, p2.y - t * p2Derivative.y);\n if (transformation) {\n p1.transform(transformation);\n p2.transform(transformation);\n cp1.transform(transformation);\n cp2.transform(transformation);\n }\n\n return {\n p1: p1,\n cp1: cp1,\n cp2: cp2,\n p2: p2\n };\n };\n\n Arc.prototype._derivativeAt = function _derivativeAt (angle) {\n var radian = rad(angle);\n\n return new Point(-this.radiusX * Math.sin(radian), this.radiusY * Math.cos(radian));\n };\n\n Arc.prototype.containsPoint = function containsPoint (point) {\n var interval = this._arcInterval();\n var intervalAngle = interval.endAngle - interval.startAngle;\n var ref = this;\n var center = ref.center;\n var radiusX = ref.radiusX;\n var radiusY = ref.radiusY;\n var distance = center.distanceTo(point);\n var angleRad = Math.atan2(point.y - center.y, point.x - center.x);\n var pointRadius = (radiusX * radiusY) /\n Math.sqrt(pow(radiusX, 2) * pow(Math.sin(angleRad), 2) + pow(radiusY, 2) * pow(Math.cos(angleRad), 2));\n var startPoint = this.pointAt(this.startAngle).round(PRECISION);\n var endPoint = this.pointAt(this.endAngle).round(PRECISION);\n var intersection = lineIntersection(center, point.round(PRECISION), startPoint, endPoint);\n var containsPoint;\n\n if (intervalAngle < 180) {\n containsPoint = intersection && closeOrLess(center.distanceTo(intersection), distance) && closeOrLess(distance, pointRadius);\n } else {\n var angle = calculateAngle(center.x, center.y, radiusX, radiusY, point.x, point.y);\n if (angle !== 360) {\n angle = (360 + angle) % 360;\n }\n\n var inAngleRange = interval.startAngle <= angle && angle <= interval.endAngle;\n containsPoint = (inAngleRange && closeOrLess(distance, pointRadius)) || (!inAngleRange && (!intersection || intersection.equals(point)));\n }\n return containsPoint;\n };\n\n Arc.prototype._isOnPath = function _isOnPath (point, width) {\n var interval = this._arcInterval();\n var center = this.center;\n var angle = calculateAngle(center.x, center.y, this.radiusX, this.radiusY, point.x, point.y);\n if (angle !== 360) {\n angle = (360 + angle) % 360;\n }\n\n var inAngleRange = interval.startAngle <= angle && angle <= interval.endAngle;\n\n return inAngleRange && this.pointAt(angle).distanceTo(point) <= width;\n };\n\n Arc.fromPoints = function fromPoints (start, end, rx, ry, largeArc, swipe, rotation) {// eslint-disable-line max-params\n var arcParameters = normalizeArcParameters({\n x1: start.x,\n y1: start.y,\n x2: end.x,\n y2: end.y,\n rx: rx,\n ry: ry,\n largeArc: largeArc,\n swipe: swipe,\n rotation: rotation\n });\n\n return new Arc(arcParameters.center, {\n startAngle: arcParameters.startAngle,\n endAngle: arcParameters.endAngle,\n radiusX: arcParameters.radiusX,\n radiusY: arcParameters.radiusY,\n xRotation: arcParameters.xRotation,\n anticlockwise: swipe === 0\n });\n };\n\n return Arc;\n}(withAccessors(HasObservers, accessors)));\n\nfunction calculateAngle(cx, cy, rx, ry, x, y) {\n var cos = round((x - cx) / rx, 3);\n var sin = round((y - cy) / ry, 3);\n\n return round(deg(Math.atan2(sin, cos)));\n}\n\nfunction normalizeArcParameters(parameters) {\n var x1 = parameters.x1;\n var y1 = parameters.y1;\n var x2 = parameters.x2;\n var y2 = parameters.y2;\n var rx = parameters.rx;\n var ry = parameters.ry;\n var largeArc = parameters.largeArc;\n var swipe = parameters.swipe;\n var rotation = parameters.rotation; if ( rotation === void 0 ) rotation = 0;\n\n var radians = rad(rotation);\n var cosine = Math.cos(radians);\n var sine = Math.sin(radians);\n\n var xT = cosine * (x1 - x2) / 2 + sine * (y1 - y2) / 2;\n var yT = -sine * (x1 - x2) / 2 + cosine * (y1 - y2) / 2;\n\n var sign = largeArc !== swipe ? 1 : -1;\n\n var xt2 = Math.pow(xT, 2);\n var yt2 = Math.pow(yT, 2);\n var rx2 = Math.pow(rx, 2);\n var ry2 = Math.pow(ry, 2);\n\n var delta = xt2 / rx2 + yt2 / ry2;\n\n if (delta > 1) {\n delta = Math.sqrt(xt2 / rx2 + yt2 / ry2);\n rx = delta * rx;\n rx2 = Math.pow(rx, 2);\n\n ry = delta * ry;\n ry2 = Math.pow(ry, 2);\n }\n\n var constT = sign * Math.sqrt((rx2 * ry2 - rx2 * yt2 - ry2 * xt2) / (rx2 * yt2 + ry2 * xt2));\n // due to rounding errors the value could become NaN even after radii correction\n if (isNaN(constT)) {\n constT = 0;\n }\n\n var cxT = constT * (rx * yT) / ry;\n var cyT = - constT * (ry * xT) / rx;\n\n var cx = cosine * cxT - sine * cyT + (x1 + x2) / 2;\n var cy = sine * cxT + cosine * cyT + (y1 + y2) / 2;\n\n\n var uX = (xT - cxT) / rx;\n var uY = (yT - cyT) / ry;\n var vX = -(xT + cxT) / rx;\n var vY = -(yT + cyT) / ry;\n\n var startAngle = (uY >= 0 ? 1 : -1) * deg(Math.acos(uX / Math.sqrt(uX * uX + uY * uY)));\n\n var angleCosine = round((uX * vX + uY * vY) / (Math.sqrt(uX * uX + uY * uY) * Math.sqrt(vX * vX + vY * vY)), 10);\n var angle = (uX * vY - uY * vX >= 0 ? 1 : -1) * deg(Math.acos(angleCosine));\n\n if (!swipe && angle > 0) {\n angle -= 360;\n }\n\n if (swipe && angle < 0) {\n angle += 360;\n }\n var endAngle = startAngle + angle;\n var signEndAngle = endAngle >= 0 ? 1 : -1;\n endAngle = (Math.abs(endAngle) % 360) * signEndAngle;\n\n return {\n center: new Point(cx, cy),\n startAngle: startAngle,\n endAngle: endAngle,\n radiusX: rx,\n radiusY: ry,\n xRotation: rotation\n };\n}\n\nfunction bboxStartAngle(angle, start) {\n var startAngle = angle;\n\n while (startAngle < start) {\n startAngle += 90;\n }\n\n return startAngle;\n}\n\nexport default Arc;\n","import Point from '../point';\n\nexport default function lineIntersection(p0, p1, p2, p3) {\n var s1x = p1.x - p0.x;\n var s2x = p3.x - p2.x;\n var s1y = p1.y - p0.y;\n var s2y = p3.y - p2.y;\n var nx = p0.x - p2.x;\n var ny = p0.y - p2.y;\n var d = s1x * s2y - s2x * s1y;\n var s = (s1x * ny - s1y * nx) / d;\n var t = (s2x * ny - s2y * nx) / d;\n\n if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {\n return new Point(p0.x + t * s1x, p0.y + t * s1y);\n }\n}","import withAccessors from '../mixins/with-accessors';\nimport Point from './point';\nimport Rect from './rect';\nimport ellipseExtremeAngles from './math/ellipse-extreme-angles';\nimport HasObservers from '../core/has-observers';\nimport { rad } from '../util';\n\n\nvar PI_DIV_2 = Math.PI / 2;\n\nvar Circle = (function (superclass) {\n function Circle(center, radius) {\n if ( center === void 0 ) center = new Point();\n if ( radius === void 0 ) radius = 0;\n\n superclass.call(this);\n\n this.setCenter(center);\n this.setRadius(radius);\n }\n\n if ( superclass ) Circle.__proto__ = superclass;\n Circle.prototype = Object.create( superclass && superclass.prototype );\n Circle.prototype.constructor = Circle;\n\n Circle.prototype.setCenter = function setCenter (value) {\n this._observerField(\"center\", Point.create(value));\n this.geometryChange();\n return this;\n };\n\n Circle.prototype.getCenter = function getCenter () {\n return this.center;\n };\n\n Circle.prototype.equals = function equals (other) {\n return other &&\n other.center.equals(this.center) &&\n other.radius === this.radius;\n };\n\n Circle.prototype.clone = function clone () {\n return new Circle(this.center.clone(), this.radius);\n };\n\n Circle.prototype.pointAt = function pointAt (angle) {\n return this._pointAt(rad(angle));\n };\n\n Circle.prototype.bbox = function bbox (matrix) {\n var this$1 = this;\n\n var extremeAngles = ellipseExtremeAngles(this.center, this.radius, this.radius, matrix);\n var minPoint = Point.maxPoint();\n var maxPoint = Point.minPoint();\n\n for (var i = 0; i < 4; i++) {\n var currentPointX = this$1._pointAt(extremeAngles.x + i * PI_DIV_2).transformCopy(matrix);\n var currentPointY = this$1._pointAt(extremeAngles.y + i * PI_DIV_2).transformCopy(matrix);\n var currentPoint = new Point(currentPointX.x, currentPointY.y);\n\n minPoint = Point.min(minPoint, currentPoint);\n maxPoint = Point.max(maxPoint, currentPoint);\n }\n\n return Rect.fromPoints(minPoint, maxPoint);\n };\n\n Circle.prototype._pointAt = function _pointAt (angle) {\n var ref = this;\n var center = ref.center;\n var radius = ref.radius;\n\n return new Point(\n center.x + radius * Math.cos(angle),\n center.y + radius * Math.sin(angle)\n );\n };\n\n Circle.prototype.containsPoint = function containsPoint (point) {\n var ref = this;\n var center = ref.center;\n var radius = ref.radius;\n var inCircle = Math.pow(point.x - center.x, 2) +\n Math.pow(point.y - center.y, 2) <= Math.pow(radius, 2);\n return inCircle;\n };\n\n Circle.prototype._isOnPath = function _isOnPath (point, width) {\n var ref = this;\n var center = ref.center;\n var radius = ref.radius;\n var pointDistance = center.distanceTo(point);\n\n return radius - width <= pointDistance && pointDistance <= radius + width;\n };\n\n return Circle;\n}(withAccessors(HasObservers, [ \"radius\" ])));\n\nexport default Circle;\n","function matchUserAgent(userAgent) {\n var browserRxs = {\n edge: /(edge)[ \\/]([\\w.]+)/i,\n webkit: /(chrome)[ \\/]([\\w.]+)/i,\n safari: /(webkit)[ \\/]([\\w.]+)/i,\n opera: /(opera)(?:.*version|)[ \\/]([\\w.]+)/i,\n msie: /(msie\\s|trident.*? rv:)([\\w.]+)/i,\n mozilla: /(mozilla)(?:.*? rv:([\\w.]+)|)/i\n };\n\n var browser;\n\n for (var agent in browserRxs) {\n if (browserRxs.hasOwnProperty(agent)) {\n var match = userAgent.match(browserRxs[agent]);\n if (match) {\n browser = {};\n browser[agent] = true;\n browser[match[1].toLowerCase().split(\" \")[0].split(\"/\")[0]] = true;\n browser.version = parseInt(document.documentMode || match[2], 10);\n\n break;\n }\n }\n }\n\n return browser;\n}\n\nvar browser = {};\n\nvar support = {\n get browser() {\n if (typeof window === 'undefined' || browser) {\n return browser;\n }\n\n browser = matchUserAgent(window.navigator.userAgent);\n return browser;\n }\n};\n\nexport default support;\n","import { support } from '../common';\n\n/* eslint-disable no-multi-spaces, key-spacing, indent, camelcase, space-before-blocks, eqeqeq, brace-style */\n/* eslint-disable space-infix-ops, space-before-function-paren, array-bracket-spacing, object-curly-spacing */\n/* eslint-disable no-nested-ternary, max-params, default-case, no-else-return, no-empty */\n/* eslint-disable no-param-reassign, no-var, block-scoped-var */\n\n// XXX: remove this junk (assume `true`) when we no longer have to support IE < 10\n// IE 9 (at least compatibility) reports having Uint8Array but the request response does not contain ArrayBuffer which results in missing table head error\nvar HAS_TYPED_ARRAYS = typeof Uint8Array !== 'undefined' && support.browser && (!support.browser.msie || support.browser.version > 9);\n\nvar BASE64 = (function(){\n var keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n return {\n decode: function(str) {\n var input = str.replace(/[^A-Za-z0-9\\+\\/\\=]/g, \"\"), i = 0, n = input.length, output = [];\n\n while (i < n) {\n var enc1 = keyStr.indexOf(input.charAt(i++));\n var enc2 = keyStr.indexOf(input.charAt(i++));\n var enc3 = keyStr.indexOf(input.charAt(i++));\n var enc4 = keyStr.indexOf(input.charAt(i++));\n\n var chr1 = (enc1 << 2) | (enc2 >>> 4);\n var chr2 = ((enc2 & 15) << 4) | (enc3 >>> 2);\n var chr3 = ((enc3 & 3) << 6) | enc4;\n\n output.push(chr1);\n if (enc3 != 64) {\n output.push(chr2);\n }\n if (enc4 != 64) {\n output.push(chr3);\n }\n }\n\n return output;\n },\n encode: function(bytes) {\n var i = 0, n = bytes.length;\n var output = \"\";\n\n while (i < n) {\n var chr1 = bytes[i++];\n var chr2 = bytes[i++];\n var chr3 = bytes[i++];\n\n var enc1 = chr1 >>> 2;\n var enc2 = ((chr1 & 3) << 4) | (chr2 >>> 4);\n var enc3 = ((chr2 & 15) << 2) | (chr3 >>> 6);\n var enc4 = chr3 & 63;\n\n if (i - n == 2) {\n enc3 = enc4 = 64;\n } else if (i - n == 1) {\n enc4 = 64;\n }\n\n output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);\n }\n return output;\n }\n };\n}());\n\nfunction BinaryStream(data) {\n var offset = 0, length = 0;\n if (data == null) {\n data = HAS_TYPED_ARRAYS ? new Uint8Array(256) : [];\n } else {\n length = data.length;\n }\n\n var ensure = HAS_TYPED_ARRAYS ? function(len) {\n if (len >= data.length) {\n var tmp = new Uint8Array(Math.max(len + 256, data.length * 2));\n tmp.set(data, 0);\n data = tmp;\n }\n } : function() {};\n\n var get = HAS_TYPED_ARRAYS ? function() {\n return new Uint8Array(data.buffer, 0, length);\n } : function() {\n return data;\n };\n\n var write = HAS_TYPED_ARRAYS ? function(bytes) {\n if (typeof bytes == \"string\") {\n return writeString(bytes);\n }\n var len = bytes.length;\n ensure(offset + len);\n data.set(bytes, offset);\n offset += len;\n if (offset > length) {\n length = offset;\n }\n } : function(bytes) {\n if (typeof bytes == \"string\") {\n return writeString(bytes);\n }\n for (var i = 0; i < bytes.length; ++i) {\n writeByte(bytes[i]);\n }\n };\n\n var slice = HAS_TYPED_ARRAYS ? function(start, length) {\n if (data.buffer.slice) {\n return new Uint8Array(data.buffer.slice(start, start + length));\n } else {\n // IE10\n var x = new Uint8Array(length);\n x.set(new Uint8Array(data.buffer, start, length));\n return x;\n }\n } : function(start, length) {\n return data.slice(start, start + length);\n };\n\n function eof() {\n return offset >= length;\n }\n function readByte() {\n return offset < length ? data[offset++] : 0;\n }\n function writeByte(b) {\n ensure(offset);\n data[offset++] = b & 0xFF;\n if (offset > length) {\n length = offset;\n }\n }\n function readShort() {\n return (readByte() << 8) | readByte();\n }\n function writeShort(w) {\n writeByte(w >> 8);\n writeByte(w);\n }\n function readShort_() {\n var w = readShort();\n return w >= 0x8000 ? w - 0x10000 : w;\n }\n function writeShort_(w) {\n writeShort(w < 0 ? w + 0x10000 : w);\n }\n function readLong() {\n return (readShort() * 0x10000) + readShort();\n }\n function writeLong(w) {\n writeShort((w >>> 16) & 0xFFFF);\n writeShort(w & 0xFFFF);\n }\n function readLong_() {\n var w = readLong();\n return w >= 0x80000000 ? w - 0x100000000 : w;\n }\n function writeLong_(w) {\n writeLong(w < 0 ? w + 0x100000000 : w);\n }\n function readFixed() {\n return readLong() / 0x10000;\n }\n function writeFixed(f) {\n writeLong(Math.round(f * 0x10000));\n }\n function readFixed_() {\n return readLong_() / 0x10000;\n }\n function writeFixed_(f) {\n writeLong_(Math.round(f * 0x10000));\n }\n function read(len) {\n return times(len, readByte);\n }\n function readString(len) {\n return String.fromCharCode.apply(String, read(len));\n }\n function writeString(str) {\n for (var i = 0; i < str.length; ++i) {\n writeByte(str.charCodeAt(i));\n }\n }\n function times(n, reader) {\n for (var ret = new Array(n), i = 0; i < n; ++i) {\n ret[i] = reader();\n }\n return ret;\n }\n\n var stream = {\n eof : eof,\n readByte : readByte,\n writeByte : writeByte,\n readShort : readShort,\n writeShort : writeShort,\n readLong : readLong,\n writeLong : writeLong,\n readFixed : readFixed,\n writeFixed : writeFixed,\n\n // signed numbers.\n readShort_ : readShort_,\n writeShort_ : writeShort_,\n readLong_ : readLong_,\n writeLong_ : writeLong_,\n readFixed_ : readFixed_,\n writeFixed_ : writeFixed_,\n\n read : read,\n write : write,\n readString : readString,\n writeString : writeString,\n\n times : times,\n get : get,\n slice : slice,\n\n offset: function(pos) {\n if (pos != null) {\n offset = pos;\n return stream;\n }\n return offset;\n },\n\n skip: function(nbytes) {\n offset += nbytes;\n },\n\n toString: function() {\n throw new Error(\"FIX CALLER. BinaryStream is no longer convertible to string!\");\n },\n\n length: function() { return length; },\n\n saveExcursion: function(f) {\n var pos = offset;\n try {\n return f();\n } finally {\n offset = pos;\n }\n },\n\n writeBase64: function(base64) {\n if (window.atob) {\n writeString(window.atob(base64));\n } else {\n write(BASE64.decode(base64));\n }\n },\n base64: function() {\n return BASE64.encode(get());\n }\n };\n\n return stream;\n}\n\nfunction ucs2decode(string) {\n var output = [],\n counter = 0,\n length = string.length,\n value,\n extra;\n while (counter < length) {\n value = string.charCodeAt(counter++);\n if (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n // high surrogate, and there is a next character\n extra = string.charCodeAt(counter++);\n if ((extra & 0xFC00) == 0xDC00) { // low surrogate\n output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n } else {\n // unmatched surrogate; only append this code unit, in case the next\n // code unit is the high surrogate of a surrogate pair\n output.push(value);\n counter--;\n }\n } else {\n output.push(value);\n }\n }\n return output;\n}\n\nfunction ucs2encode(array) {\n return array.map(function(value){\n var output = \"\";\n if (value > 0xFFFF) {\n value -= 0x10000;\n output += String.fromCharCode(value >>> 10 & 0x3FF | 0xD800);\n value = 0xDC00 | value & 0x3FF;\n }\n output += String.fromCharCode(value);\n return output;\n }).join(\"\");\n}\n\nfunction atobUint8Array(base64) {\n var data = window.atob(base64);\n var result = new Uint8Array(data.length);\n\n for (var idx = 0; idx < data.length; idx++) {\n result[idx] = data.charCodeAt(idx);\n }\n\n return result;\n}\n\nfunction createUint8Array(data) {\n var result = new Uint8Array(data.length);\n\n for (var idx = 0; idx < data.length; idx++) {\n result[idx] = data[idx];\n }\n\n return result;\n}\n\nfunction base64ToUint8Array(base64) {\n if (window.atob) {\n return atobUint8Array(base64);\n }\n\n return createUint8Array(BASE64.decode(base64));\n}\n\nexport {\n HAS_TYPED_ARRAYS,\n BASE64,\n BinaryStream,\n ucs2decode,\n ucs2encode,\n base64ToUint8Array\n};\n","/* eslint-disable no-multi-spaces, key-spacing, indent, camelcase, space-before-blocks, eqeqeq, brace-style */\n/* eslint-disable space-infix-ops, space-before-function-paren, array-bracket-spacing, object-curly-spacing */\n/* eslint-disable no-nested-ternary, max-params, default-case, no-else-return, no-empty */\n/* eslint-disable no-param-reassign, no-var, block-scoped-var */\n\n/*****************************************************************************\\\n *\n * The code in this file, although written from scratch, is influenced by the\n * TrueType parser/encoder in PDFKit -- http://pdfkit.org/ (a CoffeeScript\n * library for producing PDF files).\n *\n * PDFKit is (c) Devon Govett 2014 and released under the MIT License.\n *\n\\*****************************************************************************/\n\nimport { BinaryStream, ucs2decode } from \"./utils\";\n\nfunction hasOwnProperty(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nfunction sortedKeys(obj) {\n return Object.keys(obj).sort(function(a, b){ return a - b; }).map(parseFloat);\n}\n\n///\nvar Directory = function Directory(data) {\n this.raw = data;\n this.scalerType = data.readLong();\n this.tableCount = data.readShort();\n this.searchRange = data.readShort();\n this.entrySelector = data.readShort();\n this.rangeShift = data.readShort();\n\n var tables = this.tables = {};\n for (var i = 0; i < this.tableCount; ++i) {\n var entry = {\n tag : data.readString(4),\n checksum : data.readLong(),\n offset : data.readLong(),\n length : data.readLong()\n };\n tables[entry.tag] = entry;\n }\n};\n\nDirectory.prototype.readTable = function readTable (name, Ctor) {\n var def = this.tables[name];\n if (!def) {\n throw new Error(\"Table \" + name + \" not found in directory\");\n }\n return (this[name] = def.table = new Ctor(this, def));\n};\n\nDirectory.prototype.render = function render (tables) {\n var this$1 = this;\n\n var tableCount = Object.keys(tables).length;\n\n var maxpow2 = Math.pow(2, Math.floor(Math.log(tableCount) / Math.LN2));\n var searchRange = maxpow2 * 16;\n var entrySelector = Math.floor(Math.log(maxpow2) / Math.LN2);\n var rangeShift = tableCount * 16 - searchRange;\n\n var out = BinaryStream();\n out.writeLong(this.scalerType);\n out.writeShort(tableCount);\n out.writeShort(searchRange);\n out.writeShort(entrySelector);\n out.writeShort(rangeShift);\n\n var directoryLength = tableCount * 16;\n var offset = out.offset() + directoryLength;\n var headOffset = null;\n var tableData = BinaryStream();\n\n for (var tag in tables) {\n if (hasOwnProperty(tables, tag)) {\n var table = tables[tag];\n\n out.writeString(tag);\n out.writeLong(this$1.checksum(table));\n out.writeLong(offset);\n out.writeLong(table.length);\n\n tableData.write(table);\n if (tag == \"head\") {\n headOffset = offset;\n }\n offset += table.length;\n\n while (offset % 4) {\n tableData.writeByte(0);\n offset++;\n }\n }\n }\n\n out.write(tableData.get());\n var sum = this.checksum(out.get());\n var adjustment = 0xB1B0AFBA - sum;\n\n out.offset(headOffset + 8);\n out.writeLong(adjustment);\n return out.get();\n};\n\nDirectory.prototype.checksum = function checksum (data) {\n data = BinaryStream(data);\n var sum = 0;\n while (!data.eof()) {\n sum += data.readLong();\n }\n return sum & 0xFFFFFFFF;\n};\n\nvar Table = function Table(file, def) {\n this.definition = def;\n this.length = def.length;\n this.offset = def.offset;\n this.file = file;\n this.rawData = file.raw;\n this.parse(file.raw);\n};\n\nTable.prototype.raw = function raw () {\n return this.rawData.slice(this.offset, this.length);\n};\n\nTable.prototype.parse = function parse () {};\n\nvar HeadTable = (function (Table) {\n function HeadTable () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) HeadTable.__proto__ = Table;\n HeadTable.prototype = Object.create( Table && Table.prototype );\n HeadTable.prototype.constructor = HeadTable;\n\n HeadTable.prototype.parse = function parse (data) {\n data.offset(this.offset);\n this.version = data.readLong();\n this.revision = data.readLong();\n this.checkSumAdjustment = data.readLong();\n this.magicNumber = data.readLong();\n this.flags = data.readShort();\n this.unitsPerEm = data.readShort();\n this.created = data.read(8);\n this.modified = data.read(8);\n\n this.xMin = data.readShort_();\n this.yMin = data.readShort_();\n this.xMax = data.readShort_();\n this.yMax = data.readShort_();\n\n this.macStyle = data.readShort();\n this.lowestRecPPEM = data.readShort();\n this.fontDirectionHint = data.readShort_();\n this.indexToLocFormat = data.readShort_();\n this.glyphDataFormat = data.readShort_();\n };\n\n HeadTable.prototype.render = function render (indexToLocFormat) {\n var out = BinaryStream();\n out.writeLong(this.version);\n out.writeLong(this.revision);\n out.writeLong(0); // checksum adjustment; shall be computed later\n out.writeLong(this.magicNumber);\n out.writeShort(this.flags);\n out.writeShort(this.unitsPerEm);\n out.write(this.created);\n out.write(this.modified);\n out.writeShort_(this.xMin);\n out.writeShort_(this.yMin);\n out.writeShort_(this.xMax);\n out.writeShort_(this.yMax);\n out.writeShort(this.macStyle);\n out.writeShort(this.lowestRecPPEM);\n out.writeShort_(this.fontDirectionHint);\n out.writeShort_(indexToLocFormat); // this will depend on the `loca` table\n out.writeShort_(this.glyphDataFormat);\n return out.get();\n };\n\n return HeadTable;\n}(Table));\n\nvar LocaTable = (function (Table) {\n function LocaTable () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) LocaTable.__proto__ = Table;\n LocaTable.prototype = Object.create( Table && Table.prototype );\n LocaTable.prototype.constructor = LocaTable;\n\n LocaTable.prototype.parse = function parse (data) {\n data.offset(this.offset);\n var format = this.file.head.indexToLocFormat;\n if (format === 0) {\n this.offsets = data.times(this.length / 2, function(){\n return 2 * data.readShort();\n });\n } else {\n this.offsets = data.times(this.length / 4, data.readLong);\n }\n };\n\n LocaTable.prototype.offsetOf = function offsetOf (id) {\n return this.offsets[id];\n };\n\n LocaTable.prototype.lengthOf = function lengthOf (id) {\n return this.offsets[id + 1] - this.offsets[id];\n };\n\n LocaTable.prototype.render = function render (offsets) {\n var out = BinaryStream();\n var needsLongFormat = offsets[offsets.length - 1] > 0xFFFF;\n for (var i = 0; i < offsets.length; ++i) {\n if (needsLongFormat) {\n out.writeLong(offsets[i]);\n } else {\n out.writeShort(offsets[i] / 2);\n }\n }\n return {\n format: needsLongFormat ? 1 : 0,\n table: out.get()\n };\n };\n\n return LocaTable;\n}(Table));\n\nvar HheaTable = (function (Table) {\n function HheaTable () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) HheaTable.__proto__ = Table;\n HheaTable.prototype = Object.create( Table && Table.prototype );\n HheaTable.prototype.constructor = HheaTable;\n\n HheaTable.prototype.parse = function parse (data) {\n data.offset(this.offset);\n\n this.version = data.readLong();\n this.ascent = data.readShort_();\n this.descent = data.readShort_();\n this.lineGap = data.readShort_();\n this.advanceWidthMax = data.readShort();\n this.minLeftSideBearing = data.readShort_();\n this.minRightSideBearing = data.readShort_();\n this.xMaxExtent = data.readShort_();\n this.caretSlopeRise = data.readShort_();\n this.caretSlopeRun = data.readShort_();\n this.caretOffset = data.readShort_();\n\n data.skip(4 * 2); // reserved\n\n this.metricDataFormat = data.readShort_();\n this.numOfLongHorMetrics = data.readShort();\n };\n\n HheaTable.prototype.render = function render (ids) {\n var out = BinaryStream();\n out.writeLong(this.version);\n out.writeShort_(this.ascent);\n out.writeShort_(this.descent);\n out.writeShort_(this.lineGap);\n out.writeShort(this.advanceWidthMax);\n out.writeShort_(this.minLeftSideBearing);\n out.writeShort_(this.minRightSideBearing);\n out.writeShort_(this.xMaxExtent);\n out.writeShort_(this.caretSlopeRise);\n out.writeShort_(this.caretSlopeRun);\n out.writeShort_(this.caretOffset);\n\n out.write([ 0, 0, 0, 0, 0, 0, 0, 0 ]); // reserved bytes\n\n out.writeShort_(this.metricDataFormat);\n out.writeShort(ids.length);\n return out.get();\n };\n\n return HheaTable;\n}(Table));\n\nvar MaxpTable = (function (Table) {\n function MaxpTable () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) MaxpTable.__proto__ = Table;\n MaxpTable.prototype = Object.create( Table && Table.prototype );\n MaxpTable.prototype.constructor = MaxpTable;\n\n MaxpTable.prototype.parse = function parse (data) {\n data.offset(this.offset);\n this.version = data.readLong();\n this.numGlyphs = data.readShort();\n this.maxPoints = data.readShort();\n this.maxContours = data.readShort();\n this.maxComponentPoints = data.readShort();\n this.maxComponentContours = data.readShort();\n this.maxZones = data.readShort();\n this.maxTwilightPoints = data.readShort();\n this.maxStorage = data.readShort();\n this.maxFunctionDefs = data.readShort();\n this.maxInstructionDefs = data.readShort();\n this.maxStackElements = data.readShort();\n this.maxSizeOfInstructions = data.readShort();\n this.maxComponentElements = data.readShort();\n this.maxComponentDepth = data.readShort();\n };\n\n MaxpTable.prototype.render = function render (glyphIds) {\n var out = BinaryStream();\n out.writeLong(this.version);\n out.writeShort(glyphIds.length);\n out.writeShort(this.maxPoints);\n out.writeShort(this.maxContours);\n out.writeShort(this.maxComponentPoints);\n out.writeShort(this.maxComponentContours);\n out.writeShort(this.maxZones);\n out.writeShort(this.maxTwilightPoints);\n out.writeShort(this.maxStorage);\n out.writeShort(this.maxFunctionDefs);\n out.writeShort(this.maxInstructionDefs);\n out.writeShort(this.maxStackElements);\n out.writeShort(this.maxSizeOfInstructions);\n out.writeShort(this.maxComponentElements);\n out.writeShort(this.maxComponentDepth);\n return out.get();\n };\n\n return MaxpTable;\n}(Table));\n\nvar HmtxTable = (function (Table) {\n function HmtxTable () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) HmtxTable.__proto__ = Table;\n HmtxTable.prototype = Object.create( Table && Table.prototype );\n HmtxTable.prototype.constructor = HmtxTable;\n\n HmtxTable.prototype.parse = function parse (data) {\n data.offset(this.offset);\n var dir = this.file, hhea = dir.hhea;\n this.metrics = data.times(hhea.numOfLongHorMetrics, function(){\n return {\n advance: data.readShort(),\n lsb: data.readShort_()\n };\n });\n var lsbCount = dir.maxp.numGlyphs - dir.hhea.numOfLongHorMetrics;\n this.leftSideBearings = data.times(lsbCount, data.readShort_);\n };\n\n HmtxTable.prototype.forGlyph = function forGlyph (id) {\n var metrics = this.metrics;\n var n = metrics.length;\n if (id < n) {\n return metrics[id];\n }\n return {\n advance: metrics[n - 1].advance,\n lsb: this.leftSideBearings[id - n]\n };\n };\n\n HmtxTable.prototype.render = function render (glyphIds) {\n var this$1 = this;\n\n var out = BinaryStream();\n for (var i = 0; i < glyphIds.length; ++i) {\n var m = this$1.forGlyph(glyphIds[i]);\n out.writeShort(m.advance);\n out.writeShort_(m.lsb);\n }\n return out.get();\n };\n\n return HmtxTable;\n}(Table));\n\nvar GlyfTable = (function(){\n var SimpleGlyph = function SimpleGlyph(raw) {\n this.raw = raw;\n };\n\n var prototypeAccessors = { compound: { configurable: true } };\n\n prototypeAccessors.compound.get = function () {\n return false;\n };\n\n SimpleGlyph.prototype.render = function render () {\n return this.raw.get();\n };\n\n Object.defineProperties( SimpleGlyph.prototype, prototypeAccessors );\n\n var ARG_1_AND_2_ARE_WORDS = 0x0001;\n var WE_HAVE_A_SCALE = 0x0008;\n var MORE_COMPONENTS = 0x0020;\n var WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;\n var WE_HAVE_A_TWO_BY_TWO = 0x0080;\n //var WE_HAVE_INSTRUCTIONS = 0x0100;\n\n var CompoundGlyph = function CompoundGlyph(data) {\n this.raw = data;\n var ids = this.glyphIds = [];\n var offsets = this.idOffsets = [];\n while (true) { // eslint-disable-line no-constant-condition\n var flags = data.readShort();\n offsets.push(data.offset());\n ids.push(data.readShort());\n\n if (!(flags & MORE_COMPONENTS)) {\n break;\n }\n\n data.skip(flags & ARG_1_AND_2_ARE_WORDS ? 4 : 2);\n\n if (flags & WE_HAVE_A_TWO_BY_TWO) {\n data.skip(8);\n } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {\n data.skip(4);\n } else if (flags & WE_HAVE_A_SCALE) {\n data.skip(2);\n }\n }\n };\n\n var prototypeAccessors$1 = { compound: { configurable: true } };\n\n prototypeAccessors$1.compound.get = function () {\n return true;\n };\n\n CompoundGlyph.prototype.render = function render (old2new) {\n var this$1 = this;\n\n var out = BinaryStream(this.raw.get());\n for (var i = 0; i < this.glyphIds.length; ++i) {\n var id = this$1.glyphIds[i];\n out.offset(this$1.idOffsets[i]);\n out.writeShort(old2new[id]);\n }\n return out.get();\n };\n\n Object.defineProperties( CompoundGlyph.prototype, prototypeAccessors$1 );\n\n return (function (Table) {\n function anonymous () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) anonymous.__proto__ = Table;\n anonymous.prototype = Object.create( Table && Table.prototype );\n anonymous.prototype.constructor = anonymous;\n\n anonymous.prototype.parse = function parse () {\n this.cache = {};\n };\n\n anonymous.prototype.glyphFor = function glyphFor (id) {\n var cache = this.cache;\n if (hasOwnProperty(cache, id)) {\n return cache[id];\n }\n\n var loca = this.file.loca;\n var length = loca.lengthOf(id);\n\n if (length === 0) {\n return (cache[id] = null);\n }\n\n var data = this.rawData;\n var offset = this.offset + loca.offsetOf(id);\n var raw = BinaryStream(data.slice(offset, length));\n\n var numberOfContours = raw.readShort_();\n var xMin = raw.readShort_();\n var yMin = raw.readShort_();\n var xMax = raw.readShort_();\n var yMax = raw.readShort_();\n\n var glyph = cache[id] = numberOfContours < 0 ? new CompoundGlyph(raw) : new SimpleGlyph(raw);\n\n glyph.numberOfContours = numberOfContours;\n glyph.xMin = xMin;\n glyph.yMin = yMin;\n glyph.xMax = xMax;\n glyph.yMax = yMax;\n\n return glyph;\n };\n\n anonymous.prototype.render = function render (glyphs, oldIds, old2new) {\n var out = BinaryStream(), offsets = [];\n for (var i = 0; i < oldIds.length; ++i) {\n var id = oldIds[i];\n var glyph = glyphs[id];\n if (out.offset() % 2) {\n out.writeByte(0);\n }\n offsets.push(out.offset());\n if (glyph) {\n out.write(glyph.render(old2new));\n }\n }\n if (out.offset() % 2) {\n out.writeByte(0);\n }\n offsets.push(out.offset());\n return {\n table: out.get(),\n offsets: offsets\n };\n };\n\n return anonymous;\n }(Table));\n}());\n\nvar NameTable = (function(){\n var NameEntry = function NameEntry(text, entry) {\n this.text = text;\n this.length = text.length;\n this.platformID = entry.platformID;\n this.platformSpecificID = entry.platformSpecificID;\n this.languageID = entry.languageID;\n this.nameID = entry.nameID;\n };\n\n return (function (Table) {\n function anonymous () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) anonymous.__proto__ = Table;\n anonymous.prototype = Object.create( Table && Table.prototype );\n anonymous.prototype.constructor = anonymous;\n\n anonymous.prototype.parse = function parse (data) {\n data.offset(this.offset);\n data.readShort(); // format\n var count = data.readShort();\n var stringOffset = this.offset + data.readShort();\n var nameRecords = data.times(count, function(){\n return {\n platformID : data.readShort(),\n platformSpecificID : data.readShort(),\n languageID : data.readShort(),\n nameID : data.readShort(),\n length : data.readShort(),\n offset : data.readShort() + stringOffset\n };\n });\n var strings = this.strings = {};\n for (var i = 0; i < nameRecords.length; ++i) {\n var rec = nameRecords[i];\n data.offset(rec.offset);\n var text = data.readString(rec.length);\n if (!strings[rec.nameID]) {\n strings[rec.nameID] = [];\n }\n strings[rec.nameID].push(new NameEntry(text, rec));\n }\n this.postscriptEntry = strings[6][0];\n this.postscriptName = this.postscriptEntry.text.replace(/[^\\x20-\\x7F]/g, \"\");\n };\n\n anonymous.prototype.render = function render (psName) {\n var this$1 = this;\n\n var strings = this.strings;\n var strCount = 0;\n for (var i in strings) {\n if (hasOwnProperty(strings, i)) {\n strCount += strings[i].length;\n }\n }\n var out = BinaryStream();\n var strTable = BinaryStream();\n\n out.writeShort(0); // format\n out.writeShort(strCount);\n out.writeShort(6 + 12 * strCount); // stringOffset\n\n for (i in strings) {\n if (hasOwnProperty(strings, i)) {\n var list = i == 6 ? [\n new NameEntry(psName, this$1.postscriptEntry)\n ] : strings[i];\n for (var j = 0; j < list.length; ++j) {\n var str = list[j];\n out.writeShort(str.platformID);\n out.writeShort(str.platformSpecificID);\n out.writeShort(str.languageID);\n out.writeShort(str.nameID);\n out.writeShort(str.length);\n out.writeShort(strTable.offset());\n\n strTable.writeString(str.text);\n }\n }\n }\n\n out.write(strTable.get());\n\n return out.get();\n };\n\n return anonymous;\n }(Table));\n})();\n\nvar PostTable = (function(){\n var POSTSCRIPT_GLYPHS = \".notdef .null nonmarkingreturn space exclam quotedbl numbersign dollar percent ampersand quotesingle parenleft parenright asterisk plus comma hyphen period slash zero one two three four five six seven eight nine colon semicolon less equal greater question at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum underscore grave a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright asciitilde Adieresis Aring Ccedilla Eacute Ntilde Odieresis Udieresis aacute agrave acircumflex adieresis atilde aring ccedilla eacute egrave ecircumflex edieresis iacute igrave icircumflex idieresis ntilde oacute ograve ocircumflex odieresis otilde uacute ugrave ucircumflex udieresis dagger degree cent sterling section bullet paragraph germandbls registered copyright trademark acute dieresis notequal AE Oslash infinity plusminus lessequal greaterequal yen mu partialdiff summation product pi integral ordfeminine ordmasculine Omega ae oslash questiondown exclamdown logicalnot radical florin approxequal Delta guillemotleft guillemotright ellipsis nonbreakingspace Agrave Atilde Otilde OE oe endash emdash quotedblleft quotedblright quoteleft quoteright divide lozenge ydieresis Ydieresis fraction currency guilsinglleft guilsinglright fi fl daggerdbl periodcentered quotesinglbase quotedblbase perthousand Acircumflex Ecircumflex Aacute Edieresis Egrave Iacute Icircumflex Idieresis Igrave Oacute Ocircumflex apple Ograve Uacute Ucircumflex Ugrave dotlessi circumflex tilde macron breve dotaccent ring cedilla hungarumlaut ogonek caron Lslash lslash Scaron scaron Zcaron zcaron brokenbar Eth eth Yacute yacute Thorn thorn minus multiply onesuperior twosuperior threesuperior onehalf onequarter threequarters franc Gbreve gbreve Idotaccent Scedilla scedilla Cacute cacute Ccaron ccaron dcroat\".split(/\\s+/g);\n\n return (function (Table) {\n function anonymous () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) anonymous.__proto__ = Table;\n anonymous.prototype = Object.create( Table && Table.prototype );\n anonymous.prototype.constructor = anonymous;\n\n anonymous.prototype.parse = function parse (data) {\n var this$1 = this;\n\n data.offset(this.offset);\n\n this.format = data.readLong();\n this.italicAngle = data.readFixed_();\n this.underlinePosition = data.readShort_();\n this.underlineThickness = data.readShort_();\n this.isFixedPitch = data.readLong();\n this.minMemType42 = data.readLong();\n this.maxMemType42 = data.readLong();\n this.minMemType1 = data.readLong();\n this.maxMemType1 = data.readLong();\n\n var numberOfGlyphs;\n\n switch (this.format) {\n case 0x00010000:\n case 0x00030000:\n break;\n\n case 0x00020000:\n numberOfGlyphs = data.readShort();\n this.glyphNameIndex = data.times(numberOfGlyphs, data.readShort);\n this.names = [];\n var limit = this.offset + this.length;\n while (data.offset() < limit) {\n this$1.names.push(data.readString(data.readByte()));\n }\n break;\n\n case 0x00025000:\n numberOfGlyphs = data.readShort();\n this.offsets = data.read(numberOfGlyphs);\n break;\n\n case 0x00040000:\n this.map = data.times(this.file.maxp.numGlyphs, data.readShort);\n break;\n }\n };\n\n anonymous.prototype.glyphFor = function glyphFor (code) {\n switch (this.format) {\n case 0x00010000:\n return POSTSCRIPT_GLYPHS[code] || \".notdef\";\n\n case 0x00020000:\n var index = this.glyphNameIndex[code];\n if (index < POSTSCRIPT_GLYPHS.length) {\n return POSTSCRIPT_GLYPHS[index];\n }\n return this.names[index - POSTSCRIPT_GLYPHS.length] || \".notdef\";\n\n case 0x00025000:\n\n case 0x00030000:\n return \".notdef\";\n\n case 0x00040000:\n return this.map[code] || 0xFFFF;\n }\n };\n\n anonymous.prototype.render = function render (mapping) {\n var this$1 = this;\n\n if (this.format == 0x00030000) {\n return this.raw();\n }\n\n // keep original header, but set format to 2.0\n var out = BinaryStream(this.rawData.slice(this.offset, 32));\n out.writeLong(0x00020000);\n out.offset(32);\n\n var indexes = [];\n var strings = [];\n\n for (var i = 0; i < mapping.length; ++i) {\n var id = mapping[i];\n var post = this$1.glyphFor(id);\n var index = POSTSCRIPT_GLYPHS.indexOf(post);\n if (index >= 0) {\n indexes.push(index);\n } else {\n indexes.push(POSTSCRIPT_GLYPHS.length + strings.length);\n strings.push(post);\n }\n }\n\n out.writeShort(mapping.length);\n\n for (i = 0; i < indexes.length; ++i) {\n out.writeShort(indexes[i]);\n }\n\n for (i = 0; i < strings.length; ++i) {\n out.writeByte(strings[i].length);\n out.writeString(strings[i]);\n }\n\n return out.get();\n };\n\n return anonymous;\n }(Table));\n})();\n\nvar CmapTable = (function(){\n var CmapEntry = function CmapEntry(data, offset, codeMap) {\n var self = this;\n self.platformID = data.readShort();\n self.platformSpecificID = data.readShort();\n self.offset = offset + data.readLong();\n\n data.saveExcursion(function(){\n var code;\n data.offset(self.offset);\n self.format = data.readShort();\n\n switch (self.format) {\n case 0:\n self.length = data.readShort();\n self.language = data.readShort();\n for (var i = 0; i < 256; ++i) {\n codeMap[i] = data.readByte();\n }\n break;\n\n case 4:\n self.length = data.readShort();\n self.language = data.readShort();\n var segCount = data.readShort() / 2;\n\n data.skip(6); // searchRange, entrySelector, rangeShift\n var endCode = data.times(segCount, data.readShort);\n data.skip(2); // reserved pad\n var startCode = data.times(segCount, data.readShort);\n var idDelta = data.times(segCount, data.readShort_);\n var idRangeOffset = data.times(segCount, data.readShort);\n\n var count = (self.length + self.offset - data.offset()) / 2;\n var glyphIds = data.times(count, data.readShort);\n\n for (i = 0; i < segCount; ++i) {\n var start = startCode[i], end = endCode[i];\n for (code = start; code <= end; ++code) {\n var glyphId;\n if (idRangeOffset[i] === 0) {\n glyphId = code + idDelta[i];\n } else {\n ///\n // When non-zero, idRangeOffset contains for each segment the byte offset of the Glyph ID\n // into the glyphIds table, from the *current* `i` cell of idRangeOffset. In other words,\n // this offset spans from the first into the second array. This works, because the arrays\n // are consecutive in the TTF file:\n //\n // [ ...idRangeOffset... ][ ...glyphIds... ]\n // ...... 48 ...... .... ID ....\n // ^----- 48 bytes -----^\n //\n // (but I can't stop wondering why is it not just a plain index, possibly incremented by 1\n // so that we can have that special `zero` value.)\n //\n // The elements of idRangeOffset are even numbers, because both arrays contain 16-bit words,\n // yet the offset is in bytes. That is why we divide it by 2. Then we subtract the\n // remaining segments (segCount-i), and add the code-start offset, to which we need to add\n // the corresponding delta to get the actual glyph ID.\n ///\n var index = idRangeOffset[i] / 2 - (segCount - i) + (code - start);\n glyphId = glyphIds[index] || 0;\n if (glyphId !== 0) {\n glyphId += idDelta[i];\n }\n }\n codeMap[code] = glyphId & 0xFFFF;\n }\n }\n break;\n\n case 6:\n self.length = data.readShort();\n self.language = data.readShort();\n code = data.readShort();\n var length = data.readShort();\n while (length-- > 0) {\n codeMap[code++] = data.readShort();\n }\n break;\n\n case 12:\n data.readShort(); // reserved\n self.length = data.readLong();\n self.language = data.readLong();\n var ngroups = data.readLong();\n while (ngroups-- > 0) {\n code = data.readLong();\n var endCharCode = data.readLong();\n var glyphCode = data.readLong();\n while (code <= endCharCode) {\n codeMap[code++] = glyphCode++;\n }\n }\n break;\n\n default:\n if (window.console) {\n window.console.error(\"Unhandled CMAP format: \" + self.format);\n }\n }\n });\n };\n\n function renderCharmap(ncid2ogid, ogid2ngid) {\n var codes = sortedKeys(ncid2ogid);\n var startCodes = [];\n var endCodes = [];\n var last = null;\n var diff = null;\n\n function new_gid(charcode) {\n return ogid2ngid[ncid2ogid[charcode]];\n }\n\n for (var i = 0; i < codes.length; ++i) {\n var code = codes[i];\n var gid = new_gid(code);\n var delta = gid - code;\n if (last == null || delta !== diff) {\n if (last) {\n endCodes.push(last);\n }\n startCodes.push(code);\n diff = delta;\n }\n last = code;\n }\n\n if (last) {\n endCodes.push(last);\n }\n endCodes.push(0xFFFF);\n startCodes.push(0xFFFF);\n\n var segCount = startCodes.length;\n var segCountX2 = segCount * 2;\n var searchRange = 2 * Math.pow(2, Math.floor(Math.log(segCount) / Math.LN2));\n var entrySelector = Math.log(searchRange / 2) / Math.LN2;\n var rangeShift = segCountX2 - searchRange;\n\n var deltas = [];\n var rangeOffsets = [];\n var glyphIds = [];\n\n for (i = 0; i < segCount; ++i) {\n var startCode = startCodes[i];\n var endCode = endCodes[i];\n if (startCode == 0xFFFF) {\n deltas.push(0);\n rangeOffsets.push(0);\n break;\n }\n var startGlyph = new_gid(startCode);\n if (startCode - startGlyph >= 0x8000) {\n deltas.push(0);\n rangeOffsets.push(2 * (glyphIds.length + segCount - i));\n for (var j = startCode; j <= endCode; ++j) {\n glyphIds.push(new_gid(j));\n }\n } else {\n deltas.push(startGlyph - startCode);\n rangeOffsets.push(0);\n }\n }\n\n var out = BinaryStream();\n\n out.writeShort(3); // platformID\n out.writeShort(1); // platformSpecificID\n out.writeLong(12); // offset\n out.writeShort(4); // format\n out.writeShort(16 + segCount * 8 + glyphIds.length * 2); // length\n out.writeShort(0); // language\n out.writeShort(segCountX2);\n out.writeShort(searchRange);\n out.writeShort(entrySelector);\n out.writeShort(rangeShift);\n\n endCodes.forEach(out.writeShort);\n out.writeShort(0); // reserved pad\n startCodes.forEach(out.writeShort);\n deltas.forEach(out.writeShort_);\n rangeOffsets.forEach(out.writeShort);\n glyphIds.forEach(out.writeShort);\n\n return out.get();\n }\n\n return (function (Table) {\n function anonymous () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) anonymous.__proto__ = Table;\n anonymous.prototype = Object.create( Table && Table.prototype );\n anonymous.prototype.constructor = anonymous;\n\n anonymous.prototype.parse = function parse (data) {\n var self = this;\n var offset = self.offset;\n data.offset(offset);\n self.codeMap = {};\n self.version = data.readShort();\n var tableCount = data.readShort();\n self.tables = data.times(tableCount, function(){\n return new CmapEntry(data, offset, self.codeMap);\n });\n };\n\n anonymous.render = function render (ncid2ogid, ogid2ngid) {\n var out = BinaryStream();\n out.writeShort(0); // version\n out.writeShort(1); // tableCount\n out.write(renderCharmap(ncid2ogid, ogid2ngid));\n return out.get();\n };\n\n return anonymous;\n }(Table));\n\n})();\n\nvar OS2Table = (function (Table) {\n function OS2Table () {\n Table.apply(this, arguments);\n }\n\n if ( Table ) OS2Table.__proto__ = Table;\n OS2Table.prototype = Object.create( Table && Table.prototype );\n OS2Table.prototype.constructor = OS2Table;\n\n OS2Table.prototype.parse = function parse (data) {\n data.offset(this.offset);\n this.version = data.readShort();\n this.averageCharWidth = data.readShort_();\n this.weightClass = data.readShort();\n this.widthClass = data.readShort();\n this.type = data.readShort();\n this.ySubscriptXSize = data.readShort_();\n this.ySubscriptYSize = data.readShort_();\n this.ySubscriptXOffset = data.readShort_();\n this.ySubscriptYOffset = data.readShort_();\n this.ySuperscriptXSize = data.readShort_();\n this.ySuperscriptYSize = data.readShort_();\n this.ySuperscriptXOffset = data.readShort_();\n this.ySuperscriptYOffset = data.readShort_();\n this.yStrikeoutSize = data.readShort_();\n this.yStrikeoutPosition = data.readShort_();\n this.familyClass = data.readShort_();\n\n this.panose = data.times(10, data.readByte);\n this.charRange = data.times(4, data.readLong);\n\n this.vendorID = data.readString(4);\n this.selection = data.readShort();\n this.firstCharIndex = data.readShort();\n this.lastCharIndex = data.readShort();\n\n if (this.version > 0) {\n this.ascent = data.readShort_();\n this.descent = data.readShort_();\n this.lineGap = data.readShort_();\n this.winAscent = data.readShort();\n this.winDescent = data.readShort();\n this.codePageRange = data.times(2, data.readLong);\n\n if (this.version > 1) {\n this.xHeight = data.readShort();\n this.capHeight = data.readShort();\n this.defaultChar = data.readShort();\n this.breakChar = data.readShort();\n this.maxContext = data.readShort();\n }\n }\n };\n\n OS2Table.prototype.render = function render () {\n return this.raw();\n };\n\n return OS2Table;\n}(Table));\n\nvar subsetTag = 100000;\n\nfunction nextSubsetTag() {\n var ret = \"\", n = String(subsetTag);\n for (var i = 0; i < n.length; ++i) {\n ret += String.fromCharCode(n.charCodeAt(i) - 48 + 65);\n }\n ++subsetTag;\n return ret;\n}\n\nvar Subfont = function Subfont(font) {\n this.font = font;\n this.subset = {};\n this.unicodes = {};\n this.ogid2ngid = { 0: 0 };\n this.ngid2ogid = { 0: 0 };\n this.ncid2ogid = {};\n this.next = this.firstChar = 1;\n this.nextGid = 1;\n this.psName = nextSubsetTag() + \"+\" + this.font.psName;\n};\n\nSubfont.prototype.use = function use (ch) {\n var self = this;\n if (typeof ch == \"string\") {\n return ucs2decode(ch).reduce(function(ret, code){\n return ret + String.fromCharCode(self.use(code));\n }, \"\");\n }\n var code = self.unicodes[ch];\n if (!code) {\n code = self.next++;\n self.subset[code] = ch;\n self.unicodes[ch] = code;\n\n // generate new GID (glyph ID) and maintain newGID ->\n // oldGID and back mappings\n var old_gid = self.font.cmap.codeMap[ch];\n if (old_gid) {\n self.ncid2ogid[code] = old_gid;\n if (self.ogid2ngid[old_gid] == null) {\n var new_gid = self.nextGid++;\n self.ogid2ngid[old_gid] = new_gid;\n self.ngid2ogid[new_gid] = old_gid;\n }\n }\n }\n return code;\n};\n\nSubfont.prototype.encodeText = function encodeText (text) {\n return this.use(text);\n};\n\nSubfont.prototype.glyphIds = function glyphIds () {\n return sortedKeys(this.ogid2ngid);\n};\n\nSubfont.prototype.glyphsFor = function glyphsFor (glyphIds, result) {\n var this$1 = this;\n\n if (!result) {\n result = {};\n }\n for (var i = 0; i < glyphIds.length; ++i) {\n var id = glyphIds[i];\n if (!result[id]) {\n var glyph = result[id] = this$1.font.glyf.glyphFor(id);\n if (glyph && glyph.compound) {\n this$1.glyphsFor(glyph.glyphIds, result);\n }\n }\n }\n return result;\n};\n\nSubfont.prototype.render = function render () {\n var this$1 = this;\n\n var glyphs = this.glyphsFor(this.glyphIds());\n\n // add missing sub-glyphs\n for (var old_gid in glyphs) {\n if (hasOwnProperty(glyphs, old_gid)) {\n old_gid = parseInt(old_gid, 10);\n if (this$1.ogid2ngid[old_gid] == null) {\n var new_gid = this$1.nextGid++;\n this$1.ogid2ngid[old_gid] = new_gid;\n this$1.ngid2ogid[new_gid] = old_gid;\n }\n }\n }\n\n // must obtain old_gid_ids in an order matching sorted\n // new_gid_ids\n var new_gid_ids = sortedKeys(this.ngid2ogid);\n var old_gid_ids = new_gid_ids.map(function(id){\n return this.ngid2ogid[id];\n }, this);\n\n var font = this.font;\n var glyf = font.glyf.render(glyphs, old_gid_ids, this.ogid2ngid);\n var loca = font.loca.render(glyf.offsets);\n\n this.lastChar = this.next - 1;\n\n var tables = {\n \"cmap\" : CmapTable.render(this.ncid2ogid, this.ogid2ngid),\n \"glyf\" : glyf.table,\n \"loca\" : loca.table,\n \"hmtx\" : font.hmtx.render(old_gid_ids),\n \"hhea\" : font.hhea.render(old_gid_ids),\n \"maxp\" : font.maxp.render(old_gid_ids),\n \"post\" : font.post.render(old_gid_ids),\n \"name\" : font.name.render(this.psName),\n \"head\" : font.head.render(loca.format),\n \"OS/2\" : font.os2.render()\n };\n\n return this.font.directory.render(tables);\n};\n\nSubfont.prototype.cidToGidMap = function cidToGidMap () {\n var this$1 = this;\n\n var out = BinaryStream(), len = 0;\n for (var cid = this.firstChar; cid < this.next; ++cid) {\n while (len < cid) {\n out.writeShort(0);\n len++;\n }\n var old_gid = this$1.ncid2ogid[cid];\n if (old_gid) {\n var new_gid = this$1.ogid2ngid[old_gid];\n out.writeShort(new_gid);\n } else {\n out.writeShort(0);\n }\n len++;\n }\n return out.get();\n};\n\nvar TTFFont = function TTFFont(rawData, name) {\n var self = this;\n var data = self.contents = BinaryStream(rawData);\n if (data.readString(4) == \"ttcf\") {\n var offset;\n var parse = function() {\n data.offset(offset);\n self.parse();\n };\n if (!name) {\n throw new Error(\"Must specify a name for TTC files\");\n }\n data.readLong(); // version\n var numFonts = data.readLong();\n for (var i = 0; i < numFonts; ++i) {\n offset = data.readLong();\n data.saveExcursion(parse);\n if (self.psName == name) {\n return;\n }\n }\n throw new Error(\"Font \" + name + \" not found in collection\");\n } else {\n data.offset(0);\n self.parse();\n }\n};\n\nTTFFont.prototype.parse = function parse () {\n var dir = this.directory = new Directory(this.contents);\n\n this.head = dir.readTable(\"head\", HeadTable);\n this.loca = dir.readTable(\"loca\", LocaTable);\n this.hhea = dir.readTable(\"hhea\", HheaTable);\n this.maxp = dir.readTable(\"maxp\", MaxpTable);\n this.hmtx = dir.readTable(\"hmtx\", HmtxTable);\n this.glyf = dir.readTable(\"glyf\", GlyfTable);\n this.name = dir.readTable(\"name\", NameTable);\n this.post = dir.readTable(\"post\", PostTable);\n this.cmap = dir.readTable(\"cmap\", CmapTable);\n this.os2 = dir.readTable(\"OS/2\", OS2Table);\n\n this.psName = this.name.postscriptName;\n this.ascent = this.os2.ascent || this.hhea.ascent;\n this.descent = this.os2.descent || this.hhea.descent;\n this.lineGap = this.os2.lineGap || this.hhea.lineGap;\n this.scale = 1000 / this.head.unitsPerEm;\n};\n\nTTFFont.prototype.widthOfGlyph = function widthOfGlyph (glyph) {\n return this.hmtx.forGlyph(glyph).advance * this.scale;\n};\n\nTTFFont.prototype.makeSubset = function makeSubset () {\n return new Subfont(this);\n};\n\nexport { TTFFont };\n","/* eslint-disable */\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nvar Z_NO_FLUSH = 0;\nvar Z_PARTIAL_FLUSH = 1;\nvar Z_SYNC_FLUSH = 2;\nvar Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n/* Return codes for the compression/decompression functions. Negative values\n* are errors, positive values are used for special but normal events.\n*/\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\nvar Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\n//export var Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//export var Z_VERSION_ERROR = -6;\n\n/* compression levels */\nvar Z_NO_COMPRESSION = 0;\nvar Z_BEST_SPEED = 1;\nvar Z_BEST_COMPRESSION = 9;\nvar Z_DEFAULT_COMPRESSION = -1;\n\n\nvar Z_FILTERED = 1;\nvar Z_HUFFMAN_ONLY = 2;\nvar Z_RLE = 3;\nvar Z_FIXED = 4;\nvar Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nvar Z_BINARY = 0;\nvar Z_TEXT = 1;\n//export var Z_ASCII = 1; // = Z_TEXT (deprecated)\nvar Z_UNKNOWN = 2;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n//export var Z_NULL = null // Use -1 or null inline; depending on var type\n\n/* eslint-disable */\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nfunction assign(obj /*from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n}\n\n\n// reduce buffer size, avoiding mem copy\nfunction shrinkBuf(buf, size) {\n if (buf.length === size) { return buf; }\n if (buf.subarray) { return buf.subarray(0, size); }\n buf.length = size;\n return buf;\n}\n\nvar fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n var i, l, len, pos, chunk, result;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n },\n Buf8: function(size) {\n return new Uint8Array(size);\n },\n Buf16: function(size) {\n return new Uint16Array(size);\n },\n Buf32: function(size) {\n return new Int32Array(size);\n }\n};\n\nvar fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n },\n Buf8: function(size) {\n return new Array(size);\n },\n Buf16: function(size) {\n return new Array(size);\n },\n Buf32: function(size) {\n return new Array(size);\n }\n};\n\nvar typedOK = function () {\n var supported =\n (typeof Uint8Array !== 'undefined') &&\n (typeof Uint16Array !== 'undefined') &&\n (typeof Int32Array !== 'undefined');\n\n typedOK = function () { return supported; };\n return supported;\n};\n\nvar arraySet = function (dest, src, src_offs, len, dest_offs) {\n arraySet = typedOK() ?\n fnTyped.arraySet : fnUntyped.arraySet;\n\n return arraySet(dest, src, src_offs, len, dest_offs);\n};\n\nvar flattenChunks = function (chunks) {\n flattenChunks = typedOK() ?\n fnTyped.flattenChunks : fnUntyped.flattenChunks;\n\n return flattenChunks(chunks);\n};\n\nvar Buf8 = function (size) {\n Buf8 = typedOK() ? fnTyped.Buf8 : fnUntyped.Buf8;\n return Buf8(size);\n};\n\nvar Buf16 = function (size) {\n Buf16 = typedOK() ? fnTyped.Buf16 : fnUntyped.Buf16;\n return Buf16(size);\n};\n\nvar Buf32 = function (size) {\n Buf32 = typedOK() ? fnTyped.Buf32 : fnUntyped.Buf32;\n return Buf32(size);\n};\n\n/* eslint-disable */\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\nvar strApplyOK = function() {\n var result = true;\n try {\n String.fromCharCode.apply(null, [ 0 ]);\n } catch (_) {\n result = false;\n }\n\n strApplyOK = function () { return result; };\n return result;\n};\n\nvar strApplyUintOK = function() {\n var result = true;\n try {\n String.fromCharCode.apply(null, new Uint8Array(1));\n } catch (_) {\n result = false;\n }\n\n strApplyUintOK = function () { return result; };\n return result;\n};\n\nvar utf8len = function(c) {\n // Table with utf8 lengths (calculated by first byte of sequence)\n // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n // because max possible codepoint is 0x10ffff\n var table = Buf8(256);\n for (var q = 0; q < 256; q++) {\n table[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n }\n table[254] = table[254] = 1; // Invalid sequence start\n\n utf8len = function (arg) { return table[arg]; };\n return table[c];\n};\n\n// convert string to array (typed, when possible)\nfunction string2buf(str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n}\n\n// Helper (used in 2 places)\nfunction _buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && strApplyUintOK()) || (!buf.subarray && strApplyOK())) {\n return String.fromCharCode.apply(null, shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nfunction buf2binstring(buf) {\n return _buf2binstring(buf, buf.length);\n}\n\n\n// Convert binary string (typed, when possible)\nfunction binstring2buf(str) {\n var buf = new Uint8Array(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n}\n\n\n// convert array to string\nfunction buf2string(buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = utf8len(c);\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return _buf2binstring(utf16buf, out);\n}\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nfunction utf8border(buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + utf8len(buf[pos]) > max) ? pos : max;\n}\n\n/* eslint-disable */\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n/* eslint-disable */\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\nvar crcTable = function() {\n var table = makeTable();\n crcTable = function () { return table; };\n return table;\n};\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable(),\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n/* eslint-disable */\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nfunction inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n}\n\n/* eslint-disable */\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nfunction inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n}\n\n/* eslint-disable */\n\nvar CODES$1 = 0;\nvar LENS$1 = 1;\nvar DISTS$1 = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH$1 = 4;\nvar Z_BLOCK$1 = 5;\nvar Z_TREES$1 = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK$1 = 0;\nvar Z_STREAM_END$1 = 1;\nvar Z_NEED_DICT$1 = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR$1 = -2;\nvar Z_DATA_ERROR$1 = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR$1 = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED$1 = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD$1 = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS$1 = 852;\nvar ENOUGH_DISTS$1 = 592;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = Buf16(320); /* temporary storage for code lengths */\n this.work = Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = Buf32(ENOUGH_LENS$1);\n state.distcode = state.distdyn = Buf32(ENOUGH_DISTS$1);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$1;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$1) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = Buf32(512);\n distfix = Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$1;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD$1;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED$1) {\n strm.msg = 'unknown compression method';\n state.mode = BAD$1;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD$1;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE$1;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED$1) {\n strm.msg = 'unknown compression method';\n state.mode = BAD$1;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD$1;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE$1;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT$1;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE$1;\n /* falls through */\n case TYPE$1:\n if (flush === Z_BLOCK$1 || flush === Z_TREES$1) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES$1) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD$1;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD$1;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES$1) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE$1;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD$1;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD$1;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD$1;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD$1;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD$1) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD$1;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD$1;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD$1;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES$1) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE$1) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE$1;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$1;\n break inf_leave;\n case BAD$1:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&\n (state.mode < CHECK || flush !== Z_FINISH$1))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE$1 ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n ret = Z_BUF_ERROR$1;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR$1;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$1;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$1;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$1;\n}\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n/* eslint-disable */\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar msg = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n/* eslint-disable */\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\n/* eslint-disable */\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\n/* eslint-disable */\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nvar Inflate = function Inflate(options) {\n if (!(this instanceof Inflate)) { return new Inflate(options); }\n\n this.options = assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended= false;// used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status= inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n};\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true);// push last chunk\n * ```\n **/\nInflate.prototype.push = function push (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n var dict;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate(strm, Z_NO_FLUSH); /* no bad return value */\n\n if (status === Z_NEED_DICT && dictionary) {\n // Convert data if needed\n if (typeof dictionary === 'string') {\n dict = string2buf(dictionary);\n } else if (toString.call(dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(dictionary);\n } else {\n dict = dictionary;\n }\n\n status = inflateSetDictionary(this.strm, dict);\n\n }\n\n if (status === Z_BUF_ERROR && allowBufError === true) {\n status = Z_OK;\n allowBufError = false;\n }\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n if (status === Z_STREAM_END) {\n _mode = Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function onData (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function onEnd (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\nvar ungzip = inflate$1;\n\n/* eslint-disable */\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nvar STORED_BLOCK = 0;\nvar STATIC_TREES = 1;\nvar DYN_TREES = 2;\n/* The three kinds of block type */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nvar D_CODES = 30;\n/* number of distance codes */\n\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nvar MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nvar END_BLOCK = 256;\n/* end of block literal code */\n\nvar REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nvar REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nvar REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nvar extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nvar extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nvar extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nvar bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nvar DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nvar static_ltree;\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nvar static_dtree;\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nvar _dist_code;\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nvar _length_code;\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nvar base_length;\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nvar base_dist;\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nvar static_l_desc;\nvar static_d_desc;\nvar static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n var res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var max_code = desc.max_code;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var extra = desc.stat_desc.extra_bits;\n var base = desc.stat_desc.extra_base;\n var max_length = desc.stat_desc.max_length;\n var h; /* heap index */\n var n, m; /* iterate over the tree elements */\n var bits; /* bit length */\n var xbits; /* extra bits */\n var f; /* frequency */\n var overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n var code = 0; /* running code value */\n var bits; /* bit index */\n var n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n var n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s)\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n var _n2 = n * 2;\n var _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n var v = s.heap[k];\n var j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n var dist; /* distance of matched string */\n var lc; /* match length or unmatched char (if dist == 0) */\n var lx = 0; /* running index in l_buf */\n var code; /* the code to send */\n var extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var elems = desc.stat_desc.elems;\n var n, m; /* iterate over heap elements */\n var max_code = -1; /* largest code with non zero frequency */\n var node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n var max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n var rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n var black_mask = 0xf3ffc07f;\n var n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nvar static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s) {\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last) {\n //DeflateState *s;\n //charf *buf; /* input block */\n //ulg stored_len; /* length of input block */\n //int last; /* one if this is the last block for a file */\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last) {\n //DeflateState *s;\n //charf *buf; /* input block, or NULL if too old */\n //ulg stored_len; /* length of input block */\n //int last; /* one if this is the last block for a file */\n var opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n var max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc) {\n // deflate_state *s;\n // unsigned dist; /* distance of matched string */\n // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\n/* eslint-disable */\n\nvar MAX_MEM_LEVEL = 9;\n\n\nvar LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nvar LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\nvar L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\nvar D_CODES$1 = 30;\n/* number of distance codes */\nvar BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\nvar HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\nvar MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar MIN_MATCH$1 = 3;\nvar MAX_MATCH$1 = 258;\nvar MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);\n\nvar PRESET_DICT = 0x20;\n\nvar INIT_STATE = 42;\nvar EXTRA_STATE = 69;\nvar NAME_STATE = 73;\nvar COMMENT_STATE = 91;\nvar HCRC_STATE = 103;\nvar BUSY_STATE = 113;\nvar FINISH_STATE = 666;\n\nvar BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nvar BS_BLOCK_DONE = 2; /* block flush performed */\nvar BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nvar BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nvar OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero$1(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n var s = strm.state;\n\n //_tr_flush_bits(s);\n var len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n// put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n var len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH$1;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH$1 - (strend - scan);\n scan = strend - MAX_MATCH$1;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n var _w_size = s.w_size;\n var p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH$1) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH$1) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// var curr = s.strstart + s.lookahead;\n// var init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n var max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n var max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n var hash_head; /* head of the hash chain */\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH$1) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH$1) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n var hash_head; /* head of hash chain */\n var bflush; /* set if current block must be flushed */\n\n var max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH$1) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH$1 - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH$1 - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH$1;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH$1 - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n var bflush; /* set if current block must be flushed */\n var prev; /* byte at distance one to match */\n var scan, strend; /* scan goes up to strend for length of run */\n\n var _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH$1) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH$1;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH$1 - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH$1) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nvar configurationTable = function() {\n var table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n \n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n ];\n\n configurationTable = function () { return table; };\n return table;\n};\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero$1(s.head); // Fill with NIL (= 0);\n\n var table = configurationTable();\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = table[s.level].max_lazy;\n s.good_match = table[s.level].good_length;\n s.nice_match = table[s.level].nice_length;\n s.max_chain_length = table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH$1 - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = Buf16(HEAP_SIZE$1 * 2);\n this.dyn_dtree = Buf16((2 * D_CODES$1 + 1) * 2);\n this.bl_tree = Buf16((2 * BL_CODES$1 + 1) * 2);\n zero$1(this.dyn_ltree);\n zero$1(this.dyn_dtree);\n zero$1(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = Buf16(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */\n zero$1(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];\n zero$1(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nfunction deflateResetKeep(strm) {\n var s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n _tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n var ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n var wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n var s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);\n\n s.window = Buf8(s.w_size * 2);\n s.head = Buf16(s.hash_size);\n s.prev = Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\n\nfunction deflate(strm, flush) {\n var old_flush, s;\n var beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n var level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configurationTable()[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero$1(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n var status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var s;\n var str, n;\n var wrap;\n var avail;\n var next;\n var input;\n var tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero$1(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = Buf8(s.w_size);\n arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH$1) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH$1 - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH$1 - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH$1 - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n\n/* eslint-disable */\n\nvar toString$1 = Object.prototype.toString;\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nvar Deflate = function Deflate(options) {\n this.options = assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended= false;// used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n var dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n};\n\n/**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true);// push last chunk\n * ```\n **/\nDeflate.prototype.push = function push (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = string2buf(data);\n } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n if (this.options.to === 'string') {\n this.onData(buf2binstring(shrinkBuf(strm.output, strm.next_out)));\n } else {\n this.onData(shrinkBuf(strm.output, strm.next_out));\n }\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate.prototype.onData = function onData (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate.prototype.onEnd = function onEnd (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n var deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || msg[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\nexport { Deflate, Inflate, Z_BEST_COMPRESSION, Z_BEST_SPEED, Z_BINARY, Z_BLOCK, Z_BUF_ERROR, Z_DATA_ERROR, Z_DEFAULT_COMPRESSION, Z_DEFAULT_STRATEGY, Z_DEFLATED, Z_ERRNO, Z_FILTERED, Z_FINISH, Z_FIXED, Z_FULL_FLUSH, Z_HUFFMAN_ONLY, Z_NEED_DICT, Z_NO_COMPRESSION, Z_NO_FLUSH, Z_OK, Z_PARTIAL_FLUSH, Z_RLE, Z_STREAM_END, Z_STREAM_ERROR, Z_SYNC_FLUSH, Z_TEXT, Z_TREES, Z_UNKNOWN, deflate$1 as deflate, deflateRaw, gzip, inflate$1 as inflate, inflateRaw, ungzip };\n","import { deflate as pakoDeflate } from '@progress/pako-esm';\n\nexport var deflate = pakoDeflate;\n\nexport function supportsDeflate() {\n return true;\n}\n\n","var fromCharCode = String.fromCharCode;\n\nexport var BOM = '\\xfe\\xff';\n\n// Encodes a string as UTF-8\nexport function encodeUTF8(input) {\n var output = \"\";\n\n for (var i = 0; i < input.length; i++) {\n var code = input.charCodeAt(i);\n\n if (0xD800 <= code && code <= 0xDBFF) {\n var hi = code;\n var low = input.charCodeAt(++i);\n\n if (!isNaN(low)) {\n // Combine high and low surrogate\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt\n code = (hi - 0xD800) * 0x400 +\n (low - 0xDC00) + 0x10000;\n }\n }\n\n if (code < 0x80) {\n // One byte\n output += fromCharCode(code);\n } else if (code < 0x800) {\n // Two bytes\n output += fromCharCode(0xC0 | (code >>> 6));\n output += fromCharCode(0x80 | (code & 0x3f));\n } else if (code < 0x10000) {\n // Three bytes\n output += fromCharCode(0xE0 | (code >>> 12));\n output += fromCharCode(0x80 | (code >>> 6 & 0x3f));\n output += fromCharCode(0x80 | (code & 0x3f));\n } else if (code < 0x10FFFF) {\n // Four bytes\n output += fromCharCode(0xF0 | (code >>> 18));\n output += fromCharCode(0x80 | (code >>> 12 & 0x3f));\n output += fromCharCode(0x80 | (code >>> 6 & 0x3f));\n output += fromCharCode(0x80 | (code & 0x3f));\n }\n }\n\n return output;\n}\n\nfunction encodeUnit(codeUnit) {\n return fromCharCode(codeUnit >> 8) + fromCharCode(codeUnit & 0x00ff);\n}\n\n// Encodes a string as UTF-16 big-endian\nexport function encodeUTF16BE(input) {\n var output = '';\n\n for (var i = 0; i < input.length; i++) {\n var c = input.charCodeAt(i);\n\n if (c < 0xFFFF) {\n output += encodeUnit(c);\n } else {\n var lead = ((c - 0x10000) >> 10) + 0xD800;\n var trail = ((c - 0x10000) & 0x3FF) + 0xDC00;\n output += encodeUnit(lead);\n output += encodeUnit(trail);\n }\n }\n\n return output;\n}\n","/* eslint-disable no-multi-spaces, key-spacing, indent, camelcase, space-before-blocks, eqeqeq, brace-style */\n/* eslint-disable space-infix-ops, space-before-function-paren, array-bracket-spacing, object-curly-spacing */\n/* eslint-disable no-nested-ternary, max-params, default-case, no-else-return, no-empty */\n/* eslint-disable no-param-reassign, no-var, block-scoped-var */\n\nimport { BinaryStream, ucs2encode, base64ToUint8Array, HAS_TYPED_ARRAYS } from \"./utils\";\nimport { support } from '../common';\nimport { TTFFont } from \"./ttf\";\nimport { deflate, supportsDeflate } from './deflate';\nimport { encodeUTF16BE, BOM } from \"../util/encode-utf\";\n\nvar browser = support.browser;\nvar NL = \"\\n\";\n\nvar RESOURCE_COUNTER = 0;\n\nvar PAPER_SIZE = {\n a0 : [ 2383.94 , 3370.39 ],\n a1 : [ 1683.78 , 2383.94 ],\n a2 : [ 1190.55 , 1683.78 ],\n a3 : [ 841.89 , 1190.55 ],\n a4 : [ 595.28 , 841.89 ],\n a5 : [ 419.53 , 595.28 ],\n a6 : [ 297.64 , 419.53 ],\n a7 : [ 209.76 , 297.64 ],\n a8 : [ 147.40 , 209.76 ],\n a9 : [ 104.88 , 147.40 ],\n a10 : [ 73.70 , 104.88 ],\n b0 : [ 2834.65 , 4008.19 ],\n b1 : [ 2004.09 , 2834.65 ],\n b2 : [ 1417.32 , 2004.09 ],\n b3 : [ 1000.63 , 1417.32 ],\n b4 : [ 708.66 , 1000.63 ],\n b5 : [ 498.90 , 708.66 ],\n b6 : [ 354.33 , 498.90 ],\n b7 : [ 249.45 , 354.33 ],\n b8 : [ 175.75 , 249.45 ],\n b9 : [ 124.72 , 175.75 ],\n b10 : [ 87.87 , 124.72 ],\n c0 : [ 2599.37 , 3676.54 ],\n c1 : [ 1836.85 , 2599.37 ],\n c2 : [ 1298.27 , 1836.85 ],\n c3 : [ 918.43 , 1298.27 ],\n c4 : [ 649.13 , 918.43 ],\n c5 : [ 459.21 , 649.13 ],\n c6 : [ 323.15 , 459.21 ],\n c7 : [ 229.61 , 323.15 ],\n c8 : [ 161.57 , 229.61 ],\n c9 : [ 113.39 , 161.57 ],\n c10 : [ 79.37 , 113.39 ],\n executive : [ 521.86 , 756.00 ],\n folio : [ 612.00 , 936.00 ],\n legal : [ 612.00 , 1008.00 ],\n letter : [ 612.00 , 792.00 ],\n tabloid : [ 792.00 , 1224.00 ]\n};\n\nfunction makeOutput() {\n var indentLevel = 0, output = BinaryStream();\n function out() {\n var arguments$1 = arguments;\n\n for (var i = 0; i < arguments.length; ++i) {\n var x = arguments$1[i];\n if (x === undefined) {\n throw new Error(\"Cannot output undefined to PDF\");\n }\n else if (x instanceof PDFValue) {\n x.beforeRender(out);\n x.render(out);\n }\n else if (isArray(x)) {\n renderArray(x, out);\n }\n else if (isDate(x)) {\n renderDate(x, out);\n }\n else if (typeof x == \"number\") {\n if (isNaN(x)) {\n throw new Error(\"Cannot output NaN to PDF\");\n }\n // make sure it doesn't end up in exponent notation\n var num = x.toFixed(7);\n if (num.indexOf(\".\") >= 0) {\n num = num.replace(/\\.?0+$/, \"\");\n }\n if (num == \"-0\") {\n num = \"0\";\n }\n output.writeString(num);\n }\n else if (/string|boolean/.test(typeof x)) {\n output.writeString(String(x));\n }\n else if (typeof x.get == \"function\") {\n output.write(x.get());\n }\n else if (typeof x == \"object\") {\n if (!x) {\n output.writeString(\"null\");\n } else {\n out(new PDFDictionary(x));\n }\n }\n }\n }\n out.writeData = function(data) {\n output.write(data);\n };\n out.withIndent = function(f) {\n ++indentLevel;\n f(out);\n --indentLevel;\n };\n out.indent = function() {\n out(NL, pad(\"\", indentLevel * 2, \" \"));\n out.apply(null, arguments);\n };\n out.offset = function() {\n return output.offset();\n };\n out.toString = function() {\n throw new Error(\"FIX CALLER\");\n };\n out.get = function() {\n return output.get();\n };\n out.stream = function() {\n return output;\n };\n return out;\n}\n\nfunction wrapObject(value, id) {\n var beforeRender = value.beforeRender;\n var renderValue = value.render;\n\n value.beforeRender = function(){};\n\n value.render = function(out) {\n out(id, \" 0 R\");\n };\n\n value.renderFull = function(out) {\n value._offset = out.offset();\n out(id, \" 0 obj \");\n beforeRender.call(value, out);\n renderValue.call(value, out);\n out(\" endobj\");\n };\n}\n\nfunction getPaperOptions(getOption) {\n if (typeof getOption != \"function\") {\n var options = getOption;\n getOption = function(key, def) {\n return key in options ? options[key] : def;\n };\n }\n var paperSize = getOption(\"paperSize\", PAPER_SIZE.a4);\n if (!paperSize) {\n return {};\n }\n if (typeof paperSize == \"string\") {\n paperSize = PAPER_SIZE[paperSize.toLowerCase()];\n if (paperSize == null) {\n throw new Error(\"Unknown paper size\");\n }\n }\n\n paperSize[0] = unitsToPoints(paperSize[0]);\n paperSize[1] = unitsToPoints(paperSize[1]);\n\n if (getOption(\"landscape\", false)) {\n paperSize = [\n Math.max(paperSize[0], paperSize[1]),\n Math.min(paperSize[0], paperSize[1])\n ];\n }\n\n var margin = getOption(\"margin\");\n if (margin) {\n if (typeof margin == \"string\" || typeof margin == \"number\") {\n margin = unitsToPoints(margin, 0);\n margin = { left: margin, top: margin, right: margin, bottom: margin };\n } else {\n margin = {\n left : unitsToPoints(margin.left, 0),\n top : unitsToPoints(margin.top, 0),\n right : unitsToPoints(margin.right, 0),\n bottom : unitsToPoints(margin.bottom, 0)\n };\n }\n if (getOption(\"addMargin\")) {\n paperSize[0] += margin.left + margin.right;\n paperSize[1] += margin.top + margin.bottom;\n }\n }\n return { paperSize: paperSize, margin: margin };\n}\n\nvar FONT_CACHE = {\n \"Times-Roman\" : true,\n \"Times-Bold\" : true,\n \"Times-Italic\" : true,\n \"Times-BoldItalic\" : true,\n \"Helvetica\" : true,\n \"Helvetica-Bold\" : true,\n \"Helvetica-Oblique\" : true,\n \"Helvetica-BoldOblique\" : true,\n \"Courier\" : true,\n \"Courier-Bold\" : true,\n \"Courier-Oblique\" : true,\n \"Courier-BoldOblique\" : true,\n \"Symbol\" : true,\n \"ZapfDingbats\" : true\n};\n\nfunction loadBinary(url, cont) {\n // IE throws Accesss denied error for Data URIs\n var m;\n if (browser.msie && (m = /^data:.*?;base64,/i.exec(url))) {\n cont(base64ToUint8Array(url.substr(m[0].length)));\n return;\n }\n\n function error() {\n if (window.console) {\n if (window.console.error) {\n window.console.error(\"Cannot load URL: %s\", url);\n } else {\n window.console.log(\"Cannot load URL: %s\", url);\n }\n }\n cont(null);\n }\n var req = new XMLHttpRequest();\n req.open('GET', url, true);\n if (HAS_TYPED_ARRAYS) {\n req.responseType = \"arraybuffer\";\n }\n req.onload = function() {\n if (req.status == 200 || req.status == 304) {\n if (HAS_TYPED_ARRAYS) {\n cont(new Uint8Array(req.response));\n } else {\n cont(new window.VBArray(req.responseBody).toArray()); // IE9 only\n }\n } else {\n error();\n }\n };\n req.onerror = error;\n req.send(null);\n}\n\nfunction loadFont(url, cont) {\n var font = FONT_CACHE[url];\n if (font) {\n cont(font);\n } else {\n loadBinary(url, function(data){\n if (data == null) {\n throw new Error(\"Cannot load font from \" + url);\n } else {\n var font = new TTFFont(data);\n FONT_CACHE[url] = font;\n cont(font);\n }\n });\n }\n}\n\nvar IMAGE_CACHE = {};\n\nfunction clearImageCache() {\n IMAGE_CACHE = {};\n}\n\nfunction loadImage(url, size, cont, options) {\n var img = IMAGE_CACHE[url], bloburl, blob;\n if (img) {\n cont(img);\n } else {\n img = new Image();\n if (!(/^data:/i.test(url))) {\n img.crossOrigin = \"Anonymous\";\n }\n if (HAS_TYPED_ARRAYS && !(/^data:/i.test(url))) {\n // IE10 fails to load images from another domain even when the server sends the\n // proper CORS headers. a XHR, however, will be able to load the data.\n // http://stackoverflow.com/a/19734516/154985\n //\n // On the other hand, it's worth doing it this way for all browsers which support\n // responseType = \"blob\" (HAS_TYPED_ARRAYS will be true), because we can inspect the\n // mime type and if it's a JPEG (very common case) we can save a lot of time in\n // _load below.\n var xhr = new XMLHttpRequest();\n xhr.onload = function() {\n blob = xhr.response;\n bloburl = URL.createObjectURL(blob);\n _load(bloburl);\n };\n xhr.onerror = _onerror;\n xhr.open(\"GET\", url, true);\n xhr.responseType = \"blob\";\n xhr.send();\n } else {\n _load(url);\n }\n }\n\n function _load(url) {\n img.src = url;\n if (img.complete && !browser.msie) {\n // IE, bless it's little heart, says img.complete == true even though the image is\n // not loaded (width=0), therefore we must go the onload route (ticket 929635).\n _onload.call(img);\n } else {\n img.onload = _onload;\n img.onerror = _onerror;\n }\n }\n\n function _trycanvas() {\n if (!size) {\n size = { width: img.width, height: img.height };\n }\n\n var canvas = document.createElement(\"canvas\");\n canvas.width = size.width;\n canvas.height = size.height;\n\n var ctx = canvas.getContext(\"2d\");\n ctx.drawImage(img, 0, 0, size.width, size.height);\n\n var imgdata;\n try {\n imgdata = ctx.getImageData(0, 0, size.width, size.height);\n } catch (ex) {\n // it tainted the canvas -- can't draw it.\n _onerror();\n return;\n } finally {\n if (bloburl) {\n URL.revokeObjectURL(bloburl);\n }\n }\n\n // in case it contains transparency, we must separate rgb data from the alpha\n // channel and create a PDFRawImage image with opacity. otherwise we can use a\n // PDFJpegImage.\n //\n // to do this in one step, we create the rgb and alpha streams anyway, even if\n // we might end up not using them if hasAlpha remains false.\n\n var hasAlpha = false, rgb = BinaryStream(), alpha = BinaryStream();\n var rawbytes = imgdata.data;\n var i = 0;\n while (i < rawbytes.length) {\n rgb.writeByte(rawbytes[i++]);\n rgb.writeByte(rawbytes[i++]);\n rgb.writeByte(rawbytes[i++]);\n var a = rawbytes[i++];\n if (a < 255) {\n hasAlpha = true;\n }\n alpha.writeByte(a);\n }\n\n if (hasAlpha || options.keepPNG) {\n img = new PDFRawImage(size.width, size.height, rgb, alpha);\n } else {\n // no transparency, encode as JPEG.\n var data = canvas.toDataURL(\"image/jpeg\", options.jpegQuality);\n data = data.substr(data.indexOf(\";base64,\") + 8);\n\n var stream = BinaryStream();\n stream.writeBase64(data);\n img = new PDFJpegImage(stream);\n }\n\n cont(IMAGE_CACHE[url] = img);\n }\n\n function _onerror() {\n cont(IMAGE_CACHE[url] = \"ERROR\");\n }\n\n function _onload() {\n if (size) {\n var svg = (blob && blob.type === 'image/svg+xml') || (\n /^data:image\\/svg\\+xml;/i.test(this.src.substring(0, 19))\n );\n\n var upscale = size.width >= img.width || size.height >= img.height;\n\n // Use the original image if requested size is bigger than the source,\n // unless it's an SVG that can be upscaled.\n if (!svg && upscale) {\n size = null;\n }\n }\n if (!size && blob && /^image\\/jpe?g$/i.test(blob.type)) {\n // If we know we got a JPEG, we can skip the process of rendering it to a\n // canvas, getting the pixel data, searching for transparency we know we won't\n // find, getting back a data URI and then decoding the BASE64 to finally get the\n // binary we already have. Also, we avoid downgrading the image quality, with\n // the possible drawback of making a bigger PDF; still, seems legit.\n //\n // Besides saving a lot of work, this also reuses the buffer memory\n // (BinaryStream does not create a copy), potentially saving some GC cycles.\n var reader = new FileReader();\n reader.onload = function() {\n try {\n var img = new PDFJpegImage(BinaryStream(new Uint8Array(this.result)));\n URL.revokeObjectURL(bloburl);\n cont(IMAGE_CACHE[url] = img);\n } catch (ex) {\n // if there's an error parsing the JPEG stream, it could be due to a\n // misconfigured server (improper content-type:\n // https://github.com/telerik/kendo-ui-core/issues/4184). If that's the case,\n // the canvas will still be able to draw it.\n _trycanvas();\n }\n };\n reader.readAsArrayBuffer(blob);\n } else {\n _trycanvas();\n }\n }\n}\n\nfunction manyLoader(loadOne) {\n return function(urls, callback) {\n var n = urls.length, i = n;\n if (n === 0) {\n return callback();\n }\n function next() {\n if (--n === 0) {\n callback();\n }\n }\n while (i-- > 0) {\n loadOne(urls[i], next);\n }\n };\n}\n\nvar loadFonts = manyLoader(loadFont);\nvar loadImages = function(images, callback, options) {\n options = Object.assign({\n jpegQuality : 0.92,\n keepPNG : false\n }, options);\n var urls = Object.keys(images), n = urls.length;\n if (n === 0) {\n return callback();\n }\n function next() {\n if (--n === 0) {\n callback();\n }\n }\n urls.forEach(function(url){\n loadImage(url, images[url], next, options);\n });\n};\n\nvar PDFDocument = function PDFDocument (options) {\n var self = this;\n var out = makeOutput();\n var objcount = 0;\n var objects = [];\n\n function getOption(name, defval) {\n return (options && options[name] != null) ? options[name] : defval;\n }\n\n self.getOption = getOption;\n\n self.attach = function(value) {\n if (objects.indexOf(value) < 0) {\n wrapObject(value, ++objcount);\n objects.push(value);\n }\n return value;\n };\n\n self.pages = [];\n\n self.FONTS = {};\n self.IMAGES = {};\n self.GRAD_COL_FUNCTIONS = {}; // cache for color gradient functions\n self.GRAD_OPC_FUNCTIONS = {}; // cache for opacity gradient functions\n self.GRAD_COL = {}; // cache for whole color gradient objects\n self.GRAD_OPC = {}; // cache for whole opacity gradient objects\n\n var catalog = self.attach(new PDFCatalog());\n var pageTree = self.attach(new PDFPageTree());\n\n if (getOption(\"autoPrint\")) {\n var nameTree = {};\n nameTree.JavaScript = new PDFDictionary({ Names: [\n new PDFString(\"JS\"), self.attach(new PDFDictionary({\n S: _(\"JavaScript\"),\n JS: new PDFString(\"print(true);\")\n }))\n ] });\n catalog.props.Names = new PDFDictionary(nameTree);\n }\n\n catalog.setPages(pageTree);\n\n var info = self.attach(new PDFDictionary({\n Producer : new PDFString(getOption(\"producer\", \"Kendo UI PDF Generator\"), true), // XXX: kendo.version?\n Title : new PDFString(getOption(\"title\", \"\"), true),\n Author : new PDFString(getOption(\"author\", \"\"), true),\n Subject : new PDFString(getOption(\"subject\", \"\"), true),\n Keywords : new PDFString(getOption(\"keywords\", \"\"), true),\n Creator : new PDFString(getOption(\"creator\", \"Kendo UI PDF Generator\"), true),\n CreationDate : getOption(\"date\", new Date())\n }));\n\n self.addPage = function(options) {\n var paperOptions = getPaperOptions(function(name, defval){\n return (options && options[name] != null) ? options[name] : defval;\n });\n var paperSize = paperOptions.paperSize;\n var margin = paperOptions.margin;\n var contentWidth = paperSize[0];\n var contentHeight = paperSize[1];\n if (margin) {\n contentWidth -= margin.left + margin.right;\n contentHeight -= margin.top + margin.bottom;\n }\n var content = new PDFStream(makeOutput(), null, true);\n var props = {\n Contents : self.attach(content),\n Parent : pageTree,\n MediaBox : [ 0, 0, paperSize[0], paperSize[1] ]\n };\n var page = new PDFPage(self, props);\n page._content = content;\n pageTree.addPage(self.attach(page));\n\n // canvas-like coord. system. (0,0) is upper-left.\n // text must be vertically mirorred before drawing.\n page.transform(1, 0, 0, -1, 0, paperSize[1]);\n\n if (margin) {\n page.translate(margin.left, margin.top);\n // XXX: clip to right/bottom margin. Make this optional?\n page.rect(0, 0, contentWidth, contentHeight);\n page.clip();\n }\n\n self.pages.push(page);\n return page;\n };\n\n self.render = function() {\n var i;\n /// file header\n out(\"%PDF-1.4\", NL, \"%\\xc2\\xc1\\xda\\xcf\\xce\", NL, NL);\n\n /// file body\n for (i = 0; i < objects.length; ++i) {\n objects[i].renderFull(out);\n out(NL, NL);\n }\n\n /// cross-reference table\n var xrefOffset = out.offset();\n out(\"xref\", NL, 0, \" \", objects.length + 1, NL);\n out(\"0000000000 65535 f \", NL);\n for (i = 0; i < objects.length; ++i) {\n out(zeropad(objects[i]._offset, 10), \" 00000 n \", NL);\n }\n out(NL);\n\n /// trailer\n out(\"trailer\", NL);\n out(new PDFDictionary({\n Size: objects.length + 1,\n Root: catalog,\n Info: info\n }), NL, NL);\n\n /// end\n out(\"startxref\", NL, xrefOffset, NL);\n out(\"%%EOF\", NL);\n\n return out.stream().offset(0);\n };\n\n self.loadFonts = loadFonts;\n self.loadImages = loadImages;\n};\n\nPDFDocument.prototype.getFont = function getFont (url) {\n var font = this.FONTS[url];\n if (!font) {\n font = FONT_CACHE[url];\n if (!font) {\n throw new Error(\"Font \" + url + \" has not been loaded\");\n }\n if (font === true) {\n font = this.attach(new PDFStandardFont(url));\n } else {\n font = this.attach(new PDFFont(this, font));\n }\n this.FONTS[url] = font;\n }\n return font;\n};\n\nPDFDocument.prototype.getImage = function getImage (url) {\n var img = this.IMAGES[url];\n if (!img) {\n img = IMAGE_CACHE[url];\n if (!img) {\n throw new Error(\"Image \" + url + \" has not been loaded\");\n }\n if (img === \"ERROR\") {\n return null;\n }\n img = this.IMAGES[url] = this.attach(img.asStream(this));\n }\n return img;\n};\n\nPDFDocument.prototype.getOpacityGS = function getOpacityGS (opacity, forStroke) {\n var id = parseFloat(opacity).toFixed(3);\n opacity = parseFloat(id);\n id += forStroke ? \"S\" : \"F\";\n var cache = this._opacityGSCache || (this._opacityGSCache = {});\n var gs = cache[id];\n if (!gs) {\n var props = {\n Type: _(\"ExtGState\")\n };\n if (forStroke) {\n props.CA = opacity;\n } else {\n props.ca = opacity;\n }\n gs = this.attach(new PDFDictionary(props));\n gs._resourceName = _(\"GS\" + (++RESOURCE_COUNTER));\n cache[id] = gs;\n }\n return gs;\n};\n\nPDFDocument.prototype.dict = function dict (props) {\n return new PDFDictionary(props);\n};\n\nPDFDocument.prototype.name = function name (str) {\n return _(str);\n};\n\nPDFDocument.prototype.stream = function stream (props, content) {\n return new PDFStream(content, props);\n};\n\n/* -----[ utils ]----- */\n\nfunction pad(str, len, ch) {\n while (str.length < len) {\n str = ch + str;\n }\n return str;\n}\n\nfunction zeropad(n, len) {\n return pad(String(n), len, \"0\");\n}\n\nfunction hasOwnProperty(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nvar isArray = Array.isArray || function(obj) {\n return obj instanceof Array;\n};\n\nfunction isDate(obj) {\n return obj instanceof Date;\n}\n\nfunction renderArray(a, out) {\n out(\"[\");\n if (a.length > 0) {\n out.withIndent(function(){\n for (var i = 0; i < a.length; ++i) {\n if (i > 0 && i % 8 === 0) {\n out.indent(a[i]);\n } else {\n out(\" \", a[i]);\n }\n }\n });\n //out.indent();\n }\n out(\" ]\");\n}\n\nfunction renderDate(date, out) {\n out(\"(D:\",\n zeropad(date.getUTCFullYear(), 4),\n zeropad(date.getUTCMonth() + 1, 2),\n zeropad(date.getUTCDate(), 2),\n zeropad(date.getUTCHours(), 2),\n zeropad(date.getUTCMinutes(), 2),\n zeropad(date.getUTCSeconds(), 2),\n \"Z)\");\n}\n\nfunction mm2pt(mm) {\n return mm * (72/25.4);\n}\n\nfunction cm2pt(cm) {\n return mm2pt(cm * 10);\n}\n\nfunction in2pt(inch) {\n return inch * 72;\n}\n\n\nfunction unitsToPoints(x, def) {\n if (typeof x == \"number\") {\n return x;\n }\n if (typeof x == \"string\") {\n var m;\n m = /^\\s*([0-9.]+)\\s*(mm|cm|in|pt)\\s*$/.exec(x);\n if (m) {\n var num = parseFloat(m[1]);\n if (!isNaN(num)) {\n if (m[2] == \"pt\") {\n return num;\n }\n return {\n \"mm\": mm2pt,\n \"cm\": cm2pt,\n \"in\": in2pt\n }[m[2]](num);\n }\n }\n }\n if (def != null) {\n return def;\n }\n throw new Error(\"Can't parse unit: \" + x);\n}\n\n/* -----[ PDF basic objects ]----- */\n\nvar PDFValue = function PDFValue () {};\n\nPDFValue.prototype.beforeRender = function beforeRender () {};\n\nvar PDFString = (function (PDFValue) {\n function PDFString(value, utf16be) {\n PDFValue.call(this);\n this.value = value;\n this.utf16be = Boolean(utf16be);\n }\n\n if ( PDFValue ) PDFString.__proto__ = PDFValue;\n PDFString.prototype = Object.create( PDFValue && PDFValue.prototype );\n PDFString.prototype.constructor = PDFString;\n\n PDFString.prototype.render = function render (out) {\n var txt = this.value;\n if (this.utf16be) {\n txt = BOM + encodeUTF16BE(txt);\n txt = txt.replace(/([\\(\\)\\\\])/g, \"\\\\$1\");\n out(\"(\", txt, \")\");\n } else {\n // out.writeString truncates charcodes to 8 bits and\n // 0x128 & 0xFF is 40, the code for open paren.\n // therefore we need to do the chopping here to make\n // sure we backslash all cases.\n var data = [ 40 ]; // open PDF string '('\n for (var i = 0; i < txt.length; ++i) {\n var code = txt.charCodeAt(i) & 0xFF;\n if (code == 40 || code == 41 || code == 92) {\n // backslash before (, ) and \\\n data.push(92);\n }\n data.push(code);\n }\n data.push(41); // ')' close PDF string\n out.writeData(data);\n }\n };\n\n PDFString.prototype.toString = function toString () {\n return this.value;\n };\n\n return PDFString;\n}(PDFValue));\n\nvar PDFHexString = (function (PDFString) {\n function PDFHexString(value) {\n PDFString.call(this, value);\n this.value = value;\n }\n\n if ( PDFString ) PDFHexString.__proto__ = PDFString;\n PDFHexString.prototype = Object.create( PDFString && PDFString.prototype );\n PDFHexString.prototype.constructor = PDFHexString;\n\n PDFHexString.prototype.render = function render (out) {\n var this$1 = this;\n\n out(\"<\");\n for (var i = 0; i < this.value.length; ++i) {\n out(zeropad(this$1.value.charCodeAt(i).toString(16), 4));\n }\n out(\">\");\n };\n\n return PDFHexString;\n}(PDFString));\n\n/// names\nvar PDFName = (function (PDFValue) {\n function PDFName(name) {\n PDFValue.call(this);\n this.name = name;\n }\n\n if ( PDFValue ) PDFName.__proto__ = PDFValue;\n PDFName.prototype = Object.create( PDFValue && PDFValue.prototype );\n PDFName.prototype.constructor = PDFName;\n\n PDFName.get = function get (name) {\n return _(name);\n };\n\n PDFName.prototype.render = function render (out) {\n out(\"/\" + this.escape());\n };\n\n PDFName.prototype.escape = function escape () {\n return this.name.replace(/[^\\x21-\\x7E]/g, function(c){\n return \"#\" + zeropad(c.charCodeAt(0).toString(16), 2);\n });\n };\n\n PDFName.prototype.toString = function toString () {\n return this.name;\n };\n\n return PDFName;\n}(PDFValue));\n\nvar PDFName_cache = {};\n\nfunction _(name) {\n if (hasOwnProperty(PDFName_cache, name)) {\n return PDFName_cache[name];\n }\n return (PDFName_cache[name] = new PDFName(name));\n}\n\n/// dictionary\n\nvar PDFDictionary = (function (PDFValue) {\n function PDFDictionary(props) {\n PDFValue.call(this);\n this.props = props;\n }\n\n if ( PDFValue ) PDFDictionary.__proto__ = PDFValue;\n PDFDictionary.prototype = Object.create( PDFValue && PDFValue.prototype );\n PDFDictionary.prototype.constructor = PDFDictionary;\n\n PDFDictionary.prototype.render = function render (out) {\n var props = this.props, empty = true;\n out(\"<<\");\n out.withIndent(function(){\n for (var i in props) {\n if (hasOwnProperty(props, i) && !/^_/.test(i)) {\n empty = false;\n out.indent(_(i), \" \", props[i]);\n }\n }\n });\n if (!empty) {\n out.indent();\n }\n out(\">>\");\n };\n\n return PDFDictionary;\n}(PDFValue));\n\n/// streams\n\nvar PDFStream = (function (PDFValue) {\n function PDFStream(data, props, compress) {\n PDFValue.call(this);\n if (typeof data == \"string\") {\n var tmp = BinaryStream();\n tmp.write(data);\n data = tmp;\n }\n this.data = data;\n this.props = props || {};\n this.compress = compress;\n }\n\n if ( PDFValue ) PDFStream.__proto__ = PDFValue;\n PDFStream.prototype = Object.create( PDFValue && PDFValue.prototype );\n PDFStream.prototype.constructor = PDFStream;\n\n PDFStream.prototype.render = function render (out) {\n var data = this.data.get(), props = this.props;\n if (this.compress && supportsDeflate()) {\n if (!props.Filter) {\n props.Filter = [];\n } else if (!(props.Filter instanceof Array)) {\n props.Filter = [ props.Filter ];\n }\n props.Filter.unshift(_(\"FlateDecode\"));\n data = deflate(data);\n }\n props.Length = data.length;\n out(new PDFDictionary(props), \" stream\", NL);\n out.writeData(data);\n out(NL, \"endstream\");\n };\n\n return PDFStream;\n}(PDFValue));\n\n/// catalog\n\nvar PDFCatalog = (function (PDFDictionary) {\n function PDFCatalog() {\n PDFDictionary.call(this, {\n Type: _(\"Catalog\")\n });\n }\n\n if ( PDFDictionary ) PDFCatalog.__proto__ = PDFDictionary;\n PDFCatalog.prototype = Object.create( PDFDictionary && PDFDictionary.prototype );\n PDFCatalog.prototype.constructor = PDFCatalog;\n\n PDFCatalog.prototype.setPages = function setPages (pagesObj) {\n this.props.Pages = pagesObj;\n };\n\n return PDFCatalog;\n}(PDFDictionary));\n\n/// page tree\n\nvar PDFPageTree = (function (PDFDictionary) {\n function PDFPageTree() {\n PDFDictionary.call(this, {\n Type : _(\"Pages\"),\n Kids : [],\n Count : 0\n });\n }\n\n if ( PDFDictionary ) PDFPageTree.__proto__ = PDFDictionary;\n PDFPageTree.prototype = Object.create( PDFDictionary && PDFDictionary.prototype );\n PDFPageTree.prototype.constructor = PDFPageTree;\n\n PDFPageTree.prototype.addPage = function addPage (pageObj) {\n this.props.Kids.push(pageObj);\n this.props.Count++;\n };\n\n return PDFPageTree;\n}(PDFDictionary));\n\n/// images\n\n// JPEG\n\nvar SOF_CODES = [0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf];\n\nvar PDFJpegImage = function PDFJpegImage(data) {\n // we must determine the correct color space. we'll parse a bit\n // of the JPEG stream for this, it's still better than going\n // through the canvas.\n // https://github.com/telerik/kendo-ui-core/issues/2845\n data.offset(0);\n var width, height, colorSpace, bitsPerComponent;\n var soi = data.readShort();\n if (soi != 0xFFD8) {\n // XXX: do we have some better options here?\n throw new Error(\"Invalid JPEG image\");\n }\n while (!data.eof()) {\n var ff = data.readByte();\n if (ff != 0xFF) {\n throw new Error(\"Invalid JPEG image\");\n }\n var marker = data.readByte();\n var length = data.readShort();\n if (SOF_CODES.indexOf(marker) >= 0) {\n // \"start of frame\" marker\n bitsPerComponent = data.readByte();\n height = data.readShort();\n width = data.readShort();\n colorSpace = data.readByte();\n break;\n }\n data.skip(length - 2);\n }\n\n if (colorSpace == null) {\n throw new Error(\"Invalid JPEG image\");\n }\n\n var props = {\n Type : _(\"XObject\"),\n Subtype : _(\"Image\"),\n Width : width,\n Height : height,\n BitsPerComponent : bitsPerComponent,\n Filter : _(\"DCTDecode\")\n };\n\n switch (colorSpace) {\n case 1:\n props.ColorSpace = _(\"DeviceGray\");\n break;\n case 3:\n props.ColorSpace = _(\"DeviceRGB\");\n break;\n case 4:\n props.ColorSpace = _(\"DeviceCMYK\");\n props.Decode = [ 1, 0, 1, 0, 1, 0, 1, 0 ]; // invert colors\n break;\n }\n\n this.asStream = function() {\n data.offset(0);\n var stream = new PDFStream(data, props);\n stream._resourceName = _(\"I\" + (++RESOURCE_COUNTER));\n return stream;\n };\n};\n\n// PDFRawImage will be used for images with transparency (PNG)\n\nvar PDFRawImage = function PDFRawImage(width, height, rgb, alpha) {\n this.asStream = function(pdf) {\n var mask = new PDFStream(alpha, {\n Type : _(\"XObject\"),\n Subtype : _(\"Image\"),\n Width : width,\n Height : height,\n BitsPerComponent : 8,\n ColorSpace : _(\"DeviceGray\")\n }, true);\n var stream = new PDFStream(rgb, {\n Type : _(\"XObject\"),\n Subtype : _(\"Image\"),\n Width : width,\n Height : height,\n BitsPerComponent : 8,\n ColorSpace : _(\"DeviceRGB\"),\n SMask : pdf.attach(mask)\n }, true);\n stream._resourceName = _(\"I\" + (++RESOURCE_COUNTER));\n return stream;\n };\n};\n\n/// standard fonts\n\nvar PDFStandardFont = (function (PDFDictionary) {\n function PDFStandardFont(name){\n PDFDictionary.call(this, {\n Type : _(\"Font\"),\n Subtype : _(\"Type1\"),\n BaseFont : _(name)\n });\n\n this._resourceName = _(\"F\" + (++RESOURCE_COUNTER));\n }\n\n if ( PDFDictionary ) PDFStandardFont.__proto__ = PDFDictionary;\n PDFStandardFont.prototype = Object.create( PDFDictionary && PDFDictionary.prototype );\n PDFStandardFont.prototype.constructor = PDFStandardFont;\n\n PDFStandardFont.prototype.encodeText = function encodeText (str) {\n return new PDFString(String(str));\n };\n\n return PDFStandardFont;\n}(PDFDictionary));\n\n/// TTF fonts\n\nvar PDFFont = (function (PDFDictionary) {\n function PDFFont(pdf, font, props){\n PDFDictionary.call(this, {});\n\n props = this.props;\n props.Type = _(\"Font\");\n props.Subtype = _(\"Type0\");\n props.Encoding = _(\"Identity-H\");\n\n this._pdf = pdf;\n this._font = font;\n this._sub = font.makeSubset();\n this._resourceName = _(\"F\" + (++RESOURCE_COUNTER));\n\n var head = font.head;\n\n this.name = font.psName;\n var scale = this.scale = font.scale;\n this.bbox = [\n head.xMin * scale,\n head.yMin * scale,\n head.xMax * scale,\n head.yMax * scale\n ];\n\n this.italicAngle = font.post.italicAngle;\n this.ascent = font.ascent * scale;\n this.descent = font.descent * scale;\n this.lineGap = font.lineGap * scale;\n this.capHeight = font.os2.capHeight || this.ascent;\n this.xHeight = font.os2.xHeight || 0;\n this.stemV = 0;\n\n this.familyClass = (font.os2.familyClass || 0) >> 8;\n this.isSerif = this.familyClass >= 1 && this.familyClass <= 7;\n this.isScript = this.familyClass == 10;\n\n this.flags = ((font.post.isFixedPitch ? 1 : 0) |\n (this.isSerif ? 1 << 1 : 0) |\n (this.isScript ? 1 << 3 : 0) |\n (this.italicAngle !== 0 ? 1 << 6 : 0) |\n (1 << 5));\n }\n\n if ( PDFDictionary ) PDFFont.__proto__ = PDFDictionary;\n PDFFont.prototype = Object.create( PDFDictionary && PDFDictionary.prototype );\n PDFFont.prototype.constructor = PDFFont;\n\n PDFFont.prototype.encodeText = function encodeText (text) {\n return new PDFHexString(this._sub.encodeText(String(text)));\n };\n\n PDFFont.prototype.getTextWidth = function getTextWidth (fontSize, text) {\n var this$1 = this;\n\n var width = 0, codeMap = this._font.cmap.codeMap;\n for (var i = 0; i < text.length; ++i) {\n var glyphId = codeMap[text.charCodeAt(i)];\n width += this$1._font.widthOfGlyph(glyphId || 0);\n }\n return width * fontSize / 1000;\n };\n\n PDFFont.prototype.beforeRender = function beforeRender () {\n var self = this;\n var sub = self._sub;\n\n // write the TTF data\n var data = sub.render();\n var fontStream = new PDFStream(BinaryStream(data), {\n Length1: data.length\n }, true);\n\n var descriptor = self._pdf.attach(new PDFDictionary({\n Type : _(\"FontDescriptor\"),\n FontName : _(self._sub.psName),\n FontBBox : self.bbox,\n Flags : self.flags,\n StemV : self.stemV,\n ItalicAngle : self.italicAngle,\n Ascent : self.ascent,\n Descent : self.descent,\n CapHeight : self.capHeight,\n XHeight : self.xHeight,\n FontFile2 : self._pdf.attach(fontStream)\n }));\n\n var cmap = sub.ncid2ogid;\n var firstChar = sub.firstChar;\n var lastChar = sub.lastChar;\n var charWidths = [];\n (function loop(i, chunk){\n if (i <= lastChar) {\n var gid = cmap[i];\n if (gid == null) {\n loop(i + 1);\n } else {\n if (!chunk) {\n charWidths.push(i, chunk = []);\n }\n chunk.push(self._font.widthOfGlyph(gid));\n loop(i + 1, chunk);\n }\n }\n })(firstChar);\n\n // As if two dictionaries weren't enough, we need another\n // one, the \"descendant font\". Only that one can be of\n // Subtype CIDFontType2. PDF is the X11 of document\n // formats: portable but full of legacy that nobody cares\n // about anymore.\n\n var descendant = new PDFDictionary({\n Type: _(\"Font\"),\n Subtype: _(\"CIDFontType2\"),\n BaseFont: _(self._sub.psName),\n CIDSystemInfo: new PDFDictionary({\n Registry : new PDFString(\"Adobe\"),\n Ordering : new PDFString(\"Identity\"),\n Supplement : 0\n }),\n FontDescriptor: descriptor,\n FirstChar: firstChar,\n LastChar: lastChar,\n DW: Math.round(self._font.widthOfGlyph(0)),\n W: charWidths,\n CIDToGIDMap: self._pdf.attach(self._makeCidToGidMap())\n });\n\n var dict = self.props;\n dict.BaseFont = _(self._sub.psName);\n dict.DescendantFonts = [ self._pdf.attach(descendant) ];\n\n // Compute the ToUnicode map so that apps can extract\n // meaningful text from the PDF.\n var unimap = new PDFToUnicodeCmap(firstChar, lastChar, sub.subset);\n var unimapStream = new PDFStream(makeOutput(), null, true);\n unimapStream.data(unimap);\n dict.ToUnicode = self._pdf.attach(unimapStream);\n };\n\n PDFFont.prototype._makeCidToGidMap = function _makeCidToGidMap () {\n return new PDFStream(BinaryStream(this._sub.cidToGidMap()), null, true);\n };\n\n return PDFFont;\n}(PDFDictionary));\n\nvar PDFToUnicodeCmap = (function (PDFValue) {\n function PDFToUnicodeCmap(firstChar, lastChar, map){\n PDFValue.call(this);\n this.firstChar = firstChar;\n this.lastChar = lastChar;\n this.map = map;\n }\n\n if ( PDFValue ) PDFToUnicodeCmap.__proto__ = PDFValue;\n PDFToUnicodeCmap.prototype = Object.create( PDFValue && PDFValue.prototype );\n PDFToUnicodeCmap.prototype.constructor = PDFToUnicodeCmap;\n\n PDFToUnicodeCmap.prototype.render = function render (out) {\n out.indent(\"/CIDInit /ProcSet findresource begin\");\n out.indent(\"12 dict begin\");\n out.indent(\"begincmap\");\n out.indent(\"/CIDSystemInfo <<\");\n out.indent(\" /Registry (Adobe)\");\n out.indent(\" /Ordering (UCS)\");\n out.indent(\" /Supplement 0\");\n out.indent(\">> def\");\n out.indent(\"/CMapName /Adobe-Identity-UCS def\");\n out.indent(\"/CMapType 2 def\");\n out.indent(\"1 begincodespacerange\");\n out.indent(\" <0000>\");\n out.indent(\"endcodespacerange\");\n\n var self = this;\n out.indent(self.lastChar - self.firstChar + 1, \" beginbfchar\");\n out.withIndent(function(){\n for (var code = self.firstChar; code <= self.lastChar; ++code) {\n var unicode = self.map[code];\n var str = ucs2encode([ unicode ]);\n out.indent(\"<\", zeropad(code.toString(16), 4), \">\", \"<\");\n for (var i = 0; i < str.length; ++i) {\n out(zeropad(str.charCodeAt(i).toString(16), 4));\n }\n out(\">\");\n }\n });\n out.indent(\"endbfchar\");\n\n out.indent(\"endcmap\");\n out.indent(\"CMapName currentdict /CMap defineresource pop\");\n out.indent(\"end\");\n out.indent(\"end\");\n };\n\n return PDFToUnicodeCmap;\n}(PDFValue));\n\n/// gradients\n\nfunction makeHash(a) {\n return a.map(function(x){\n return isArray(x) ? makeHash(x)\n : typeof x == \"number\" ? (Math.round(x * 1000) / 1000).toFixed(3)\n : x;\n }).join(\" \");\n}\n\nfunction cacheColorGradientFunction(pdf, r1, g1, b1, r2, g2, b2) {\n var hash = makeHash([ r1, g1, b1, r2, g2, b2 ]);\n var func = pdf.GRAD_COL_FUNCTIONS[hash];\n if (!func) {\n func = pdf.GRAD_COL_FUNCTIONS[hash] = pdf.attach(new PDFDictionary({\n FunctionType: 2,\n Domain: [ 0, 1 ],\n Range: [ 0, 1, 0, 1, 0, 1 ],\n N: 1,\n C0: [ r1 , g1 , b1 ],\n C1: [ r2 , g2 , b2 ]\n }));\n }\n return func;\n}\n\nfunction cacheOpacityGradientFunction(pdf, a1, a2) {\n var hash = makeHash([ a1, a2 ]);\n var func = pdf.GRAD_OPC_FUNCTIONS[hash];\n if (!func) {\n func = pdf.GRAD_OPC_FUNCTIONS[hash] = pdf.attach(new PDFDictionary({\n FunctionType: 2,\n Domain: [ 0, 1 ],\n Range: [ 0, 1 ],\n N: 1,\n C0: [ a1 ],\n C1: [ a2 ]\n }));\n }\n return func;\n}\n\nfunction makeGradientFunctions(pdf, stops) {\n var hasAlpha = false;\n var opacities = [];\n var colors = [];\n var offsets = [];\n var encode = [];\n var i, prev, cur, prevColor, curColor;\n for (i = 1; i < stops.length; ++i) {\n prev = stops[i - 1];\n cur = stops[i];\n prevColor = prev.color;\n curColor = cur.color;\n colors.push(cacheColorGradientFunction(\n pdf,\n prevColor.r, prevColor.g, prevColor.b,\n curColor.r, curColor.g, curColor.b\n ));\n if (prevColor.a < 1 || curColor.a < 1) {\n hasAlpha = true;\n }\n offsets.push(cur.offset);\n encode.push(0, 1);\n }\n if (hasAlpha) {\n for (i = 1; i < stops.length; ++i) {\n prev = stops[i - 1];\n cur = stops[i];\n prevColor = prev.color;\n curColor = cur.color;\n opacities.push(cacheOpacityGradientFunction(\n pdf, prevColor.a, curColor.a\n ));\n }\n }\n offsets.pop();\n return {\n hasAlpha : hasAlpha,\n colors : assemble(colors),\n opacities : hasAlpha ? assemble(opacities) : null\n };\n function assemble(funcs) {\n if (funcs.length == 1) {\n return funcs[0];\n }\n return {\n FunctionType: 3,\n Functions: funcs,\n Domain: [ 0, 1 ],\n Bounds: offsets,\n Encode: encode\n };\n }\n}\n\nfunction cacheColorGradient(pdf, isRadial, stops, coords, funcs, box) {\n var shading, hash;\n // if box is given then we have user-space coordinates, which\n // means the gradient is designed for a certain position/size\n // on page. caching won't do any good.\n if (!box) {\n var a = [ isRadial ].concat(coords);\n stops.forEach(function(x){\n a.push(x.offset, x.color.r, x.color.g, x.color.b);\n });\n hash = makeHash(a);\n shading = pdf.GRAD_COL[hash];\n }\n if (!shading) {\n shading = new PDFDictionary({\n Type: _(\"Shading\"),\n ShadingType: isRadial ? 3 : 2,\n ColorSpace: _(\"DeviceRGB\"),\n Coords: coords,\n Domain: [ 0, 1 ],\n Function: funcs,\n Extend: [ true, true ]\n });\n pdf.attach(shading);\n shading._resourceName = \"S\" + (++RESOURCE_COUNTER);\n if (hash) {\n pdf.GRAD_COL[hash] = shading;\n }\n }\n return shading;\n}\n\nfunction cacheOpacityGradient(pdf, isRadial, stops, coords, funcs, box) {\n var opacity, hash;\n // if box is given then we have user-space coordinates, which\n // means the gradient is designed for a certain position/size\n // on page. caching won't do any good.\n if (!box) {\n var a = [ isRadial ].concat(coords);\n stops.forEach(function(x){\n a.push(x.offset, x.color.a);\n });\n hash = makeHash(a);\n opacity = pdf.GRAD_OPC[hash];\n }\n if (!opacity) {\n opacity = new PDFDictionary({\n Type: _(\"ExtGState\"),\n AIS: false,\n CA: 1,\n ca: 1,\n SMask: {\n Type: _(\"Mask\"),\n S: _(\"Luminosity\"),\n G: pdf.attach(new PDFStream(\"/a0 gs /s0 sh\", {\n Type: _(\"XObject\"),\n Subtype: _(\"Form\"),\n FormType: 1,\n BBox: (box ? [\n box.left, box.top + box.height, box.left + box.width, box.top\n ] : [ 0, 1, 1, 0 ]),\n Group: {\n Type: _(\"Group\"),\n S: _(\"Transparency\"),\n CS: _(\"DeviceGray\"),\n I: true\n },\n Resources: {\n ExtGState: {\n a0: { CA: 1, ca: 1 }\n },\n Shading: {\n s0: {\n ColorSpace: _(\"DeviceGray\"),\n Coords: coords,\n Domain: [ 0, 1 ],\n ShadingType: isRadial ? 3 : 2,\n Function: funcs,\n Extend: [ true, true ]\n }\n }\n }\n }))\n }\n });\n pdf.attach(opacity);\n opacity._resourceName = \"O\" + (++RESOURCE_COUNTER);\n if (hash) {\n pdf.GRAD_OPC[hash] = opacity;\n }\n }\n return opacity;\n}\n\nfunction cacheGradient(pdf, gradient, box) {\n var isRadial = gradient.type == \"radial\";\n var funcs = makeGradientFunctions(pdf, gradient.stops);\n var coords = isRadial ? [\n gradient.start.x , gradient.start.y , gradient.start.r,\n gradient.end.x , gradient.end.y , gradient.end.r\n ] : [\n gradient.start.x , gradient.start.y,\n gradient.end.x , gradient.end.y\n ];\n var shading = cacheColorGradient(\n pdf, isRadial, gradient.stops, coords, funcs.colors, gradient.userSpace && box\n );\n var opacity = funcs.hasAlpha ? cacheOpacityGradient(\n pdf, isRadial, gradient.stops, coords, funcs.opacities, gradient.userSpace && box\n ) : null;\n return {\n hasAlpha: funcs.hasAlpha,\n shading: shading,\n opacity: opacity\n };\n}\n\n/// page object\n\nvar PDFPage = (function (PDFDictionary) {\n function PDFPage(pdf, props){\n PDFDictionary.call(this, props);\n\n this._pdf = pdf;\n this._rcount = 0;\n this._textMode = false;\n this._fontResources = {};\n this._gsResources = {};\n this._xResources = {};\n this._patResources = {};\n this._shResources = {};\n this._opacity = 1;\n this._matrix = [ 1, 0, 0, 1, 0, 0 ];\n this._annotations = [];\n\n this._font = null;\n this._fontSize = null;\n\n this._contextStack = [];\n\n props = this.props;\n props.Type = _(\"Page\");\n props.ProcSet = [\n _(\"PDF\"),\n _(\"Text\"),\n _(\"ImageB\"),\n _(\"ImageC\"),\n _(\"ImageI\")\n ];\n props.Resources = new PDFDictionary({\n Font : new PDFDictionary(this._fontResources),\n ExtGState : new PDFDictionary(this._gsResources),\n XObject : new PDFDictionary(this._xResources),\n Pattern : new PDFDictionary(this._patResources),\n Shading : new PDFDictionary(this._shResources)\n });\n props.Annots = this._annotations;\n }\n\n if ( PDFDictionary ) PDFPage.__proto__ = PDFDictionary;\n PDFPage.prototype = Object.create( PDFDictionary && PDFDictionary.prototype );\n PDFPage.prototype.constructor = PDFPage;\n\n PDFPage.prototype._out = function _out () {\n this._content.data.apply(null, arguments);\n };\n\n PDFPage.prototype.transform = function transform (a, b, c, d, e, f) {\n if (!isIdentityMatrix(arguments)) {\n this._matrix = mmul(arguments, this._matrix);\n this._out(a, \" \", b, \" \", c, \" \", d, \" \", e, \" \", f, \" cm\");\n // XXX: debug\n // this._out(\" % current matrix: \", this._matrix);\n this._out(NL);\n }\n };\n\n PDFPage.prototype.translate = function translate (dx, dy) {\n this.transform(1, 0, 0, 1, dx, dy);\n };\n\n PDFPage.prototype.scale = function scale (sx, sy) {\n this.transform(sx, 0, 0, sy, 0, 0);\n };\n\n PDFPage.prototype.rotate = function rotate (angle) {\n var cos = Math.cos(angle), sin = Math.sin(angle);\n this.transform(cos, sin, -sin, cos, 0, 0);\n };\n\n PDFPage.prototype.beginText = function beginText () {\n this._textMode = true;\n this._out(\"BT\", NL);\n };\n\n PDFPage.prototype.endText = function endText () {\n this._textMode = false;\n this._out(\"ET\", NL);\n };\n\n PDFPage.prototype._requireTextMode = function _requireTextMode () {\n if (!this._textMode) {\n throw new Error(\"Text mode required; call page.beginText() first\");\n }\n };\n\n PDFPage.prototype._requireFont = function _requireFont () {\n if (!this._font) {\n throw new Error(\"No font selected; call page.setFont() first\");\n }\n };\n\n PDFPage.prototype.setFont = function setFont (font, size) {\n this._requireTextMode();\n if (font == null) {\n font = this._font;\n } else if (!(font instanceof PDFFont)) {\n font = this._pdf.getFont(font);\n }\n if (size == null) {\n size = this._fontSize;\n }\n this._fontResources[font._resourceName] = font;\n this._font = font;\n this._fontSize = size;\n this._out(font._resourceName, \" \", size, \" Tf\", NL);\n };\n\n PDFPage.prototype.setTextLeading = function setTextLeading (size) {\n this._requireTextMode();\n this._out(size, \" TL\", NL);\n };\n\n PDFPage.prototype.setTextRenderingMode = function setTextRenderingMode (mode) {\n this._requireTextMode();\n this._out(mode, \" Tr\", NL);\n };\n\n PDFPage.prototype.showText = function showText (text, requestedWidth) {\n this._requireFont();\n if (text.length > 1 && requestedWidth && this._font instanceof PDFFont) {\n var outputWidth = this._font.getTextWidth(this._fontSize, text);\n var scale = requestedWidth / outputWidth * 100;\n this._out(scale, \" Tz \");\n }\n this._out(this._font.encodeText(text), \" Tj\", NL);\n };\n\n PDFPage.prototype.showTextNL = function showTextNL (text) {\n this._requireFont();\n this._out(this._font.encodeText(text), \" '\", NL);\n };\n\n PDFPage.prototype.addLink = function addLink (uri, box) {\n var ll = this._toPage({ x: box.left, y: box.bottom });\n var ur = this._toPage({ x: box.right, y: box.top });\n this._annotations.push(new PDFDictionary({\n Type : _(\"Annot\"),\n Subtype : _(\"Link\"),\n Rect : [ ll.x, ll.y, ur.x, ur.y ],\n Border : [ 0, 0, 0 ],\n A : new PDFDictionary({\n Type : _(\"Action\"),\n S : _(\"URI\"),\n URI : new PDFString(uri)\n })\n }));\n };\n\n PDFPage.prototype.setStrokeColor = function setStrokeColor (r, g, b) {\n this._out(r, \" \", g, \" \", b, \" RG\", NL);\n };\n\n PDFPage.prototype.setOpacity = function setOpacity (opacity) {\n this.setFillOpacity(opacity);\n this.setStrokeOpacity(opacity);\n this._opacity *= opacity;\n };\n\n PDFPage.prototype.setStrokeOpacity = function setStrokeOpacity (opacity) {\n if (opacity < 1) {\n var gs = this._pdf.getOpacityGS(this._opacity * opacity, true);\n this._gsResources[gs._resourceName] = gs;\n this._out(gs._resourceName, \" gs\", NL);\n }\n };\n\n PDFPage.prototype.setFillColor = function setFillColor (r, g, b) {\n this._out(r, \" \", g, \" \", b, \" rg\", NL);\n };\n\n PDFPage.prototype.setFillOpacity = function setFillOpacity (opacity) {\n if (opacity < 1) {\n var gs = this._pdf.getOpacityGS(this._opacity * opacity, false);\n this._gsResources[gs._resourceName] = gs;\n this._out(gs._resourceName, \" gs\", NL);\n }\n };\n\n PDFPage.prototype.gradient = function gradient (gradient$1, box) {\n this.save();\n this.rect(box.left, box.top, box.width, box.height);\n this.clip();\n if (!gradient$1.userSpace) {\n this.transform(box.width, 0, 0, box.height, box.left, box.top);\n }\n var g = cacheGradient(this._pdf, gradient$1, box);\n var sname = g.shading._resourceName, oname;\n this._shResources[sname] = g.shading;\n if (g.hasAlpha) {\n oname = g.opacity._resourceName;\n this._gsResources[oname] = g.opacity;\n this._out(\"/\" + oname + \" gs \");\n }\n this._out(\"/\" + sname + \" sh\", NL);\n this.restore();\n };\n\n PDFPage.prototype.setDashPattern = function setDashPattern (dashArray, dashPhase) {\n this._out(dashArray, \" \", dashPhase, \" d\", NL);\n };\n\n PDFPage.prototype.setLineWidth = function setLineWidth (width) {\n this._out(width, \" w\", NL);\n };\n\n PDFPage.prototype.setLineCap = function setLineCap (lineCap) {\n this._out(lineCap, \" J\", NL);\n };\n\n PDFPage.prototype.setLineJoin = function setLineJoin (lineJoin) {\n this._out(lineJoin, \" j\", NL);\n };\n\n PDFPage.prototype.setMitterLimit = function setMitterLimit (mitterLimit) {\n this._out(mitterLimit, \" M\", NL);\n };\n\n PDFPage.prototype.save = function save () {\n this._contextStack.push(this._context());\n this._out(\"q\", NL);\n };\n\n PDFPage.prototype.restore = function restore () {\n this._out(\"Q\", NL);\n this._context(this._contextStack.pop());\n };\n\n\n // paths\n PDFPage.prototype.moveTo = function moveTo (x, y) {\n this._out(x, \" \", y, \" m\", NL);\n };\n\n PDFPage.prototype.lineTo = function lineTo (x, y) {\n this._out(x, \" \", y, \" l\", NL);\n };\n\n PDFPage.prototype.bezier = function bezier (x1, y1, x2, y2, x3, y3) {\n this._out(x1, \" \", y1, \" \", x2, \" \", y2, \" \", x3, \" \", y3, \" c\", NL);\n };\n\n PDFPage.prototype.bezier1 = function bezier1 (x1, y1, x3, y3) {\n this._out(x1, \" \", y1, \" \", x3, \" \", y3, \" y\", NL);\n };\n\n PDFPage.prototype.bezier2 = function bezier2 (x2, y2, x3, y3) {\n this._out(x2, \" \", y2, \" \", x3, \" \", y3, \" v\", NL);\n };\n\n PDFPage.prototype.close = function close () {\n this._out(\"h\", NL);\n };\n\n PDFPage.prototype.rect = function rect (x, y, w, h) {\n this._out(x, \" \", y, \" \", w, \" \", h, \" re\", NL);\n };\n\n PDFPage.prototype.ellipse = function ellipse (x, y, rx, ry) {\n function _X(v) { return x + v; }\n function _Y(v) { return y + v; }\n\n // how to get to the \"magic number\" is explained here:\n // http://www.whizkidtech.redprince.net/bezier/circle/kappa/\n var k = 0.5522847498307936;\n\n this.moveTo(_X(0), _Y(ry));\n this.bezier(\n _X(rx * k) , _Y(ry),\n _X(rx) , _Y(ry * k),\n _X(rx) , _Y(0)\n );\n this.bezier(\n _X(rx) , _Y(-ry * k),\n _X(rx * k) , _Y(-ry),\n _X(0) , _Y(-ry)\n );\n this.bezier(\n _X(-rx * k) , _Y(-ry),\n _X(-rx) , _Y(-ry * k),\n _X(-rx) , _Y(0)\n );\n this.bezier(\n _X(-rx) , _Y(ry * k),\n _X(-rx * k) , _Y(ry),\n _X(0) , _Y(ry)\n );\n };\n\n PDFPage.prototype.circle = function circle (x, y, r) {\n this.ellipse(x, y, r, r);\n };\n\n PDFPage.prototype.stroke = function stroke () {\n this._out(\"S\", NL);\n };\n\n PDFPage.prototype.nop = function nop () {\n this._out(\"n\", NL);\n };\n\n PDFPage.prototype.clip = function clip () {\n this._out(\"W n\", NL);\n };\n\n PDFPage.prototype.clipStroke = function clipStroke () {\n this._out(\"W S\", NL);\n };\n\n PDFPage.prototype.closeStroke = function closeStroke () {\n this._out(\"s\", NL);\n };\n\n PDFPage.prototype.fill = function fill () {\n this._out(\"f\", NL);\n };\n\n PDFPage.prototype.fillStroke = function fillStroke () {\n this._out(\"B\", NL);\n };\n\n PDFPage.prototype.drawImage = function drawImage (url) {\n var img = this._pdf.getImage(url);\n if (img) { // the result can be null for a cross-domain image\n this._xResources[img._resourceName] = img;\n this._out(img._resourceName, \" Do\", NL);\n }\n };\n\n PDFPage.prototype.comment = function comment (txt) {\n var self = this;\n txt.split(/\\r?\\n/g).forEach(function(line){\n self._out(\"% \", line, NL);\n });\n };\n\n // internal\n PDFPage.prototype._context = function _context (val) {\n if (val != null) {\n this._opacity = val.opacity;\n this._matrix = val.matrix;\n } else {\n return {\n opacity: this._opacity,\n matrix: this._matrix\n };\n }\n };\n\n PDFPage.prototype._toPage = function _toPage (p) {\n var m = this._matrix;\n var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];\n return {\n x: a*p.x + c*p.y + e,\n y: b*p.x + d*p.y + f\n };\n };\n\n return PDFPage;\n}(PDFDictionary));\n\nfunction unquote(str) {\n return str.replace(/^\\s*(['\"])(.*)\\1\\s*$/, \"$2\");\n}\n\nfunction parseFontDef(fontdef) {\n // XXX: this is very crude for now and buggy. Proper parsing is quite involved.\n var rx = /^\\s*((normal|italic)\\s+)?((normal|small-caps)\\s+)?((normal|bold|\\d+)\\s+)?(([0-9.]+)(px|pt))(\\/(([0-9.]+)(px|pt)|normal))?\\s+(.*?)\\s*$/i;\n var m = rx.exec(fontdef);\n if (!m) {\n return { fontSize: 12, fontFamily: \"sans-serif\" };\n }\n var fontSize = m[8] ? parseInt(m[8], 10) : 12;\n return {\n italic : m[2] && m[2].toLowerCase() == \"italic\",\n variant : m[4],\n bold : m[6] && /bold|700/i.test(m[6]),\n fontSize : fontSize,\n lineHeight : m[12] ? m[12] == \"normal\" ? fontSize : parseInt(m[12], 10) : null,\n fontFamily : m[14].split(/\\s*,\\s*/g).map(unquote)\n };\n}\n\nfunction getFontURL(style) {\n function mkFamily(name) {\n if (style.bold) {\n name += \"|bold\";\n }\n if (style.italic) {\n name += \"|italic\";\n }\n return name.toLowerCase();\n }\n var fontFamily = style.fontFamily;\n var name, url;\n if (fontFamily instanceof Array) {\n for (var i = 0; i < fontFamily.length; ++i) {\n name = mkFamily(fontFamily[i]);\n url = FONT_MAPPINGS[name];\n if (url) {\n break;\n }\n }\n } else {\n url = FONT_MAPPINGS[fontFamily.toLowerCase()];\n }\n while (typeof url == \"function\") {\n url = url();\n }\n if (!url) {\n url = \"Times-Roman\";\n }\n return url;\n}\n\nvar FONT_MAPPINGS = {\n \"serif\" : \"Times-Roman\",\n \"serif|bold\" : \"Times-Bold\",\n \"serif|italic\" : \"Times-Italic\",\n \"serif|bold|italic\" : \"Times-BoldItalic\",\n \"sans-serif\" : \"Helvetica\",\n \"sans-serif|bold\" : \"Helvetica-Bold\",\n \"sans-serif|italic\" : \"Helvetica-Oblique\",\n \"sans-serif|bold|italic\" : \"Helvetica-BoldOblique\",\n \"monospace\" : \"Courier\",\n \"monospace|bold\" : \"Courier-Bold\",\n \"monospace|italic\" : \"Courier-Oblique\",\n \"monospace|bold|italic\" : \"Courier-BoldOblique\",\n \"zapfdingbats\" : \"ZapfDingbats\",\n \"zapfdingbats|bold\" : \"ZapfDingbats\",\n \"zapfdingbats|italic\" : \"ZapfDingbats\",\n \"zapfdingbats|bold|italic\" : \"ZapfDingbats\"\n};\n\nfunction fontAlias(alias, name) {\n alias = alias.toLowerCase();\n FONT_MAPPINGS[alias] = function() {\n return FONT_MAPPINGS[name];\n };\n FONT_MAPPINGS[alias + \"|bold\"] = function() {\n return FONT_MAPPINGS[name + \"|bold\"];\n };\n FONT_MAPPINGS[alias + \"|italic\"] = function() {\n return FONT_MAPPINGS[name + \"|italic\"];\n };\n FONT_MAPPINGS[alias + \"|bold|italic\"] = function() {\n return FONT_MAPPINGS[name + \"|bold|italic\"];\n };\n}\n\n// Let's define some common names to an appropriate replacement.\n// These are overridable via pdf.defineFont, should the user want to\n// include the proper versions.\n\nfontAlias(\"Times New Roman\" , \"serif\");\nfontAlias(\"Courier New\" , \"monospace\");\nfontAlias(\"Arial\" , \"sans-serif\");\nfontAlias(\"Helvetica\" , \"sans-serif\");\nfontAlias(\"Verdana\" , \"sans-serif\");\nfontAlias(\"Tahoma\" , \"sans-serif\");\nfontAlias(\"Georgia\" , \"sans-serif\");\nfontAlias(\"Monaco\" , \"monospace\");\nfontAlias(\"Andale Mono\" , \"monospace\");\n\nfunction defineFont(name, url) {\n if (arguments.length == 1) {\n for (var i in name) {\n if (hasOwnProperty(name, i)) {\n defineFont(i, name[i]);\n }\n }\n } else {\n name = name.toLowerCase();\n FONT_MAPPINGS[name] = url;\n\n // special handling for DejaVu fonts: if they get defined,\n // let them also replace the default families, for good\n // Unicode support out of the box.\n switch (name) {\n case \"dejavu sans\" : FONT_MAPPINGS[\"sans-serif\"] = url; break;\n case \"dejavu sans|bold\" : FONT_MAPPINGS[\"sans-serif|bold\"] = url; break;\n case \"dejavu sans|italic\" : FONT_MAPPINGS[\"sans-serif|italic\"] = url; break;\n case \"dejavu sans|bold|italic\" : FONT_MAPPINGS[\"sans-serif|bold|italic\"] = url; break;\n case \"dejavu serif\" : FONT_MAPPINGS[\"serif\"] = url; break;\n case \"dejavu serif|bold\" : FONT_MAPPINGS[\"serif|bold\"] = url; break;\n case \"dejavu serif|italic\" : FONT_MAPPINGS[\"serif|italic\"] = url; break;\n case \"dejavu serif|bold|italic\" : FONT_MAPPINGS[\"serif|bold|italic\"] = url; break;\n case \"dejavu mono\" : FONT_MAPPINGS[\"monospace\"] = url; break;\n case \"dejavu mono|bold\" : FONT_MAPPINGS[\"monospace|bold\"] = url; break;\n case \"dejavu mono|italic\" : FONT_MAPPINGS[\"monospace|italic\"] = url; break;\n case \"dejavu mono|bold|italic\" : FONT_MAPPINGS[\"monospace|bold|italic\"] = url; break;\n }\n }\n}\n\nfunction mmul(a, b) {\n var a1 = a[0], b1 = a[1], c1 = a[2], d1 = a[3], e1 = a[4], f1 = a[5];\n var a2 = b[0], b2 = b[1], c2 = b[2], d2 = b[3], e2 = b[4], f2 = b[5];\n return [\n a1*a2 + b1*c2, a1*b2 + b1*d2,\n c1*a2 + d1*c2, c1*b2 + d1*d2,\n e1*a2 + f1*c2 + e2, e1*b2 + f1*d2 + f2\n ];\n}\n\nfunction isIdentityMatrix(m) {\n return m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;\n}\n\nvar TEXT_RENDERING_MODE = {\n fill : 0,\n stroke : 1,\n fillAndStroke : 2,\n invisible : 3,\n fillAndClip : 4,\n strokeAndClip : 5,\n fillStrokeClip : 6,\n clip : 7\n};\n\nexport {\n PDFDocument as Document,\n BinaryStream,\n defineFont,\n parseFontDef,\n getFontURL,\n loadFonts,\n loadImages,\n getPaperOptions,\n clearImageCache,\n TEXT_RENDERING_MODE\n};\n","export default function createPromise() {\n var resolveFn, rejectFn;\n var promise = new Promise(function (resolve, reject) {\n resolveFn = function (data) {\n promise._state = \"resolved\";\n resolve(data);\n return promise;\n };\n rejectFn = function (data) {\n promise._state = \"rejected\";\n reject(data);\n\n return promise;\n };\n });\n promise._state = \"pending\";\n promise.resolve = resolveFn;\n promise.reject = rejectFn;\n promise.state = function () { return promise._state; };\n\n return promise;\n}\n","import { Class } from '../common';\n\nvar LRUCache = (function (Class) {\n function LRUCache(size) {\n Class.call(this);\n\n this._size = size;\n this._length = 0;\n this._map = {};\n }\n\n if ( Class ) LRUCache.__proto__ = Class;\n LRUCache.prototype = Object.create( Class && Class.prototype );\n LRUCache.prototype.constructor = LRUCache;\n\n LRUCache.prototype.put = function put (key, value) {\n var map = this._map;\n var entry = { key: key, value: value };\n\n map[key] = entry;\n\n if (!this._head) {\n this._head = this._tail = entry;\n } else {\n this._tail.newer = entry;\n entry.older = this._tail;\n this._tail = entry;\n }\n\n if (this._length >= this._size) {\n map[this._head.key] = null;\n this._head = this._head.newer;\n this._head.older = null;\n } else {\n this._length++;\n }\n };\n\n LRUCache.prototype.get = function get (key) {\n var entry = this._map[key];\n\n if (entry) {\n if (entry === this._head && entry !== this._tail) {\n this._head = entry.newer;\n this._head.older = null;\n }\n\n if (entry !== this._tail) {\n if (entry.older) {\n entry.older.newer = entry.newer;\n entry.newer.older = entry.older;\n }\n\n entry.older = this._tail;\n entry.newer = null;\n\n this._tail.newer = entry;\n this._tail = entry;\n }\n\n return entry.value;\n }\n };\n\n return LRUCache;\n}(Class));\n\nexport default LRUCache;","var REPLACE_REGEX = /\\r?\\n|\\r|\\t/g;\nvar SPACE = ' ';\n\nfunction normalizeText(text) {\n return String(text).replace(REPLACE_REGEX, SPACE);\n}\n\nfunction objectKey(object) {\n var parts = [];\n for (var key in object) {\n parts.push(key + object[key]);\n }\n\n return parts.sort().join(\"\");\n}\n\n// Computes FNV-1 hash\n// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function\nfunction hashKey(str) {\n // 32-bit FNV-1 offset basis\n // See http://isthe.com/chongo/tech/comp/fnv/#FNV-param\n var hash = 0x811C9DC5;\n\n for (var i = 0; i < str.length; ++i) {\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n hash ^= str.charCodeAt(i);\n }\n\n return hash >>> 0;\n}\n\nexport { objectKey, hashKey, normalizeText };","import LRUCache from './lru-cache';\nimport { Class } from '../common';\nimport { objectKey, hashKey, normalizeText } from './util';\n\nfunction zeroSize() {\n return { width: 0, height: 0, baseline: 0 };\n}\n\nvar DEFAULT_OPTIONS = {\n baselineMarkerSize: 1\n};\n\nvar defaultMeasureBox;\n\nif (typeof document !== \"undefined\") {\n defaultMeasureBox = document.createElement(\"div\");\n defaultMeasureBox.style.cssText = \"position: absolute !important; top: -4000px !important; width: auto !important; height: auto !important;\" +\n \"padding: 0 !important; margin: 0 !important; border: 0 !important;\" +\n \"line-height: normal !important; visibility: hidden !important; white-space: pre!important;\";\n}\n\nvar TextMetrics = (function (Class) {\n function TextMetrics(options) {\n Class.call(this);\n\n this._cache = new LRUCache(1000);\n this.options = Object.assign({}, DEFAULT_OPTIONS, options);\n }\n\n if ( Class ) TextMetrics.__proto__ = Class;\n TextMetrics.prototype = Object.create( Class && Class.prototype );\n TextMetrics.prototype.constructor = TextMetrics;\n\n TextMetrics.prototype.measure = function measure (text, style, options) {\n if ( options === void 0 ) options = {};\n\n if (typeof text === 'undefined' || text === null) {\n return zeroSize();\n }\n\n var styleKey = objectKey(style);\n var cacheKey = hashKey(text + styleKey);\n var cachedResult = this._cache.get(cacheKey);\n\n if (cachedResult) {\n return cachedResult;\n }\n\n var size = zeroSize();\n var measureBox = options.box || defaultMeasureBox;\n var baselineMarker = this._baselineMarker().cloneNode(false);\n\n for (var key in style) {\n var value = style[key];\n if (typeof value !== \"undefined\") {\n measureBox.style[key] = value;\n }\n }\n\n var textStr = options.normalizeText !== false ? normalizeText(text) : String(text);\n\n measureBox.textContent = textStr;\n measureBox.appendChild(baselineMarker);\n document.body.appendChild(measureBox);\n\n if (textStr.length) {\n size.width = measureBox.offsetWidth - this.options.baselineMarkerSize;\n size.height = measureBox.offsetHeight;\n size.baseline = baselineMarker.offsetTop + this.options.baselineMarkerSize;\n }\n\n if (size.width > 0 && size.height > 0) {\n this._cache.put(cacheKey, size);\n }\n\n measureBox.parentNode.removeChild(measureBox);\n\n return size;\n };\n\n TextMetrics.prototype._baselineMarker = function _baselineMarker () {\n var marker = document.createElement(\"div\");\n marker.style.cssText = \"display: inline-block; vertical-align: baseline;width: \" +\n this.options.baselineMarkerSize + \"px; height: \" + this.options.baselineMarkerSize + \"px;overflow: hidden;\";\n\n return marker;\n };\n\n return TextMetrics;\n}(Class));\n\nTextMetrics.current = new TextMetrics();\n\nexport default TextMetrics;\n","import TextMetrics from './text-metrics';\n\nexport default function measureText(text, style, measureBox) {\n return TextMetrics.current.measure(text, style, measureBox);\n}\n","/* eslint-disable key-spacing,no-multi-spaces,no-param-reassign */\n\nvar literals = {\n 1 : \"i\", 10 : \"x\", 100 : \"c\",\n 2 : \"ii\", 20 : \"xx\", 200 : \"cc\",\n 3 : \"iii\", 30 : \"xxx\", 300 : \"ccc\",\n 4 : \"iv\", 40 : \"xl\", 400 : \"cd\",\n 5 : \"v\", 50 : \"l\", 500 : \"d\",\n 6 : \"vi\", 60 : \"lx\", 600 : \"dc\",\n 7 : \"vii\", 70 : \"lxx\", 700 : \"dcc\",\n 8 : \"viii\", 80 : \"lxxx\", 800 : \"dccc\",\n 9 : \"ix\", 90 : \"xc\", 900 : \"cm\",\n 1000 : \"m\"\n};\n\nexport default function arabicToRoman(n) {\n var values = [ 1000,\n 900 , 800, 700, 600, 500, 400, 300, 200, 100,\n 90 , 80 , 70 , 60 , 50 , 40 , 30 , 20 , 10 ,\n 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 ];\n\n var roman = \"\";\n while (n > 0) {\n if (n < values[0]) {\n values.shift();\n } else {\n roman += literals[values[0]];\n n -= values[0];\n }\n }\n return roman;\n}","/* eslint-disable no-multi-spaces, key-spacing, indent, camelcase, space-before-blocks, eqeqeq, brace-style */\n/* eslint-disable space-infix-ops, space-before-function-paren, array-bracket-spacing, object-curly-spacing */\n/* eslint-disable no-nested-ternary, max-params, default-case, no-else-return, no-empty */\n/* eslint-disable no-param-reassign, no-var, block-scoped-var */\n\n// mergeSort is stable.\nexport default function mergeSort(a, cmp) {\n if (a.length < 2) {\n return a.slice();\n }\n function merge(a, b) {\n var r = [], ai = 0, bi = 0, i = 0;\n while (ai < a.length && bi < b.length) {\n if (cmp(a[ai], b[bi]) <= 0) {\n r[i++] = a[ai++];\n } else {\n r[i++] = b[bi++];\n }\n }\n if (ai < a.length) {\n r.push.apply(r, a.slice(ai));\n }\n if (bi < b.length) {\n r.push.apply(r, b.slice(bi));\n }\n return r;\n }\n return (function sort(a) {\n if (a.length <= 1) {\n return a;\n }\n var m = Math.floor(a.length / 2);\n var left = a.slice(0, m);\n var right = a.slice(m);\n left = sort(left);\n right = sort(right);\n return merge(left, right);\n })(a);\n}","var namedColors = {\n aliceblue: \"f0f8ff\", antiquewhite: \"faebd7\", aqua: \"00ffff\",\n aquamarine: \"7fffd4\", azure: \"f0ffff\", beige: \"f5f5dc\",\n bisque: \"ffe4c4\", black: \"000000\", blanchedalmond: \"ffebcd\",\n blue: \"0000ff\", blueviolet: \"8a2be2\", brown: \"a52a2a\",\n burlywood: \"deb887\", cadetblue: \"5f9ea0\", chartreuse: \"7fff00\",\n chocolate: \"d2691e\", coral: \"ff7f50\", cornflowerblue: \"6495ed\",\n cornsilk: \"fff8dc\", crimson: \"dc143c\", cyan: \"00ffff\",\n darkblue: \"00008b\", darkcyan: \"008b8b\", darkgoldenrod: \"b8860b\",\n darkgray: \"a9a9a9\", darkgrey: \"a9a9a9\", darkgreen: \"006400\",\n darkkhaki: \"bdb76b\", darkmagenta: \"8b008b\", darkolivegreen: \"556b2f\",\n darkorange: \"ff8c00\", darkorchid: \"9932cc\", darkred: \"8b0000\",\n darksalmon: \"e9967a\", darkseagreen: \"8fbc8f\", darkslateblue: \"483d8b\",\n darkslategray: \"2f4f4f\", darkslategrey: \"2f4f4f\", darkturquoise: \"00ced1\",\n darkviolet: \"9400d3\", deeppink: \"ff1493\", deepskyblue: \"00bfff\",\n dimgray: \"696969\", dimgrey: \"696969\", dodgerblue: \"1e90ff\",\n firebrick: \"b22222\", floralwhite: \"fffaf0\", forestgreen: \"228b22\",\n fuchsia: \"ff00ff\", gainsboro: \"dcdcdc\", ghostwhite: \"f8f8ff\",\n gold: \"ffd700\", goldenrod: \"daa520\", gray: \"808080\",\n grey: \"808080\", green: \"008000\", greenyellow: \"adff2f\",\n honeydew: \"f0fff0\", hotpink: \"ff69b4\", indianred: \"cd5c5c\",\n indigo: \"4b0082\", ivory: \"fffff0\", khaki: \"f0e68c\",\n lavender: \"e6e6fa\", lavenderblush: \"fff0f5\", lawngreen: \"7cfc00\",\n lemonchiffon: \"fffacd\", lightblue: \"add8e6\", lightcoral: \"f08080\",\n lightcyan: \"e0ffff\", lightgoldenrodyellow: \"fafad2\", lightgray: \"d3d3d3\",\n lightgrey: \"d3d3d3\", lightgreen: \"90ee90\", lightpink: \"ffb6c1\",\n lightsalmon: \"ffa07a\", lightseagreen: \"20b2aa\", lightskyblue: \"87cefa\",\n lightslategray: \"778899\", lightslategrey: \"778899\", lightsteelblue: \"b0c4de\",\n lightyellow: \"ffffe0\", lime: \"00ff00\", limegreen: \"32cd32\",\n linen: \"faf0e6\", magenta: \"ff00ff\", maroon: \"800000\",\n mediumaquamarine: \"66cdaa\", mediumblue: \"0000cd\", mediumorchid: \"ba55d3\",\n mediumpurple: \"9370d8\", mediumseagreen: \"3cb371\", mediumslateblue: \"7b68ee\",\n mediumspringgreen: \"00fa9a\", mediumturquoise: \"48d1cc\", mediumvioletred: \"c71585\",\n midnightblue: \"191970\", mintcream: \"f5fffa\", mistyrose: \"ffe4e1\",\n moccasin: \"ffe4b5\", navajowhite: \"ffdead\", navy: \"000080\",\n oldlace: \"fdf5e6\", olive: \"808000\", olivedrab: \"6b8e23\",\n orange: \"ffa500\", orangered: \"ff4500\", orchid: \"da70d6\",\n palegoldenrod: \"eee8aa\", palegreen: \"98fb98\", paleturquoise: \"afeeee\",\n palevioletred: \"d87093\", papayawhip: \"ffefd5\", peachpuff: \"ffdab9\",\n peru: \"cd853f\", pink: \"ffc0cb\", plum: \"dda0dd\",\n powderblue: \"b0e0e6\", purple: \"800080\", red: \"ff0000\",\n rosybrown: \"bc8f8f\", royalblue: \"4169e1\", saddlebrown: \"8b4513\",\n salmon: \"fa8072\", sandybrown: \"f4a460\", seagreen: \"2e8b57\",\n seashell: \"fff5ee\", sienna: \"a0522d\", silver: \"c0c0c0\",\n skyblue: \"87ceeb\", slateblue: \"6a5acd\", slategray: \"708090\",\n slategrey: \"708090\", snow: \"fffafa\", springgreen: \"00ff7f\",\n steelblue: \"4682b4\", tan: \"d2b48c\", teal: \"008080\",\n thistle: \"d8bfd8\", tomato: \"ff6347\", turquoise: \"40e0d0\",\n violet: \"ee82ee\", wheat: \"f5deb3\", white: \"ffffff\",\n whitesmoke: \"f5f5f5\", yellow: \"ffff00\", yellowgreen: \"9acd32\"\n};\n\nexport default namedColors;","import Class from '../class';\nimport support from '../support';\nimport namedColors from './named-colors';\n\nvar browser = support.browser;\n\nvar matchNamedColor = function (color) {\n var colorNames = Object.keys(namedColors);\n colorNames.push(\"transparent\");\n\n var regexp = new RegExp(\"^(\" + colorNames.join(\"|\") + \")(\\\\W|$)\", \"i\");\n matchNamedColor = function (color) { return regexp.exec(color); };\n\n return regexp.exec(color);\n};\n\nvar BaseColor = (function (Class) {\n function BaseColor() { Class.call(this); }\n\n if ( Class ) BaseColor.__proto__ = Class;\n BaseColor.prototype = Object.create( Class && Class.prototype );\n BaseColor.prototype.constructor = BaseColor;\n BaseColor.prototype.toHSV = function toHSV () { return this; };\n\n BaseColor.prototype.toRGB = function toRGB () { return this; };\n\n BaseColor.prototype.toHex = function toHex () { return this.toBytes().toHex(); };\n\n BaseColor.prototype.toBytes = function toBytes () { return this; };\n\n BaseColor.prototype.toCss = function toCss () { return \"#\" + this.toHex(); };\n\n BaseColor.prototype.toCssRgba = function toCssRgba () {\n var rgb = this.toBytes();\n return (\"rgba(\" + (rgb.r) + \", \" + (rgb.g) + \", \" + (rgb.b) + \", \" + (parseFloat((Number(this.a)).toFixed(3))) + \")\");\n };\n\n BaseColor.prototype.toDisplay = function toDisplay () {\n if (browser.msie && browser.version < 9) {\n return this.toCss(); // no RGBA support; does it support any opacity in colors?\n }\n return this.toCssRgba();\n };\n\n BaseColor.prototype.equals = function equals (c) {\n return c === this || c !== null && this.toCssRgba() === parseColor(c).toCssRgba();\n };\n\n BaseColor.prototype.diff = function diff (other) {\n if (other === null) {\n return NaN;\n }\n\n var c1 = this.toBytes();\n var c2 = other.toBytes();\n\n return Math.sqrt(Math.pow((c1.r - c2.r) * 0.30, 2) +\n Math.pow((c1.g - c2.g) * 0.59, 2) +\n Math.pow((c1.b - c2.b) * 0.11, 2));\n };\n\n BaseColor.prototype.clone = function clone () {\n var c = this.toBytes();\n if (c === this) {\n c = new Bytes(c.r, c.g, c.b, c.a);\n }\n\n return c;\n };\n\n return BaseColor;\n}(Class));\n\nvar RGB = (function (BaseColor) {\n function RGB(r, g, b, a) {\n BaseColor.call(this);\n\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n\n if ( BaseColor ) RGB.__proto__ = BaseColor;\n RGB.prototype = Object.create( BaseColor && BaseColor.prototype );\n RGB.prototype.constructor = RGB;\n\n RGB.prototype.toHSV = function toHSV () {\n var ref = this;\n var r = ref.r;\n var g = ref.g;\n var b = ref.b;\n var min = Math.min(r, g, b);\n var max = Math.max(r, g, b);\n var delta = max - min;\n var v = max;\n var h, s;\n\n if (delta === 0) {\n return new HSV(0, 0, v, this.a);\n }\n\n if (max !== 0) {\n s = delta / max;\n if (r === max) {\n h = (g - b) / delta;\n } else if (g === max) {\n h = 2 + (b - r) / delta;\n } else {\n h = 4 + (r - g) / delta;\n }\n\n h *= 60;\n if (h < 0) {\n h += 360;\n }\n } else {\n s = 0;\n h = -1;\n }\n\n return new HSV(h, s, v, this.a);\n };\n\n RGB.prototype.toHSL = function toHSL () {\n var ref = this;\n var r = ref.r;\n var g = ref.g;\n var b = ref.b;\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var h, s, l = (max + min) / 2;\n\n if (max === min) {\n h = s = 0;\n } else {\n var d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n default: break;\n }\n }\n\n return new HSL(h * 60, s * 100, l * 100, this.a);\n };\n\n RGB.prototype.toBytes = function toBytes () {\n return new Bytes(this.r * 255, this.g * 255, this.b * 255, this.a);\n };\n\n return RGB;\n}(BaseColor));\n\nvar Bytes = (function (RGB) {\n function Bytes(r, g, b, a) {\n RGB.call(this, Math.round(r), Math.round(g), Math.round(b), a);\n }\n\n if ( RGB ) Bytes.__proto__ = RGB;\n Bytes.prototype = Object.create( RGB && RGB.prototype );\n Bytes.prototype.constructor = Bytes;\n\n Bytes.prototype.toRGB = function toRGB () {\n return new RGB(this.r / 255, this.g / 255, this.b / 255, this.a);\n };\n\n Bytes.prototype.toHSV = function toHSV () {\n return this.toRGB().toHSV();\n };\n\n Bytes.prototype.toHSL = function toHSL () {\n return this.toRGB().toHSL();\n };\n\n Bytes.prototype.toHex = function toHex () {\n return hex(this.r, 2) + hex(this.g, 2) + hex(this.b, 2);\n };\n\n Bytes.prototype.toBytes = function toBytes () {\n return this;\n };\n\n return Bytes;\n}(RGB));\n\nfunction hex(n, width, pad) {\n if ( pad === void 0 ) pad = \"0\";\n\n var result = n.toString(16);\n while (width > result.length) {\n result = pad + result;\n }\n\n return result;\n}\n\nvar HSV = (function (BaseColor) {\n function HSV(h, s, v, a) {\n BaseColor.call(this);\n\n this.h = h;\n this.s = s;\n this.v = v;\n this.a = a;\n }\n\n if ( BaseColor ) HSV.__proto__ = BaseColor;\n HSV.prototype = Object.create( BaseColor && BaseColor.prototype );\n HSV.prototype.constructor = HSV;\n\n HSV.prototype.toRGB = function toRGB () {\n var ref = this;\n var h = ref.h;\n var s = ref.s;\n var v = ref.v;\n var r, g, b;\n\n if (s === 0) {\n r = g = b = v;\n } else {\n h /= 60;\n\n var i = Math.floor(h);\n var f = h - i;\n var p = v * (1 - s);\n var q = v * (1 - s * f);\n var t = v * (1 - s * (1 - f));\n\n switch (i) {\n case 0: r = v; g = t; b = p; break;\n case 1: r = q; g = v; b = p; break;\n case 2: r = p; g = v; b = t; break;\n case 3: r = p; g = q; b = v; break;\n case 4: r = t; g = p; b = v; break;\n default: r = v; g = p; b = q; break;\n }\n }\n\n return new RGB(r, g, b, this.a);\n };\n\n HSV.prototype.toHSL = function toHSL () {\n return this.toRGB().toHSL();\n };\n\n HSV.prototype.toBytes = function toBytes () {\n return this.toRGB().toBytes();\n };\n\n return HSV;\n}(BaseColor));\n\nvar HSL = (function (BaseColor) {\n function HSL(h, s, l, a) {\n BaseColor.call(this);\n\n this.h = h;\n this.s = s;\n this.l = l;\n this.a = a;\n }\n\n if ( BaseColor ) HSL.__proto__ = BaseColor;\n HSL.prototype = Object.create( BaseColor && BaseColor.prototype );\n HSL.prototype.constructor = HSL;\n\n HSL.prototype.toRGB = function toRGB () {\n var h = this.h / 360;\n var s = this.s / 100;\n var l = this.l / 100;\n var r, g, b;\n\n if (s === 0) {\n r = g = b = l; // achromatic\n } else {\n var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n var p = 2 * l - q;\n r = hue2rgb(p, q, h + 1 / 3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1 / 3);\n }\n\n return new RGB(r, g, b, this.a);\n };\n\n HSL.prototype.toHSV = function toHSV () {\n return this.toRGB().toHSV();\n };\n\n HSL.prototype.toBytes = function toBytes () {\n return this.toRGB().toBytes();\n };\n\n return HSL;\n}(BaseColor));\n\nfunction hue2rgb(p, q, s) {\n var t = s;\n\n if (t < 0) {\n t += 1;\n }\n\n if (t > 1) {\n t -= 1;\n }\n\n if (t < 1 / 6) {\n return p + (q - p) * 6 * t;\n }\n\n if (t < 1 / 2) {\n return q;\n }\n\n if (t < 2 / 3) {\n return p + (q - p) * (2 / 3 - t) * 6;\n }\n\n return p;\n}\n\nexport { RGB, Bytes, HSV, HSL };\n\nexport default function parseColor(value, safe) {\n var m, ret;\n\n if (value == null || value === \"none\") {\n return null;\n }\n\n if (value instanceof BaseColor) {\n return value;\n }\n\n var color = value.toLowerCase();\n if ((m = matchNamedColor(color))) {\n if (m[1] === \"transparent\") {\n color = new RGB(1, 1, 1, 0);\n } else {\n color = parseColor(namedColors[m[1]], safe);\n }\n color.match = [ m[1] ];\n return color;\n }\n if ((m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\\b/i.exec(color))) {\n ret = new Bytes(parseInt(m[1], 16),\n parseInt(m[2], 16),\n parseInt(m[3], 16), 1);\n } else if ((m = /^#?([0-9a-f])([0-9a-f])([0-9a-f])\\b/i.exec(color))) {\n ret = new Bytes(parseInt(m[1] + m[1], 16),\n parseInt(m[2] + m[2], 16),\n parseInt(m[3] + m[3], 16), 1);\n } else if ((m = /^rgb\\(\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*\\)/.exec(color))) {\n ret = new Bytes(parseInt(m[1], 10),\n parseInt(m[2], 10),\n parseInt(m[3], 10), 1);\n } else if ((m = /^rgba\\(\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9.]+)\\s*\\)/.exec(color))) {\n ret = new Bytes(parseInt(m[1], 10),\n parseInt(m[2], 10),\n parseInt(m[3], 10), parseFloat(m[4]));\n } else if ((m = /^rgb\\(\\s*([0-9]*\\.?[0-9]+)%\\s*,\\s*([0-9]*\\.?[0-9]+)%\\s*,\\s*([0-9]*\\.?[0-9]+)%\\s*\\)/.exec(color))) {\n ret = new RGB(parseFloat(m[1]) / 100,\n parseFloat(m[2]) / 100,\n parseFloat(m[3]) / 100, 1);\n } else if ((m = /^rgba\\(\\s*([0-9]*\\.?[0-9]+)%\\s*,\\s*([0-9]*\\.?[0-9]+)%\\s*,\\s*([0-9]*\\.?[0-9]+)%\\s*,\\s*([0-9.]+)\\s*\\)/.exec(color))) {\n ret = new RGB(parseFloat(m[1]) / 100,\n parseFloat(m[2]) / 100,\n parseFloat(m[3]) / 100, parseFloat(m[4]));\n }\n\n if (ret) {\n ret.match = m;\n } else if (!safe) {\n throw new Error(\"Cannot parse color: \" + color);\n }\n\n return ret;\n}\n","import { Class } from '../common';\nimport HasObservers from './has-observers';\nimport { defined } from '../util';\n\n\nvar toString = {}.toString;\n\nvar OptionsStore = (function (HasObservers) {\n function OptionsStore(options, prefix) {\n var this$1 = this;\n if ( prefix === void 0 ) prefix = \"\";\n\n HasObservers.call(this);\n\n this.prefix = prefix;\n\n for (var field in options) {\n var member = options[field];\n member = this$1._wrap(member, field);\n this$1[field] = member;\n }\n }\n\n if ( HasObservers ) OptionsStore.__proto__ = HasObservers;\n OptionsStore.prototype = Object.create( HasObservers && HasObservers.prototype );\n OptionsStore.prototype.constructor = OptionsStore;\n\n OptionsStore.prototype.get = function get (field) {\n var parts = field.split(\".\");\n var result = this;\n\n while (parts.length && result) {\n var part = parts.shift();\n result = result[part];\n }\n\n return result;\n };\n\n OptionsStore.prototype.set = function set (field, value) {\n var current = this.get(field);\n\n if (current !== value) {\n this._set(field, this._wrap(value, field));\n this.optionsChange({\n field: this.prefix + field,\n value: value\n });\n }\n };\n\n OptionsStore.prototype._set = function _set (field, value) {\n var this$1 = this;\n\n var composite = field.indexOf(\".\") >= 0;\n var parentObj = this;\n var fieldName = field;\n\n if (composite) {\n var parts = fieldName.split(\".\");\n var prefix = this.prefix;\n\n while (parts.length > 1) {\n fieldName = parts.shift();\n prefix += fieldName + \".\";\n\n var obj = parentObj[fieldName];\n\n if (!obj) {\n obj = new OptionsStore({}, prefix);\n obj.addObserver(this$1);\n parentObj[fieldName] = obj;\n }\n parentObj = obj;\n }\n fieldName = parts[0];\n }\n\n parentObj._clear(fieldName);\n parentObj[fieldName] = value;\n };\n\n OptionsStore.prototype._clear = function _clear (field) {\n var current = this[field];\n if (current && current.removeObserver) {\n current.removeObserver(this);\n }\n };\n\n OptionsStore.prototype._wrap = function _wrap (object, field) {\n var type = toString.call(object);\n var wrapped = object;\n\n if (wrapped !== null && defined(wrapped) && type === \"[object Object]\") {\n if (!(object instanceof OptionsStore) && !(object instanceof Class)) {\n wrapped = new OptionsStore(wrapped, this.prefix + field + \".\");\n }\n\n wrapped.addObserver(this);\n }\n\n return wrapped;\n };\n\n return OptionsStore;\n}(HasObservers));\n\nexport default OptionsStore;\n","var defId = 1;\n\nexport default function definitionId() {\n return \"kdef\" + defId++;\n}","import defined from './defined';\n\nexport default function isTransparent(color) {\n return color === \"\" || color === null || color === \"none\" || color === \"transparent\" || !defined(color);\n}","import OptionsStore from '../core/options-store';\nimport Rect from '../geometry/rect';\nimport Matrix from '../geometry/matrix';\nimport createTransform from '../geometry/transform';\nimport toMatrix from '../geometry/to-matrix';\nimport HasObservers from '../core/has-observers';\nimport { defined, definitionId, isTransparent, valueOrDefault } from '../util';\n\nvar Element = (function (HasObservers) {\n function Element(options) {\n HasObservers.call(this);\n\n this._initOptions(options);\n }\n\n if ( HasObservers ) Element.__proto__ = HasObservers;\n Element.prototype = Object.create( HasObservers && HasObservers.prototype );\n Element.prototype.constructor = Element;\n\n var prototypeAccessors = { nodeType: { configurable: true } };\n\n prototypeAccessors.nodeType.get = function () {\n return \"Rect\";\n };\n\n Element.prototype._initOptions = function _initOptions (options) {\n if ( options === void 0 ) options = {};\n\n var clip = options.clip;\n var transform = options.transform;\n\n if (transform) {\n options.transform = createTransform(transform);\n }\n\n if (clip && !clip.id) {\n clip.id = definitionId();\n }\n\n this.options = new OptionsStore(options);\n this.options.addObserver(this);\n };\n\n Element.prototype.transform = function transform (value) {\n if (defined(value)) {\n this.options.set(\"transform\", createTransform(value));\n } else {\n return this.options.get(\"transform\");\n }\n };\n\n Element.prototype.parentTransform = function parentTransform () {\n var element = this;\n var parentMatrix;\n\n while (element.parent) {\n element = element.parent;\n var transformation = element.transform();\n if (transformation) {\n parentMatrix = transformation.matrix().multiplyCopy(parentMatrix || Matrix.unit());\n }\n }\n\n if (parentMatrix) {\n return createTransform(parentMatrix);\n }\n };\n\n Element.prototype.currentTransform = function currentTransform (parentTransform) {\n if ( parentTransform === void 0 ) parentTransform = this.parentTransform();\n\n var elementTransform = this.transform();\n var elementMatrix = toMatrix(elementTransform);\n\n var parentMatrix = toMatrix(parentTransform);\n var combinedMatrix;\n\n if (elementMatrix && parentMatrix) {\n combinedMatrix = parentMatrix.multiplyCopy(elementMatrix);\n } else {\n combinedMatrix = elementMatrix || parentMatrix;\n }\n\n if (combinedMatrix) {\n return createTransform(combinedMatrix);\n }\n };\n\n Element.prototype.visible = function visible (value) {\n if (defined(value)) {\n this.options.set(\"visible\", value);\n return this;\n }\n\n return this.options.get(\"visible\") !== false;\n };\n\n Element.prototype.clip = function clip (value) {\n var options = this.options;\n if (defined(value)) {\n if (value && !value.id) {\n value.id = definitionId();\n }\n options.set(\"clip\", value);\n return this;\n }\n\n return options.get(\"clip\");\n };\n\n Element.prototype.opacity = function opacity (value) {\n if (defined(value)) {\n this.options.set(\"opacity\", value);\n return this;\n }\n\n return valueOrDefault(this.options.get(\"opacity\"), 1);\n };\n\n Element.prototype.clippedBBox = function clippedBBox (transformation) {\n var bbox = this._clippedBBox(transformation);\n if (bbox) {\n var clip = this.clip();\n return clip ? Rect.intersect(bbox, clip.bbox(transformation)) : bbox;\n }\n };\n\n Element.prototype.containsPoint = function containsPoint (point, parentTransform) {\n if (this.visible()) {\n var transform = this.currentTransform(parentTransform);\n var transformedPoint = point;\n if (transform) {\n transformedPoint = point.transformCopy(transform.matrix().invert());\n }\n return (this._hasFill() && this._containsPoint(transformedPoint)) || (this._isOnPath && this._hasStroke() && this._isOnPath(transformedPoint));\n }\n return false;\n };\n\n Element.prototype._hasFill = function _hasFill () {\n var fill = this.options.fill;\n return fill && !isTransparent(fill.color);\n };\n\n Element.prototype._hasStroke = function _hasStroke () {\n var stroke = this.options.stroke;\n return stroke && stroke.width > 0 && !isTransparent(stroke.color);\n };\n\n Element.prototype._clippedBBox = function _clippedBBox (transformation) {\n return this.bbox(transformation);\n };\n\n Object.defineProperties( Element.prototype, prototypeAccessors );\n\n return Element;\n}(HasObservers));\n\nexport default Element;\n","import defined from './defined';\n\nexport default function valueOrDefault(value, defaultValue) {\n return defined(value) ? value : defaultValue;\n}","import { defined } from '../util';\n\nvar GRADIENT = \"Gradient\";\n\nvar paintable = function (TBase) { return (\n (function (TBase) {\n function anonymous () {\n TBase.apply(this, arguments);\n }\n\n if ( TBase ) anonymous.__proto__ = TBase;\n anonymous.prototype = Object.create( TBase && TBase.prototype );\n anonymous.prototype.constructor = anonymous;\n\n anonymous.prototype.fill = function fill (color, opacity) {\n var options = this.options;\n\n if (defined(color)) {\n if (color && color.nodeType !== GRADIENT) {\n var newFill = {\n color: color\n };\n if (defined(opacity)) {\n newFill.opacity = opacity;\n }\n options.set(\"fill\", newFill);\n } else {\n options.set(\"fill\", color);\n }\n\n return this;\n }\n\n return options.get(\"fill\");\n };\n\n anonymous.prototype.stroke = function stroke (color, width, opacity) {\n if (defined(color)) {\n this.options.set(\"stroke.color\", color);\n\n if (defined(width)) {\n this.options.set(\"stroke.width\", width);\n }\n\n if (defined(opacity)) {\n this.options.set(\"stroke.opacity\", opacity);\n }\n\n return this;\n }\n\n return this.options.get(\"stroke\");\n };\n\n return anonymous;\n }(TBase))\n); };\n\nexport default paintable;\n","import { defined } from '../util';\nimport Point from '../geometry/point';\n\nfunction pointAccessor(name) {\n var fieldName = \"_\" + name;\n return function(value) {\n if (defined(value)) {\n this._observerField(fieldName, Point.create(value));\n this.geometryChange();\n return this;\n }\n\n return this[fieldName];\n };\n}\n\nfunction definePointAccessors(fn, names) {\n for (var i = 0; i < names.length; i++) {\n fn[names[i]] = pointAccessor(names[i]);\n }\n}\n\nvar withPoints = function (TBase, names) {\n var result = (function (TBase) {\n function result () {\n TBase.apply(this, arguments);\n }if ( TBase ) result.__proto__ = TBase;\n result.prototype = Object.create( TBase && TBase.prototype );\n result.prototype.constructor = result;\n\n \n\n return result;\n }(TBase));\n definePointAccessors(result.prototype, names);\n\n return result;\n};\n\nexport default withPoints;\n","import Element from './element';\nimport Point from '../geometry/point';\nimport Rect from '../geometry/rect';\nimport toMatrix from '../geometry/to-matrix';\nimport paintable from '../mixins/paintable';\nimport withPoints from '../mixins/with-points';\nimport { defined, measureText } from '../util';\n\n\nvar DEFAULT_FONT = \"12px sans-serif\";\nvar DEFAULT_FILL = \"#000\";\n\nvar Text = (function (superclass) {\n function Text(content, position, options) {\n if ( position === void 0 ) position = new Point();\n if ( options === void 0 ) options = {};\n\n superclass.call(this, options);\n\n this.content(content);\n this.position(position);\n\n if (!this.options.font) {\n this.options.font = DEFAULT_FONT;\n }\n\n if (!defined(this.options.fill)) {\n this.fill(DEFAULT_FILL);\n }\n }\n\n if ( superclass ) Text.__proto__ = superclass;\n Text.prototype = Object.create( superclass && superclass.prototype );\n Text.prototype.constructor = Text;\n\n var prototypeAccessors = { nodeType: { configurable: true } };\n\n prototypeAccessors.nodeType.get = function () {\n return \"Text\";\n };\n\n Text.prototype.content = function content (value) {\n if (defined(value)) {\n this.options.set(\"content\", value);\n return this;\n }\n\n return this.options.get(\"content\");\n };\n\n Text.prototype.measure = function measure () {\n var metrics = measureText(this.content(), {\n font: this.options.get(\"font\")\n });\n\n return metrics;\n };\n\n Text.prototype.rect = function rect () {\n var size = this.measure();\n var pos = this.position().clone();\n return new Rect(pos, [ size.width, size.height ]);\n };\n\n Text.prototype.bbox = function bbox (transformation) {\n var combinedMatrix = toMatrix(this.currentTransform(transformation));\n return this.rect().bbox(combinedMatrix);\n };\n\n Text.prototype.rawBBox = function rawBBox () {\n return this.rect().bbox();\n };\n\n Text.prototype._containsPoint = function _containsPoint (point) {\n return this.rect().containsPoint(point);\n };\n\n Object.defineProperties( Text.prototype, prototypeAccessors );\n\n return Text;\n}(paintable(withPoints(Element, [ \"position\" ]))));\n\nexport default Text;\n","var traversable = function (TBase, childrenField) { return (\n (function (TBase) {\n function anonymous () {\n TBase.apply(this, arguments);\n }\n\n if ( TBase ) anonymous.__proto__ = TBase;\n anonymous.prototype = Object.create( TBase && TBase.prototype );\n anonymous.prototype.constructor = anonymous;\n\n anonymous.prototype.traverse = function traverse (callback) {\n var children = this[childrenField];\n\n for (var i = 0; i < children.length; i++) {\n var child = children[i];\n\n if (child.traverse) {\n child.traverse(callback);\n } else {\n callback(child);\n }\n }\n\n return this;\n };\n\n return anonymous;\n }(TBase))\n); };\n\nexport default traversable;\n","export default function append(first, second) {\n first.push.apply(first, second);\n return first;\n}","import Rect from '../../geometry/rect';\n\nexport default function elementsBoundingBox(elements, applyTransform, transformation) {\n var boundingBox;\n\n for (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n if (element.visible()) {\n var elementBoundingBox = applyTransform ? element.bbox(transformation) : element.rawBBox();\n if (elementBoundingBox) {\n if (boundingBox) {\n boundingBox = Rect.union(boundingBox, elementBoundingBox);\n } else {\n boundingBox = elementBoundingBox;\n }\n }\n }\n }\n\n return boundingBox;\n}\n\n","import Rect from '../../geometry/rect';\n\nexport default function elementsClippedBoundingBox(elements, transformation) {\n var boundingBox;\n\n for (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n if (element.visible()) {\n var elementBoundingBox = element.clippedBBox(transformation);\n if (elementBoundingBox) {\n if (boundingBox) {\n boundingBox = Rect.union(boundingBox, elementBoundingBox);\n } else {\n boundingBox = elementBoundingBox;\n }\n }\n }\n }\n\n return boundingBox;\n}","import Element from './element';\nimport traversable from '../mixins/traversable';\nimport { append } from '../util';\nimport elementsBoundingBox from './utils/elements-bounding-box';\nimport elementsClippedBoundingBox from './utils/elements-clippend-bounding-box';\n\n\nvar Group = (function (superclass) {\n function Group(options) {\n superclass.call(this, options);\n this.children = [];\n }\n\n if ( superclass ) Group.__proto__ = superclass;\n Group.prototype = Object.create( superclass && superclass.prototype );\n Group.prototype.constructor = Group;\n\n var prototypeAccessors = { nodeType: { configurable: true } };\n\n prototypeAccessors.nodeType.get = function () {\n return \"Group\";\n };\n\n Group.prototype.childrenChange = function childrenChange (action, items, index) {\n this.trigger(\"childrenChange\",{\n action: action,\n items: items,\n index: index\n });\n };\n\n Group.prototype.append = function append$1 () {\n append(this.children, arguments);\n this._reparent(arguments, this);\n\n this.childrenChange(\"add\", arguments);\n\n return this;\n };\n\n Group.prototype.insert = function insert (index, element) {\n this.children.splice(index, 0, element);\n element.parent = this;\n\n this.childrenChange(\"add\", [ element ], index);\n\n return this;\n };\n\n Group.prototype.insertAt = function insertAt (element, index) {\n return this.insert(index, element);\n };\n\n Group.prototype.remove = function remove (element) {\n var index = this.children.indexOf(element);\n if (index >= 0) {\n this.children.splice(index, 1);\n element.parent = null;\n this.childrenChange(\"remove\", [ element ], index);\n }\n\n return this;\n };\n\n Group.prototype.removeAt = function removeAt (index) {\n if (0 <= index && index < this.children.length) {\n var element = this.children[index];\n this.children.splice(index, 1);\n element.parent = null;\n this.childrenChange(\"remove\", [ element ], index);\n }\n\n return this;\n };\n\n Group.prototype.clear = function clear () {\n var items = this.children;\n this.children = [];\n this._reparent(items, null);\n\n this.childrenChange(\"remove\", items, 0);\n\n return this;\n };\n\n Group.prototype.bbox = function bbox (transformation) {\n return elementsBoundingBox(this.children, true, this.currentTransform(transformation));\n };\n\n Group.prototype.rawBBox = function rawBBox () {\n return elementsBoundingBox(this.children, false);\n };\n\n Group.prototype._clippedBBox = function _clippedBBox (transformation) {\n return elementsClippedBoundingBox(this.children, this.currentTransform(transformation));\n };\n\n Group.prototype.currentTransform = function currentTransform (transformation) {\n return Element.prototype.currentTransform.call(this, transformation) || null;\n };\n\n Group.prototype.containsPoint = function containsPoint (point, parentTransform) {\n if (this.visible()) {\n var children = this.children;\n var transform = this.currentTransform(parentTransform);\n for (var idx = 0; idx < children.length; idx++) {\n if (children[idx].containsPoint(point, transform)) {\n return true;\n }\n }\n }\n return false;\n };\n\n Group.prototype._reparent = function _reparent (elements, newParent) {\n var this$1 = this;\n\n for (var i = 0; i < elements.length; i++) {\n var child = elements[i];\n var parent = child.parent;\n if (parent && parent !== this$1 && parent.remove) {\n parent.remove(child);\n }\n\n child.parent = newParent;\n }\n };\n\n Object.defineProperties( Group.prototype, prototypeAccessors );\n\n return Group;\n}(traversable(Element, \"children\")));\n\nexport default Group;","import HasObservers from '../core/has-observers';\n\nvar push = [].push;\nvar pop = [].pop;\nvar splice = [].splice;\nvar shift = [].shift;\nvar slice = [].slice;\nvar unshift = [].unshift;\n\nvar ElementsArray = (function (HasObservers) {\n function ElementsArray(array) {\n if ( array === void 0 ) array = [];\n\n HasObservers.call(this);\n\n this.length = 0;\n this._splice(0, array.length, array);\n }\n\n if ( HasObservers ) ElementsArray.__proto__ = HasObservers;\n ElementsArray.prototype = Object.create( HasObservers && HasObservers.prototype );\n ElementsArray.prototype.constructor = ElementsArray;\n\n ElementsArray.prototype.elements = function elements (value) {\n if (value) {\n this._splice(0, this.length, value);\n\n this._change();\n return this;\n }\n\n return this.slice(0);\n };\n\n ElementsArray.prototype.push = function push$1 () {\n var elements = arguments;\n var result = push.apply(this, elements);\n\n this._add(elements);\n\n return result;\n };\n\n ElementsArray.prototype.slice = function slice$1 () {\n return slice.call(this);\n };\n\n ElementsArray.prototype.pop = function pop$1 () {\n var length = this.length;\n var result = pop.apply(this);\n\n if (length) {\n this._remove([ result ]);\n }\n\n return result;\n };\n\n ElementsArray.prototype.splice = function splice (index, howMany) {\n var elements = slice.call(arguments, 2);\n var result = this._splice(index, howMany, elements);\n\n this._change();\n\n return result;\n };\n\n ElementsArray.prototype.shift = function shift$1 () {\n var length = this.length;\n var result = shift.apply(this);\n\n if (length) {\n this._remove([ result ]);\n }\n\n return result;\n };\n\n ElementsArray.prototype.unshift = function unshift$1 () {\n var elements = arguments;\n var result = unshift.apply(this, elements);\n\n this._add(elements);\n\n return result;\n };\n\n ElementsArray.prototype.indexOf = function indexOf (element) {\n var this$1 = this;\n\n var length = this.length;\n\n for (var idx = 0; idx < length; idx++) {\n if (this$1[idx] === element) {\n return idx;\n }\n }\n return -1;\n };\n\n ElementsArray.prototype._splice = function _splice (index, howMany, elements) {\n var result = splice.apply(this, [ index, howMany ].concat(elements));\n\n this._clearObserver(result);\n this._setObserver(elements);\n\n return result;\n };\n\n ElementsArray.prototype._add = function _add (elements) {\n this._setObserver(elements);\n this._change();\n };\n\n ElementsArray.prototype._remove = function _remove (elements) {\n this._clearObserver(elements);\n this._change();\n };\n\n ElementsArray.prototype._setObserver = function _setObserver (elements) {\n var this$1 = this;\n\n for (var idx = 0; idx < elements.length; idx++) {\n elements[idx].addObserver(this$1);\n }\n };\n\n ElementsArray.prototype._clearObserver = function _clearObserver (elements) {\n var this$1 = this;\n\n for (var idx = 0; idx < elements.length; idx++) {\n elements[idx].removeObserver(this$1);\n }\n };\n\n ElementsArray.prototype._change = function _change () {};\n\n return ElementsArray;\n}(HasObservers));\n\nexport default ElementsArray;\n","import ElementsArray from './elements-array';\n\nvar GeometryElementsArray = (function (ElementsArray) {\n function GeometryElementsArray () {\n ElementsArray.apply(this, arguments);\n }\n\n if ( ElementsArray ) GeometryElementsArray.__proto__ = ElementsArray;\n GeometryElementsArray.prototype = Object.create( ElementsArray && ElementsArray.prototype );\n GeometryElementsArray.prototype.constructor = GeometryElementsArray;\n\n GeometryElementsArray.prototype._change = function _change () {\n this.geometryChange();\n };\n\n return GeometryElementsArray;\n}(ElementsArray));\n\nexport default GeometryElementsArray;","import Matrix from '../geometry/matrix';\nimport toMatrix from '../geometry/to-matrix';\n\nvar IDENTITY_MATRIX_HASH = Matrix.IDENTITY.toString();\n\nvar measurable = function (TBase) { return (\n (function (TBase) {\n function anonymous () {\n TBase.apply(this, arguments);\n }\n\n if ( TBase ) anonymous.__proto__ = TBase;\n anonymous.prototype = Object.create( TBase && TBase.prototype );\n anonymous.prototype.constructor = anonymous;\n\n anonymous.prototype.bbox = function bbox (transformation) {\n var combinedMatrix = toMatrix(this.currentTransform(transformation));\n var matrixHash = combinedMatrix ? combinedMatrix.toString() : IDENTITY_MATRIX_HASH;\n var bbox;\n\n if (this._bboxCache && this._matrixHash === matrixHash) {\n bbox = this._bboxCache.clone();\n } else {\n bbox = this._bbox(combinedMatrix);\n this._bboxCache = bbox ? bbox.clone() : null;\n this._matrixHash = matrixHash;\n }\n\n var strokeWidth = this.options.get(\"stroke.width\");\n if (strokeWidth && bbox) {\n bbox.expand(strokeWidth / 2);\n }\n\n return bbox;\n };\n\n anonymous.prototype.geometryChange = function geometryChange () {\n delete this._bboxCache;\n this.trigger(\"geometryChange\", {\n element: this\n });\n };\n\n return anonymous;\n }(TBase))\n); };\n\nexport default measurable;","import { deg } from '../../util';\nimport transform from '../transform';\n\nexport default function isOutOfEndPoint(endPoint, controlPoint, point) {\n var angle = deg(Math.atan2(controlPoint.y - endPoint.y, controlPoint.x - endPoint.x));\n var rotatedPoint = point.transformCopy(transform().rotate(-angle, endPoint));\n\n return rotatedPoint.x < endPoint.x;\n}","export default function calculateCurveAt(t, field, points) {\n var t1 = 1 - t;\n return Math.pow(t1, 3) * points[0][field] +\n 3 * Math.pow(t1, 2) * t * points[1][field] +\n 3 * Math.pow(t, 2) * t1 * points[2][field] +\n Math.pow(t, 3) * points[3][field];\n}","export default function toCubicPolynomial(points, field) {\n return [ -points[0][field] + 3 * points[1][field] - 3 * points[2][field] + points[3][field],\n 3 * (points[0][field] - 2 * points[1][field] + points[2][field]),\n 3 * (-points[0][field] + points[1][field]),\n points[0][field]\n ];\n}","import { PRECISION } from '../constants';\nimport { Class } from '../../common';\nimport { round } from '../../util';\n\nvar ComplexNumber = (function (Class) {\n function ComplexNumber(real, img) {\n if ( real === void 0 ) real = 0;\n if ( img === void 0 ) img = 0;\n\n Class.call(this);\n\n this.real = real;\n this.img = img;\n }\n\n if ( Class ) ComplexNumber.__proto__ = Class;\n ComplexNumber.prototype = Object.create( Class && Class.prototype );\n ComplexNumber.prototype.constructor = ComplexNumber;\n\n ComplexNumber.prototype.add = function add (cNumber) {\n return new ComplexNumber(round(this.real + cNumber.real, PRECISION), round(this.img + cNumber.img, PRECISION));\n };\n\n ComplexNumber.prototype.addConstant = function addConstant (value) {\n return new ComplexNumber(this.real + value, this.img);\n };\n\n ComplexNumber.prototype.negate = function negate () {\n return new ComplexNumber(-this.real, -this.img);\n };\n\n ComplexNumber.prototype.multiply = function multiply (cNumber) {\n return new ComplexNumber(this.real * cNumber.real - this.img * cNumber.img,\n this.real * cNumber.img + this.img * cNumber.real);\n };\n\n ComplexNumber.prototype.multiplyConstant = function multiplyConstant (value) {\n return new ComplexNumber(this.real * value, this.img * value);\n };\n\n ComplexNumber.prototype.nthRoot = function nthRoot (n) {\n var rad = Math.atan2(this.img, this.real);\n var r = Math.sqrt(Math.pow(this.img, 2) + Math.pow(this.real, 2));\n var nthR = Math.pow(r, 1 / n);\n\n return new ComplexNumber(nthR * Math.cos(rad / n), nthR * Math.sin(rad / n)); //Moivre's formula\n };\n\n ComplexNumber.prototype.equals = function equals (cNumber) {\n return this.real === cNumber.real && this.img === cNumber.img;\n };\n\n ComplexNumber.prototype.isReal = function isReal () {\n return this.img === 0;\n };\n\n return ComplexNumber;\n}(Class));\n\nexport default ComplexNumber;","import ComplexNumber from './complex-number';\nimport { PRECISION } from '../constants';\nimport { round } from '../../util';\n\nfunction numberSign(x) {\n return x < 0 ? -1 : 1;\n}\n\nfunction solveQuadraticEquation(a, b, c) {\n var squareRoot = Math.sqrt(Math.pow(b, 2) - 4 * a * c);\n return [\n (-b + squareRoot) / (2 * a),\n (-b - squareRoot) / (2 * a)\n ];\n}\n\n//Cardano's formula\nexport default function solveCubicEquation(a, b, c, d) {\n if (a === 0) {\n return solveQuadraticEquation(b, c, d);\n }\n\n var p = (3 * a * c - Math.pow(b, 2)) / (3 * Math.pow(a, 2));\n var q = (2 * Math.pow(b, 3) - 9 * a * b * c + 27 * Math.pow(a, 2) * d) / (27 * Math.pow(a, 3));\n var Q = Math.pow(p / 3, 3) + Math.pow(q / 2, 2);\n var i = new ComplexNumber(0,1);\n var b3a = -b / (3 * a);\n var x1, x2, y1, y2, y3, z1, z2;\n\n if (Q < 0) {\n x1 = new ComplexNumber(-q / 2, Math.sqrt(-Q)).nthRoot(3);\n x2 = new ComplexNumber(-q / 2, - Math.sqrt(-Q)).nthRoot(3);\n } else {\n x1 = -q / 2 + Math.sqrt(Q);\n x1 = new ComplexNumber(numberSign(x1) * Math.pow(Math.abs(x1), 1 / 3));\n x2 = -q / 2 - Math.sqrt(Q);\n x2 = new ComplexNumber(numberSign(x2) * Math.pow(Math.abs(x2), 1 / 3));\n }\n\n y1 = x1.add(x2);\n\n z1 = x1.add(x2).multiplyConstant(-1 / 2);\n z2 = x1.add(x2.negate()).multiplyConstant(Math.sqrt(3) / 2);\n\n y2 = z1.add(i.multiply(z2));\n y3 = z1.add(i.negate().multiply(z2));\n\n var result = [];\n\n if (y1.isReal()) {\n result.push(round(y1.real + b3a, PRECISION));\n }\n if (y2.isReal()) {\n result.push(round(y2.real + b3a, PRECISION));\n }\n if (y3.isReal()) {\n result.push(round(y3.real + b3a, PRECISION));\n }\n\n return result;\n}","import toCubicPolynomial from './to-cubic-polynomial';\nimport solveCubicEquation from './solve-cubic-equation';\nimport calculateCurveAt from './calculate-curve-at';\n\nexport default function hasRootsInRange(points, point, field, rootField, range) {\n var polynomial = toCubicPolynomial(points, rootField);\n var roots = solveCubicEquation(polynomial[0], polynomial[1], polynomial[2], polynomial[3] - point[rootField]);\n var intersection;\n\n for (var idx = 0; idx < roots.length; idx++) {\n if (0 <= roots[idx] && roots[idx] <= 1) {\n intersection = calculateCurveAt(roots[idx], field, points);\n if (Math.abs(intersection - point[field]) <= range) {\n return true;\n }\n }\n }\n}","export default function lineIntersectionsCount(a, b, point) {\n var intersects;\n if (a.x !== b.x) {\n var minX = Math.min(a.x, b.x);\n var maxX = Math.max(a.x, b.x);\n var minY = Math.min(a.y, b.y);\n var maxY = Math.max(a.y, b.y);\n var inRange = minX <= point.x && point.x < maxX;\n\n if (minY === maxY) {\n intersects = point.y <= minY && inRange;\n } else {\n intersects = inRange && (((maxY - minY) * ((a.x - b.x) * (a.y - b.y) > 0 ? point.x - minX : maxX - point.x)) / (maxX - minX) + minY - point.y) >= 0;\n }\n }\n\n return intersects ? 1 : 0;\n}","import HasObservers from '../core/has-observers';\nimport Rect from './rect';\nimport Point from './point';\nimport transform from './transform';\nimport { deg, MIN_NUM, MAX_NUM } from '../util';\nimport isOutOfEndPoint from './math/is-out-of-end-point';\nimport calculateCurveAt from './math/calculate-curve-at';\nimport hasRootsInRange from './math/has-roots-in-range';\nimport curveIntersectionsCount from './math/curve-intersections-count';\nimport lineIntersectionsCount from './math/line-intersections-count';\nimport withPoints from '../mixins/with-points';\n\n\nvar points = [ \"anchor\", \"controlIn\", \"controlOut\" ];\n\nvar Segment = (function (superclass) {\n function Segment(anchor, controlIn, controlOut) {\n superclass.call(this);\n\n this.anchor(anchor || new Point());\n this.controlIn(controlIn);\n this.controlOut(controlOut);\n }\n\n if ( superclass ) Segment.__proto__ = superclass;\n Segment.prototype = Object.create( superclass && superclass.prototype );\n Segment.prototype.constructor = Segment;\n\n Segment.prototype.bboxTo = function bboxTo (toSegment, matrix) {\n var segmentAnchor = this.anchor().transformCopy(matrix);\n var toSegmentAnchor = toSegment.anchor().transformCopy(matrix);\n var rect;\n\n if (this.controlOut() && toSegment.controlIn()) {\n rect = this._curveBoundingBox(\n segmentAnchor, this.controlOut().transformCopy(matrix),\n toSegment.controlIn().transformCopy(matrix), toSegmentAnchor\n );\n } else {\n rect = this._lineBoundingBox(segmentAnchor, toSegmentAnchor);\n }\n\n return rect;\n };\n\n Segment.prototype._lineBoundingBox = function _lineBoundingBox (p1, p2) {\n return Rect.fromPoints(p1, p2);\n };\n\n Segment.prototype._curveBoundingBox = function _curveBoundingBox (p1, cp1, cp2, p2) {\n var points = [ p1, cp1, cp2, p2 ];\n var extremesX = this._curveExtremesFor(points, \"x\");\n var extremesY = this._curveExtremesFor(points, \"y\");\n var xLimits = arrayLimits([ extremesX.min, extremesX.max, p1.x, p2.x ]);\n var yLimits = arrayLimits([ extremesY.min, extremesY.max, p1.y, p2.y ]);\n\n return Rect.fromPoints(new Point(xLimits.min, yLimits.min), new Point(xLimits.max, yLimits.max));\n };\n\n Segment.prototype._curveExtremesFor = function _curveExtremesFor (points, field) {\n var extremes = this._curveExtremes(\n points[0][field], points[1][field],\n points[2][field], points[3][field]\n );\n\n return {\n min: calculateCurveAt(extremes.min, field, points),\n max: calculateCurveAt(extremes.max, field, points)\n };\n };\n\n Segment.prototype._curveExtremes = function _curveExtremes (x1, x2, x3, x4) {\n var a = x1 - 3 * x2 + 3 * x3 - x4;\n var b = - 2 * (x1 - 2 * x2 + x3);\n var c = x1 - x2;\n var sqrt = Math.sqrt(b * b - 4 * a * c);\n var t1 = 0;\n var t2 = 1;\n\n if (a === 0) {\n if (b !== 0) {\n t1 = t2 = -c / b;\n }\n } else if (!isNaN(sqrt)) {\n t1 = (- b + sqrt) / (2 * a);\n t2 = (- b - sqrt) / (2 * a);\n }\n\n var min = Math.max(Math.min(t1, t2), 0);\n if (min < 0 || min > 1) {\n min = 0;\n }\n\n var max = Math.min(Math.max(t1, t2), 1);\n if (max > 1 || max < 0) {\n max = 1;\n }\n\n return {\n min: min,\n max: max\n };\n };\n\n Segment.prototype._intersectionsTo = function _intersectionsTo (segment, point) {\n var intersectionsCount;\n if (this.controlOut() && segment.controlIn()) {\n intersectionsCount = curveIntersectionsCount([ this.anchor(), this.controlOut(), segment.controlIn(), segment.anchor() ], point, this.bboxTo(segment));\n } else {\n intersectionsCount = lineIntersectionsCount(this.anchor(), segment.anchor(), point);\n }\n return intersectionsCount;\n };\n\n Segment.prototype._isOnCurveTo = function _isOnCurveTo (segment, point, width, endSegment) {\n var bbox = this.bboxTo(segment).expand(width, width);\n if (bbox.containsPoint(point)) {\n var p1 = this.anchor();\n var p2 = this.controlOut();\n var p3 = segment.controlIn();\n var p4 = segment.anchor();\n\n if (endSegment === \"start\" && p1.distanceTo(point) <= width) {\n return !isOutOfEndPoint(p1, p2, point);\n } else if (endSegment === \"end\" && p4.distanceTo(point) <= width) {\n return !isOutOfEndPoint(p4, p3, point);\n }\n\n //the approach is not entirely correct but is close and the alternatives are solving a 6th degree polynomial or testing the segment points\n var points = [ p1, p2, p3, p4 ];\n if (hasRootsInRange(points, point, \"x\", \"y\", width) || hasRootsInRange(points, point, \"y\", \"x\", width)) {\n return true;\n }\n var rotation = transform().rotate(45, point);\n var rotatedPoints = [ p1.transformCopy(rotation), p2.transformCopy(rotation), p3.transformCopy(rotation), p4.transformCopy(rotation) ];\n return hasRootsInRange(rotatedPoints, point, \"x\", \"y\", width) || hasRootsInRange(rotatedPoints, point, \"y\", \"x\", width);\n }\n };\n\n Segment.prototype._isOnLineTo = function _isOnLineTo (segment, point, width) {\n var p1 = this.anchor();\n var p2 = segment.anchor();\n var angle = deg(Math.atan2(p2.y - p1.y, p2.x - p1.x));\n var rect = new Rect([ p1.x, p1.y - width / 2 ], [ p1.distanceTo(p2), width ]);\n return rect.containsPoint(point.transformCopy(transform().rotate(-angle, p1)));\n };\n\n Segment.prototype._isOnPathTo = function _isOnPathTo (segment, point, width, endSegment) {\n var isOnPath;\n if (this.controlOut() && segment.controlIn()) {\n isOnPath = this._isOnCurveTo(segment, point, width / 2, endSegment);\n } else {\n isOnPath = this._isOnLineTo(segment, point, width);\n }\n return isOnPath;\n };\n\n return Segment;\n}(withPoints(HasObservers, points)));\n\nfunction arrayLimits(arr) {\n var length = arr.length;\n var min = MAX_NUM;\n var max = MIN_NUM;\n\n for (var i = 0; i < length; i ++) {\n max = Math.max(max, arr[i]);\n min = Math.min(min, arr[i]);\n }\n\n return {\n min: min,\n max: max\n };\n}\n\nexport default Segment;\n","import toCubicPolynomial from './to-cubic-polynomial';\nimport solveCubicEquation from './solve-cubic-equation';\nimport calculateCurveAt from './calculate-curve-at';\nimport close from './close';\n\nexport default function curveIntersectionsCount(points, point, bbox) {\n var polynomial = toCubicPolynomial(points, \"x\");\n var roots = solveCubicEquation(polynomial[0], polynomial[1], polynomial[2], polynomial[3] - point.x);\n var rayIntersection, intersectsRay;\n var count = 0;\n for (var i = 0; i < roots.length; i++) {\n rayIntersection = calculateCurveAt(roots[i], \"y\", points);\n intersectsRay = close(rayIntersection, point.y) || rayIntersection > point.y;\n if (intersectsRay && (((roots[i] === 0 || roots[i] === 1) && bbox.bottomRight().x > point.x) || (0 < roots[i] && roots[i] < 1))) {\n count++;\n }\n }\n\n return count;\n}","export default function last(array) {\n if (array) {\n return array[array.length - 1];\n }\n}","import Point from '../geometry/point';\nimport { last } from '../util';\n\nvar ShapeMap = {\n l: function(path, options) {\n var parameters = options.parameters;\n var position = options.position;\n\n for (var i = 0; i < parameters.length; i += 2) {\n var point = new Point(parameters[i], parameters[i + 1]);\n\n if (options.isRelative) {\n point.translateWith(position);\n }\n\n path.lineTo(point.x, point.y);\n\n position.x = point.x;\n position.y = point.y;\n }\n },\n\n c: function(path, options) {\n var parameters = options.parameters;\n var position = options.position;\n\n for (var i = 0; i < parameters.length; i += 6) {\n var controlOut = new Point(parameters[i], parameters[i + 1]);\n var controlIn = new Point(parameters[i + 2], parameters[i + 3]);\n var point = new Point(parameters[i + 4], parameters[i + 5]);\n if (options.isRelative) {\n controlIn.translateWith(position);\n controlOut.translateWith(position);\n point.translateWith(position);\n }\n\n path.curveTo(controlOut, controlIn, point);\n\n position.x = point.x;\n position.y = point.y;\n }\n },\n\n v: function(path, options) {\n var value = options.isRelative ? 0 : options.position.x;\n\n toLineParamaters(options.parameters, true, value);\n this.l(path, options);\n },\n\n h: function(path, options) {\n var value = options.isRelative ? 0 : options.position.y;\n\n toLineParamaters(options.parameters, false, value);\n this.l(path, options);\n },\n\n a: function(path, options) {\n var parameters = options.parameters;\n var position = options.position;\n\n for (var i = 0; i < parameters.length; i += 7) {\n var radiusX = parameters[i];\n var radiusY = parameters[i + 1];\n var rotation = parameters[i + 2];\n var largeArc = parameters[i + 3];\n var swipe = parameters[i + 4];\n var endPoint = new Point(parameters[i + 5], parameters[i + 6]);\n\n if (options.isRelative) {\n endPoint.translateWith(position);\n }\n if (position.x !== endPoint.x || position.y !== endPoint.y) {\n path.arcTo(endPoint, radiusX, radiusY, largeArc, swipe, rotation);\n\n position.x = endPoint.x;\n position.y = endPoint.y;\n }\n }\n },\n\n s: function(path, options) {\n var parameters = options.parameters;\n var position = options.position;\n var previousCommand = options.previousCommand;\n var lastControlIn;\n\n if (previousCommand === \"s\" || previousCommand === \"c\") {\n lastControlIn = last(last(path.paths).segments).controlIn();\n }\n\n for (var i = 0; i < parameters.length; i += 4) {\n var controlIn = new Point(parameters[i], parameters[i + 1]);\n var endPoint = new Point(parameters[i + 2], parameters[i + 3]);\n var controlOut = (void 0);\n\n if (options.isRelative) {\n controlIn.translateWith(position);\n endPoint.translateWith(position);\n }\n\n if (lastControlIn) {\n controlOut = reflectionPoint(lastControlIn, position);\n } else {\n controlOut = position.clone();\n }\n\n lastControlIn = controlIn;\n\n path.curveTo(controlOut, controlIn, endPoint);\n\n position.x = endPoint.x;\n position.y = endPoint.y;\n }\n },\n\n q: function(path, options) {\n var parameters = options.parameters;\n var position = options.position;\n\n for (var i = 0; i < parameters.length; i += 4) {\n var controlPoint = new Point(parameters[i], parameters[i + 1]);\n var endPoint = new Point(parameters[i + 2], parameters[i + 3]);\n\n if (options.isRelative) {\n controlPoint.translateWith(position);\n endPoint.translateWith(position);\n }\n\n var cubicControlPoints = quadraticToCubicControlPoints(position, controlPoint, endPoint);\n\n path.curveTo(cubicControlPoints.controlOut, cubicControlPoints.controlIn, endPoint);\n\n position.x = endPoint.x;\n position.y = endPoint.y;\n }\n },\n\n t: function(path, options) {\n var parameters = options.parameters;\n var position = options.position;\n var previousCommand = options.previousCommand;\n var controlPoint;\n\n if (previousCommand === \"q\" || previousCommand === \"t\") {\n var lastSegment = last(last(path.paths).segments);\n controlPoint = lastSegment.controlIn().clone()\n .translateWith(position.scaleCopy(-1 / 3))\n .scale(3 / 2);\n }\n\n for (var i = 0; i < parameters.length; i += 2) {\n var endPoint = new Point(parameters[i], parameters[i + 1]);\n if (options.isRelative) {\n endPoint.translateWith(position);\n }\n\n if (controlPoint) {\n controlPoint = reflectionPoint(controlPoint, position);\n } else {\n controlPoint = position.clone();\n }\n\n var cubicControlPoints = quadraticToCubicControlPoints(position, controlPoint, endPoint);\n\n path.curveTo(cubicControlPoints.controlOut, cubicControlPoints.controlIn, endPoint);\n\n position.x = endPoint.x;\n position.y = endPoint.y;\n }\n }\n};\n\nfunction toLineParamaters(parameters, isVertical, value) {\n var insertPosition = isVertical ? 0 : 1;\n\n for (var i = 0; i < parameters.length; i += 2) {\n parameters.splice(i + insertPosition, 0, value);\n }\n}\n\nfunction reflectionPoint(point, center) {\n if (point && center) {\n return center.scaleCopy(2).translate(-point.x, -point.y);\n }\n}\n\nvar third = 1 / 3;\n\nfunction quadraticToCubicControlPoints(position, controlPoint, endPoint) {\n var scaledPoint = controlPoint.clone().scale(2 / 3);\n return {\n controlOut: scaledPoint.clone().translateWith(position.scaleCopy(third)),\n controlIn: scaledPoint.translateWith(endPoint.scaleCopy(third))\n };\n}\n\nexport default ShapeMap;","import Point from '../geometry/point';\nimport ShapeMap from './shape-map';\n\nvar SEGMENT_REGEX = /([a-df-z]{1})([^a-df-z]*)(z)?/gi;\nvar SPLIT_REGEX = /[,\\s]?([+\\-]?(?:\\d*\\.\\d+|\\d+)(?:[eE][+\\-]?\\d+)?)/g;\nvar MOVE = \"m\";\nvar CLOSE = \"z\";\n\nfunction parseParameters(str) {\n var parameters = [];\n str.replace(SPLIT_REGEX, function(match, number) {\n parameters.push(parseFloat(number));\n });\n return parameters;\n}\n\nfunction parsePath(pathInstance, str) {\n var position = new Point();\n var previousCommand;\n\n str.replace(SEGMENT_REGEX, function (match, element, params, closePath) {\n var command = element.toLowerCase();\n var isRelative = command === element;\n var parameters = parseParameters(params.trim());\n\n if (command === MOVE) {\n if (isRelative) {\n position.x += parameters[0];\n position.y += parameters[1];\n } else {\n position.x = parameters[0];\n position.y = parameters[1];\n }\n\n pathInstance.moveTo(position.x, position.y);\n\n if (parameters.length > 2) {\n command = \"l\";\n parameters.splice(0, 2);\n }\n }\n\n if (ShapeMap[command]) {\n ShapeMap[command](\n pathInstance, {\n parameters: parameters,\n position: position,\n isRelative: isRelative,\n previousCommand: previousCommand\n }\n );\n\n if (closePath && closePath.toLowerCase() === CLOSE) {\n pathInstance.close();\n }\n } else if (command !== MOVE) {\n throw new Error(\"Error while parsing SVG path. Unsupported command: \" + command);\n }\n\n previousCommand = command;\n });\n\n return pathInstance;\n}\n\nexport default parsePath;\n\n","export default function limitValue(value, min, max) {\n return Math.max(Math.min(value, max), min);\n}","import GeometryElementsArray from './geometry-elements-array';\nimport Element from './element';\nimport paintable from '../mixins/paintable';\nimport measurable from '../mixins/measurable';\nimport Arc from '../geometry/arc';\nimport Rect from '../geometry/rect';\nimport Segment from '../geometry/segment';\nimport Point from '../geometry/point';\nimport Size from '../geometry/size';\nimport lineIntersectionsCount from '../geometry/math/line-intersections-count';\nimport { defined, last, rad } from '../util';\nimport parsePath from '../parsing/parse-path';\nimport elementsBoundingBox from './utils/elements-bounding-box';\nimport elementsClippedBoundingBox from './utils/elements-clippend-bounding-box';\nimport limitValue from '../util/limit-value';\n\n\nexport var Path = (function (superclass) {\n function Path(options) {\n superclass.call(this, options);\n this.segments = new GeometryElementsArray();\n this.segments.addObserver(this);\n\n if (!defined(this.options.stroke)) {\n this.stroke(\"#000\");\n\n if (!defined(this.options.stroke.lineJoin)) {\n this.options.set(\"stroke.lineJoin\", \"miter\");\n }\n }\n }\n\n if ( superclass ) Path.__proto__ = superclass;\n Path.prototype = Object.create( superclass && superclass.prototype );\n Path.prototype.constructor = Path;\n\n var prototypeAccessors = { nodeType: { configurable: true } };\n\n Path.parse = function parse (str, options) {\n return MultiPath.parse(str, options);\n };\n\n prototypeAccessors.nodeType.get = function () {\n return \"Path\";\n };\n\n Path.prototype.moveTo = function moveTo (x, y) {\n this.suspend();\n this.segments.elements([]);\n this.resume();\n\n this.lineTo(x, y);\n\n return this;\n };\n\n Path.prototype.lineTo = function lineTo (x, y) {\n var point = defined(y) ? new Point(x, y) : x;\n var segment = new Segment(point);\n\n this.segments.push(segment);\n\n return this;\n };\n\n Path.prototype.curveTo = function curveTo (controlOut, controlIn, point) {\n if (this.segments.length > 0) {\n var lastSegment = last(this.segments);\n var segment = new Segment(point, controlIn);\n this.suspend();\n lastSegment.controlOut(controlOut);\n this.resume();\n\n this.segments.push(segment);\n }\n\n return this;\n };\n\n Path.prototype.arc = function arc (startAngle, endAngle, radiusX, radiusY, anticlockwise) {\n if (this.segments.length > 0) {\n var lastSegment = last(this.segments);\n var anchor = lastSegment.anchor();\n var start = rad(startAngle);\n var center = new Point(anchor.x - radiusX * Math.cos(start),\n anchor.y - radiusY * Math.sin(start));\n var arc = new Arc(center, {\n startAngle: startAngle,\n endAngle: endAngle,\n radiusX: radiusX,\n radiusY: radiusY,\n anticlockwise: anticlockwise\n });\n\n this._addArcSegments(arc);\n }\n\n return this;\n };\n\n Path.prototype.arcTo = function arcTo (end, rx, ry, largeArc, swipe, rotation) {\n if (this.segments.length > 0) {\n var lastSegment = last(this.segments);\n var anchor = lastSegment.anchor();\n var arc = Arc.fromPoints(anchor, Point.create(end), rx, ry, largeArc, swipe, rotation);\n\n this._addArcSegments(arc);\n }\n return this;\n };\n\n Path.prototype._addArcSegments = function _addArcSegments (arc) {\n var this$1 = this;\n\n this.suspend();\n\n var curvePoints = arc.curvePoints();\n\n for (var i = 1; i < curvePoints.length; i += 3) {\n this$1.curveTo(curvePoints[i], curvePoints[i + 1], curvePoints[i + 2]);\n }\n\n this.resume();\n this.geometryChange();\n };\n\n Path.prototype.close = function close () {\n this.options.closed = true;\n this.geometryChange();\n\n return this;\n };\n\n Path.prototype.rawBBox = function rawBBox () {\n return this._bbox();\n };\n\n Path.prototype._containsPoint = function _containsPoint (point) {\n var segments = this.segments;\n var length = segments.length;\n var intersectionsCount = 0;\n var previous, current;\n\n for (var idx = 1; idx < length; idx++) {\n previous = segments[idx - 1];\n current = segments[idx];\n intersectionsCount += previous._intersectionsTo(current, point);\n }\n\n if (this.options.closed || !segments[0].anchor().equals(segments[length - 1].anchor())) {\n intersectionsCount += lineIntersectionsCount(segments[0].anchor(), segments[length - 1].anchor(), point);\n }\n\n return intersectionsCount % 2 !== 0;\n };\n\n Path.prototype._isOnPath = function _isOnPath (point, width) {\n var segments = this.segments;\n var length = segments.length;\n var pathWidth = width || this.options.stroke.width;\n\n if (length > 1) {\n if (segments[0]._isOnPathTo(segments[1], point, pathWidth, \"start\")) {\n return true;\n }\n\n for (var idx = 2; idx <= length - 2; idx++) {\n if (segments[idx - 1]._isOnPathTo(segments[idx], point, pathWidth)) {\n return true;\n }\n }\n\n if (segments[length - 2]._isOnPathTo(segments[length - 1], point, pathWidth, \"end\")) {\n return true;\n }\n }\n return false;\n };\n\n Path.prototype._bbox = function _bbox (matrix) {\n var segments = this.segments;\n var length = segments.length;\n var boundingBox;\n\n if (length === 1) {\n var anchor = segments[0].anchor().transformCopy(matrix);\n boundingBox = new Rect(anchor, Size.ZERO);\n } else if (length > 0) {\n for (var i = 1; i < length; i++) {\n var segmentBox = segments[i - 1].bboxTo(segments[i], matrix);\n if (boundingBox) {\n boundingBox = Rect.union(boundingBox, segmentBox);\n } else {\n boundingBox = segmentBox;\n }\n }\n }\n\n return boundingBox;\n };\n\n Path.fromRect = function fromRect (rect, options) {\n var path = new Path(options);\n var ref = rect.cornerRadius;\n var rx = ref[0];\n var ry = ref[1];\n\n if (rx === 0 && ry === 0) {\n path.moveTo(rect.topLeft())\n .lineTo(rect.topRight())\n .lineTo(rect.bottomRight())\n .lineTo(rect.bottomLeft())\n .close();\n } else {\n var origin = rect.origin;\n var x = origin.x;\n var y = origin.y;\n var width = rect.width();\n var height = rect.height();\n rx = limitValue(rx, 0, width / 2);\n ry = limitValue(ry, 0, height / 2);\n\n path.moveTo(x + rx, y)\n .lineTo(x + width - rx, y)\n .arcTo([ x + width, y + ry ], rx, ry, false)\n .lineTo(x + width, y + height - ry)\n .arcTo([ x + width - rx, y + height ], rx, ry, false)\n .lineTo(x + rx, y + height)\n .arcTo([ x, y + height - ry ], rx, ry, false)\n .lineTo(x, y + ry)\n .arcTo([ x + rx, y ], rx, ry, false);\n }\n\n return path;\n };\n\n Path.fromPoints = function fromPoints (points, options) {\n if (points) {\n var path = new Path(options);\n\n for (var i = 0; i < points.length; i++) {\n var point = Point.create(points[i]);\n if (point) {\n if (i === 0) {\n path.moveTo(point);\n } else {\n path.lineTo(point);\n }\n }\n }\n\n return path;\n }\n };\n\n Path.fromArc = function fromArc (arc, options) {\n var path = new Path(options);\n var startAngle = arc.startAngle;\n var start = arc.pointAt(startAngle);\n path.moveTo(start.x, start.y);\n path.arc(startAngle, arc.endAngle, arc.radiusX, arc.radiusY, arc.anticlockwise);\n return path;\n };\n\n Object.defineProperties( Path.prototype, prototypeAccessors );\n\n return Path;\n}(paintable(measurable(Element))));\n\nexport var MultiPath = (function (superclass) {\n function MultiPath(options) {\n superclass.call(this, options);\n this.paths = new GeometryElementsArray();\n this.paths.addObserver(this);\n\n if (!defined(this.options.stroke)) {\n this.stroke(\"#000\");\n }\n }\n\n if ( superclass ) MultiPath.__proto__ = superclass;\n MultiPath.prototype = Object.create( superclass && superclass.prototype );\n MultiPath.prototype.constructor = MultiPath;\n\n var prototypeAccessors$1 = { nodeType: { configurable: true } };\n\n MultiPath.parse = function parse (str, options) {\n var instance = new MultiPath(options);\n return parsePath(instance, str);\n };\n\n prototypeAccessors$1.nodeType.get = function () {\n return \"MultiPath\";\n };\n\n MultiPath.prototype.moveTo = function moveTo (x, y) {\n var path = new Path();\n path.moveTo(x, y);\n\n this.paths.push(path);\n\n return this;\n };\n\n MultiPath.prototype.lineTo = function lineTo (x, y) {\n if (this.paths.length > 0) {\n last(this.paths).lineTo(x, y);\n }\n\n return this;\n };\n\n MultiPath.prototype.curveTo = function curveTo (controlOut, controlIn, point) {\n if (this.paths.length > 0) {\n last(this.paths).curveTo(controlOut, controlIn, point);\n }\n\n return this;\n };\n\n MultiPath.prototype.arc = function arc (startAngle, endAngle, radiusX, radiusY, anticlockwise) {\n if (this.paths.length > 0) {\n last(this.paths).arc(startAngle, endAngle, radiusX, radiusY, anticlockwise);\n }\n\n return this;\n };\n\n MultiPath.prototype.arcTo = function arcTo (end, rx, ry, largeArc, swipe, rotation) {\n if (this.paths.length > 0) {\n last(this.paths).arcTo(end, rx, ry, largeArc, swipe, rotation);\n }\n\n return this;\n };\n\n MultiPath.prototype.close = function close () {\n if (this.paths.length > 0) {\n last(this.paths).close();\n }\n\n return this;\n };\n\n MultiPath.prototype._bbox = function _bbox (matrix) {\n return elementsBoundingBox(this.paths, true, matrix);\n };\n\n MultiPath.prototype.rawBBox = function rawBBox () {\n return elementsBoundingBox(this.paths, false);\n };\n\n MultiPath.prototype._containsPoint = function _containsPoint (point) {\n var paths = this.paths;\n\n for (var idx = 0; idx < paths.length; idx++) {\n if (paths[idx]._containsPoint(point)) {\n return true;\n }\n }\n return false;\n };\n\n MultiPath.prototype._isOnPath = function _isOnPath (point) {\n var paths = this.paths;\n var width = this.options.stroke.width;\n\n for (var idx = 0; idx < paths.length; idx++) {\n if (paths[idx]._isOnPath(point, width)) {\n return true;\n }\n }\n return false;\n };\n\n MultiPath.prototype._clippedBBox = function _clippedBBox (transformation) {\n return elementsClippedBoundingBox(this.paths, this.currentTransform(transformation));\n };\n\n Object.defineProperties( MultiPath.prototype, prototypeAccessors$1 );\n\n return MultiPath;\n}(paintable(measurable(Element))));\n\n","import { defined } from '../util';\n\nfunction geometryAccessor(name) {\n var fieldName = \"_\" + name;\n return function(value) {\n if (defined(value)) {\n this._observerField(fieldName, value);\n this.geometryChange();\n return this;\n }\n\n return this[fieldName];\n };\n}\n\nfunction defineGeometryAccessors(fn, names) {\n for (var i = 0; i < names.length; i++) {\n fn[names[i]] = geometryAccessor(names[i]);\n }\n}\n\nvar withGeometry = function (TBase, names) {\n if ( names === void 0 ) names = [ \"geometry\" ];\n\n var result = (function (TBase) {\n function result () {\n TBase.apply(this, arguments);\n }if ( TBase ) result.__proto__ = TBase;\n result.prototype = Object.create( TBase && TBase.prototype );\n result.prototype.constructor = result;\n\n \n\n return result;\n }(TBase));\n defineGeometryAccessors(result.prototype, names);\n\n return result;\n};\n\nexport default withGeometry;\n","import withGeometry from '../mixins/with-geometry';\nimport Element from './element';\nimport Rect from '../geometry/rect';\nimport toMatrix from '../geometry/to-matrix';\nimport { defined } from '../util';\n\n\nvar Image = (function (superclass) {\n function Image(src, rect, options) {\n if ( rect === void 0 ) rect = new Rect();\n if ( options === void 0 ) options = {};\n\n superclass.call(this, options);\n\n this.src(src);\n this.rect(rect);\n }\n\n if ( superclass ) Image.__proto__ = superclass;\n Image.prototype = Object.create( superclass && superclass.prototype );\n Image.prototype.constructor = Image;\n\n var prototypeAccessors = { nodeType: { configurable: true } };\n\n prototypeAccessors.nodeType.get = function () {\n return \"Image\";\n };\n\n Image.prototype.src = function src (value) {\n if (defined(value)) {\n this.options.set(\"src\", value);\n return this;\n }\n\n return this.options.get(\"src\");\n };\n\n Image.prototype.bbox = function bbox (transformation) {\n var combinedMatrix = toMatrix(this.currentTransform(transformation));\n return this._rect.bbox(combinedMatrix);\n };\n\n Image.prototype.rawBBox = function rawBBox () {\n return this._rect.bbox();\n };\n\n Image.prototype._containsPoint = function _containsPoint (point) {\n return this._rect.containsPoint(point);\n };\n\n Image.prototype._hasFill = function _hasFill () {\n return this.src();\n };\n\n Object.defineProperties( Image.prototype, prototypeAccessors );\n\n return Image;\n}(withGeometry(Element, [ \"rect\" ])));\n\nexport default Image;","import ElementsArray from '../shapes/elements-array';\n\nvar StopsArray = (function (ElementsArray) {\n function StopsArray () {\n ElementsArray.apply(this, arguments);\n }\n\n if ( ElementsArray ) StopsArray.__proto__ = ElementsArray;\n StopsArray.prototype = Object.create( ElementsArray && ElementsArray.prototype );\n StopsArray.prototype.constructor = StopsArray;\n\n StopsArray.prototype._change = function _change () {\n this.optionsChange({\n field: \"stops\"\n });\n };\n\n return StopsArray;\n}(ElementsArray));\n\nexport default StopsArray;","import { defined } from '../util';\n\nfunction optionsAccessor(name) {\n return function(value) {\n if (defined(value)) {\n this.options.set(name, value);\n return this;\n }\n\n return this.options.get(name);\n };\n}\n\nfunction defineOptionsAccessors(fn, names) {\n for (var i = 0; i < names.length; i++) {\n fn[names[i]] = optionsAccessor(names[i]);\n }\n}\n\nvar withOptions = function (TBase, names) {\n var result = (function (TBase) {\n function result () {\n TBase.apply(this, arguments);\n }if ( TBase ) result.__proto__ = TBase;\n result.prototype = Object.create( TBase && TBase.prototype );\n result.prototype.constructor = result;\n\n \n\n return result;\n }(TBase));\n defineOptionsAccessors(result.prototype, names);\n\n return result;\n};\n\nexport default withOptions;\n","import OptionsStore from '../core/options-store';\nimport withOptions from '../mixins/with-options';\nimport HasObservers from '../core/has-observers';\nimport { defined } from '../util';\n\n\nvar options = [ \"offset\", \"color\", \"opacity\" ];\n\nvar GradientStop = (function (superclass) {\n function GradientStop(offset, color, opacity) {\n superclass.call(this);\n\n this.options = new OptionsStore({\n offset: offset,\n color: color,\n opacity: defined(opacity) ? opacity : 1\n });\n\n this.options.addObserver(this);\n }\n\n if ( superclass ) GradientStop.__proto__ = superclass;\n GradientStop.prototype = Object.create( superclass && superclass.prototype );\n GradientStop.prototype.constructor = GradientStop;\n\n GradientStop.create = function create (arg) {\n if (defined(arg)) {\n var stop;\n if (arg instanceof GradientStop) {\n stop = arg;\n } else if (arg.length > 1) {\n stop = new GradientStop(arg[0], arg[1], arg[2]);\n } else {\n stop = new GradientStop(arg.offset, arg.color, arg.opacity);\n }\n\n return stop;\n }\n };\n\n return GradientStop;\n}(withOptions(HasObservers, options)));\n\nexport default GradientStop;\n","import StopsArray from './stops-array';\nimport GradientStop from './gradient-stop';\nimport HasObservers from '../core/has-observers';\nimport { defined, definitionId } from '../util';\n\nvar Gradient = (function (HasObservers) {\n function Gradient(options) {\n if ( options === void 0 ) options = {};\n\n HasObservers.call(this);\n\n this.stops = new StopsArray(this._createStops(options.stops));\n this.stops.addObserver(this);\n this._userSpace = options.userSpace;\n this.id = definitionId();\n }\n\n if ( HasObservers ) Gradient.__proto__ = HasObservers;\n Gradient.prototype = Object.create( HasObservers && HasObservers.prototype );\n Gradient.prototype.constructor = Gradient;\n\n var prototypeAccessors = { nodeType: { configurable: true } };\n\n prototypeAccessors.nodeType.get = function () {\n return \"Gradient\";\n };\n\n Gradient.prototype.userSpace = function userSpace (value) {\n if (defined(value)) {\n this._userSpace = value;\n this.optionsChange();\n return this;\n }\n\n return this._userSpace;\n };\n\n Gradient.prototype._createStops = function _createStops (stops) {\n if ( stops === void 0 ) stops = [];\n\n var result = [];\n for (var idx = 0; idx < stops.length; idx++) {\n result.push(GradientStop.create(stops[idx]));\n }\n\n return result;\n };\n\n Gradient.prototype.addStop = function addStop (offset, color, opacity) {\n this.stops.push(new GradientStop(offset, color, opacity));\n };\n\n Gradient.prototype.removeStop = function removeStop (stop) {\n var index = this.stops.indexOf(stop);\n if (index >= 0) {\n this.stops.splice(index, 1);\n }\n };\n\n Gradient.prototype.optionsChange = function optionsChange (e) {\n this.trigger(\"optionsChange\", {\n field: \"gradient\" + (e ? \".\" + e.field : \"\"),\n value: this\n });\n };\n\n Gradient.prototype.geometryChange = function geometryChange () {\n this.optionsChange();\n };\n\n Object.defineProperties( Gradient.prototype, prototypeAccessors );\n\n return Gradient;\n}(HasObservers));\n\nexport default Gradient;\n","import withPoints from '../mixins/with-points';\nimport Point from '../geometry/point';\nimport Gradient from './gradient';\n\n\nvar points = [ \"start\", \"end\" ];\n\nvar LinearGradient = (function (superclass) {\n function LinearGradient(options) {\n if ( options === void 0 ) options = {};\n\n superclass.call(this, options);\n\n this.start(options.start || new Point());\n this.end(options.end || new Point(1, 0));\n }\n\n if ( superclass ) LinearGradient.__proto__ = superclass;\n LinearGradient.prototype = Object.create( superclass && superclass.prototype );\n LinearGradient.prototype.constructor = LinearGradient;\n\n return LinearGradient;\n}(withPoints(Gradient, points)));\n\nexport default LinearGradient;\n","import GeometryCircle from '../geometry/circle';\nimport paintable from '../mixins/paintable';\nimport measurable from '../mixins/measurable';\nimport withGeometry from '../mixins/with-geometry';\nimport Element from './element';\nimport { defined } from '../util';\n\nvar DEFAULT_STROKE = \"#000\";\n\nvar Circle = (function (superclass) {\n function Circle(geometry, options) {\n if ( geometry === void 0 ) geometry = new GeometryCircle();\n if ( options === void 0 ) options = {};\n\n superclass.call(this, options);\n\n this.geometry(geometry);\n\n if (!defined(this.options.stroke)) {\n this.stroke(DEFAULT_STROKE);\n }\n }\n\n if ( superclass ) Circle.__proto__ = superclass;\n Circle.prototype = Object.create( superclass && superclass.prototype );\n Circle.prototype.constructor = Circle;\n\n var prototypeAccessors = { nodeType: { configurable: true } };\n\n prototypeAccessors.nodeType.get = function () {\n return \"Circle\";\n };\n\n Circle.prototype.rawBBox = function rawBBox () {\n return this._geometry.bbox();\n };\n\n Circle.prototype._bbox = function _bbox (matrix) {\n return this._geometry.bbox(matrix);\n };\n\n Circle.prototype._containsPoint = function _containsPoint (point) {\n return this.geometry().containsPoint(point);\n };\n\n Circle.prototype._isOnPath = function _isOnPath (point) {\n return this.geometry()._isOnPath(point, this.options.stroke.width / 2);\n };\n\n Object.defineProperties( Circle.prototype, prototypeAccessors );\n\n return Circle;\n}(paintable(measurable(withGeometry(Element)))));\n\nexport default Circle;\n","import { encodeUTF8 } from './encode-utf';\n\nvar KEY_STR = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\nexport default function encodeBase64(input) {\n var output = \"\";\n var i = 0;\n\n var utfInput = encodeUTF8(input);\n\n while (i < utfInput.length) {\n var chr1 = utfInput.charCodeAt(i++);\n var chr2 = utfInput.charCodeAt(i++);\n var chr3 = utfInput.charCodeAt(i++);\n\n var enc1 = chr1 >> 2;\n var enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n var enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n var enc4 = chr3 & 63;\n\n if (isNaN(chr2)) {\n enc3 = enc4 = 64;\n } else if (isNaN(chr3)) {\n enc4 = 64;\n }\n\n output = output +\n KEY_STR.charAt(enc1) + KEY_STR.charAt(enc2) +\n KEY_STR.charAt(enc3) + KEY_STR.charAt(enc4);\n }\n\n return output;\n}","/* eslint-disable no-multi-spaces, key-spacing, indent, camelcase, space-before-blocks, eqeqeq, brace-style */\n/* eslint-disable space-infix-ops, space-before-function-paren, array-bracket-spacing, object-curly-spacing */\n/* eslint-disable no-nested-ternary, max-params, default-case, no-else-return, no-empty, yoda */\n/* eslint-disable no-param-reassign, no-var, block-scoped-var */\n\nimport * as geo from \"../geometry\";\nimport * as PDF from \"../pdf\";\nimport { arabicToRoman, createPromise, measureText, mergeSort } from '../util';\nimport { parseColor as utils_parseColor, support, template as compileTemplate } from \"../common\";\nimport { Path, Text, Group, Image, Circle, LinearGradient } from \"../drawing\";\nimport { encodeBase64 } from \"../util\";\n\nvar browser = support.browser || {};\n/*\n\n XXX: to test:\n\n - cloneNodes function:\n - drawing document containing canvas with page breaking\n - drawing document with named radio -s (should not clear selection)\n - IE9/IE10 don't support el.dataset; do they copy user data?\n\n - repeating table headers/footers on page breaking\n\n - forceBreak, keepTogether\n\n - avoidLinks\n\n */\n\n/* -----[ local vars ]----- */\n\nfunction slice(thing) {\n return Array.prototype.slice.call(thing);\n}\n\nvar KENDO_PSEUDO_ELEMENT = \"KENDO-PSEUDO-ELEMENT\";\n\nvar IMAGE_CACHE = {};\n\nvar nodeInfo = {};\nnodeInfo._root = nodeInfo;\n\n/* -----[ Custom Text node to speed up rendering in PDF ]----- */\n\nvar inBrowser = typeof window !== 'undefined';\nvar microsoft = inBrowser ? browser.msie || browser.edge : false;\n\nvar TextRect = (function (Text) {\n function TextRect(str, rect, options) {\n Text.call(this, str, rect.getOrigin(), options);\n this._pdfRect = rect;\n }\n\n if ( Text ) TextRect.__proto__ = Text;\n TextRect.prototype = Object.create( Text && Text.prototype );\n TextRect.prototype.constructor = TextRect;\n TextRect.prototype.rect = function rect () {\n // this is the crux of it: we can avoid a call to\n // measure(), which is what the base class does, since we\n // already know the rect. measure() is s-l-o-w.\n return this._pdfRect;\n };\n TextRect.prototype.rawBBox = function rawBBox () {\n // also let's avoid creating a new rectangle.\n return this._pdfRect;\n };\n\n return TextRect;\n}(Text));\n\nfunction addClass(el, cls) {\n if (el.classList) {\n el.classList.add(cls);\n } else {\n el.className += \" \" + cls;\n }\n}\n\nfunction removeClass(el, cls) {\n if (el.classList) {\n el.classList.remove(cls);\n } else {\n el.className = el.className.split(/\\s+/).reduce(function(a, word){\n if (word != cls) {\n a.push(word);\n }\n return a;\n }, []).join(\" \");\n }\n}\n\nfunction setCSS(el, styles) {\n Object.keys(styles).forEach(function(key){\n el.style[key] = styles[key];\n });\n}\n\nvar matches = typeof Element !== \"undefined\" && Element.prototype && (function(p){\n if (p.matches) {\n return function(el, selector) { return el.matches(selector); };\n }\n if (p.webkitMatchesSelector) {\n return function(el, selector) { return el.webkitMatchesSelector(selector); };\n }\n if (p.mozMatchesSelector) {\n return function(el, selector) { return el.mozMatchesSelector(selector); };\n }\n if (p.msMatchesSelector) {\n return function(el, selector) { return el.msMatchesSelector(selector); };\n }\n return function(s) {\n\treturn [].indexOf.call(document.querySelectorAll(s), this) !== -1;\n };\n})(Element.prototype);\n\nfunction closest(el, selector) {\n if (el.closest) {\n return el.closest(selector);\n }\n // IE: stringifying rather than simply comparing with `document`,\n // which is not iframe-proof and fails in editor export —\n // https://github.com/telerik/kendo/issues/6721\n while (el && !/^\\[object (?:HTML)?Document\\]$/.test(String(el))) {\n if (el.nodeType == 1 /* Element */ && matches(el, selector)) {\n return el;\n }\n el = el.parentNode;\n }\n}\n\n// clone nodes ourselves, so that we redraw