From 7f727480e8c198a69d5b1658bba405afc4be58bb Mon Sep 17 00:00:00 2001 From: viction Date: Thu, 23 Dec 2021 16:59:48 +0000 Subject: [PATCH 1/9] feat: allowHTML --- README.md | 9 ++++ src/scripts/choices.ts | 8 +-- src/scripts/constants.test.ts | 1 + src/scripts/defaults.ts | 1 + src/scripts/interfaces/options.ts | 10 ++++ src/scripts/templates.ts | 81 +++++++++++++++---------------- 6 files changed, 64 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index ecf188b..02b2f1f 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,7 @@ Or include Choices directly: removeItems: true, removeItemButton: false, editItems: false, + allowHTML: true duplicateItemsAllowed: true, delimiter: ',', paste: true, @@ -314,6 +315,14 @@ Pass an array of objects: **Usage:** Whether a user can edit items. An item's value can be edited by pressing the backspace. +### allowHTML + +**Type:** `Boolean` **Default:** `true` + +**Input types affected:** `text`, `select-one`, `select-multiple + +**Usage:** Whether HTML should be shown properly when showing choices. (Can be used to perform XSS attacks if not disabled or handled correctly) + ### duplicateItemsAllowed **Type:** `Boolean` **Default:** `true` diff --git a/src/scripts/choices.ts b/src/scripts/choices.ts index 772d8df..7c79684 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -151,6 +151,10 @@ class Choices implements Choices { | HTMLSelectElement = '[data-choice]', userConfig: Partial = {}, ) { + if (userConfig.allowHTML === undefined) { + console.warn('Deprecation warning: allowHTML in the future will be defaulted to false. You must explicitly set it to true to properly display html tags in choices.'); + } + this.config = merge.all( [DEFAULT_CONFIG, Choices.defaults.options, userConfig], // When merging array configs, replace with a copy of the userConfig array, @@ -2105,9 +2109,7 @@ class Choices implements Choices { } _getTemplate(template: string, ...args: any): any { - const { classNames } = this.config; - - return this._templates[template].call(this, classNames, ...args); + return this._templates[template].call(this, this.config, ...args); } _createTemplates(): void { diff --git a/src/scripts/constants.test.ts b/src/scripts/constants.test.ts index 24af92d..807016d 100644 --- a/src/scripts/constants.test.ts +++ b/src/scripts/constants.test.ts @@ -54,6 +54,7 @@ describe('constants', () => { expect(DEFAULT_CONFIG.removeItems).to.be.a('boolean'); expect(DEFAULT_CONFIG.removeItemButton).to.be.a('boolean'); expect(DEFAULT_CONFIG.editItems).to.be.a('boolean'); + expect(DEFAULT_CONFIG.allowHTML).to.be.a('boolean'); expect(DEFAULT_CONFIG.duplicateItemsAllowed).to.be.a('boolean'); expect(DEFAULT_CONFIG.delimiter).to.be.a('string'); expect(DEFAULT_CONFIG.paste).to.be.a('boolean'); diff --git a/src/scripts/defaults.ts b/src/scripts/defaults.ts index e5562b4..a67e363 100644 --- a/src/scripts/defaults.ts +++ b/src/scripts/defaults.ts @@ -42,6 +42,7 @@ export const DEFAULT_CONFIG: Options = { removeItems: true, removeItemButton: false, editItems: false, + allowHTML: true, duplicateItemsAllowed: true, delimiter: ',', paste: true, diff --git a/src/scripts/interfaces/options.ts b/src/scripts/interfaces/options.ts index 8f08b5e..6819873 100644 --- a/src/scripts/interfaces/options.ts +++ b/src/scripts/interfaces/options.ts @@ -159,6 +159,16 @@ export interface Options { */ editItems: boolean; + /** + * Whether HTML should be shown properly when showing choices. + * (Can be used to perform XSS attacks if not disabled or handled correctly) + * + * **Input types affected:** text, select-one, select-multiple + * + * @default true + */ + allowHTML: boolean; + /** * Whether each inputted/chosen item should be unique. * diff --git a/src/scripts/templates.ts b/src/scripts/templates.ts index 15d2ce0..3b93549 100644 --- a/src/scripts/templates.ts +++ b/src/scripts/templates.ts @@ -4,14 +4,14 @@ */ import { Choice } from './interfaces/choice'; -import { ClassNames } from './interfaces/class-names'; import { Group } from './interfaces/group'; import { Item } from './interfaces/item'; +import { Options } from './interfaces/options'; import { PassedElementType } from './interfaces/passed-element-type'; const templates = { containerOuter( - { containerOuter }: Pick, + { classNames: { containerOuter } }: Options, dir: HTMLElement['dir'], isSelectElement: boolean, isSelectOneElement: boolean, @@ -46,19 +46,19 @@ const templates = { }, containerInner({ - containerInner, - }: Pick): HTMLDivElement { + classNames: { containerInner }, + }: Options): HTMLDivElement { return Object.assign(document.createElement('div'), { className: containerInner, }); }, - itemList( - { + itemList({ + classNames: { list, listSingle, listItems, - }: Pick, + }}: Options, isSelectOneElement: boolean, ): HTMLDivElement { return Object.assign(document.createElement('div'), { @@ -67,26 +67,22 @@ const templates = { }, placeholder( - { placeholder }: Pick, + { allowHTML, classNames: { placeholder } }: Options, value: string, ): HTMLDivElement { return Object.assign(document.createElement('div'), { className: placeholder, - innerHTML: value, + [allowHTML ? 'innerHTML' : 'innerText']: value, }); }, - item( - { + item({ allowHTML, classNames: { item, button, highlightedState, itemSelectable, placeholder, - }: Pick< - ClassNames, - 'item' | 'button' | 'highlightedState' | 'itemSelectable' | 'placeholder' - >, + } }: Options, { id, value, @@ -101,7 +97,7 @@ const templates = { ): HTMLDivElement { const div = Object.assign(document.createElement('div'), { className: item, - innerHTML: label, + [allowHTML ? 'innerHTML' : 'innerText']: label, }); Object.assign(div.dataset, { @@ -135,7 +131,7 @@ const templates = { const removeButton = Object.assign(document.createElement('button'), { type: 'button', className: button, - innerHTML: REMOVE_ITEM_TEXT, + [allowHTML ? 'innerHTML' : 'innerText']: REMOVE_ITEM_TEXT, }); removeButton.setAttribute( 'aria-label', @@ -149,7 +145,7 @@ const templates = { }, choiceList( - { list }: Pick, + { classNames: { list } }: Options, isSelectOneElement: boolean, ): HTMLDivElement { const div = Object.assign(document.createElement('div'), { @@ -164,12 +160,13 @@ const templates = { return div; }, - choiceGroup( - { + choiceGroup({ + allowHTML, + classNames: { group, groupHeading, itemDisabled, - }: Pick, + } }: Options, { id, value, disabled }: Group, ): HTMLDivElement { const div = Object.assign(document.createElement('div'), { @@ -191,30 +188,24 @@ const templates = { div.appendChild( Object.assign(document.createElement('div'), { className: groupHeading, - innerHTML: value, + [allowHTML ? 'innerHTML' : 'innerText']: value, }), ); return div; }, - choice( - { + choice({ + allowHTML, + classNames: { item, itemChoice, itemSelectable, selectedState, itemDisabled, placeholder, - }: Pick< - ClassNames, - | 'item' - | 'itemChoice' - | 'itemSelectable' - | 'selectedState' - | 'itemDisabled' - | 'placeholder' - >, + } + }: Options, { id, value, @@ -229,7 +220,7 @@ const templates = { ): HTMLDivElement { const div = Object.assign(document.createElement('div'), { id: elementId, - innerHTML: label, + [allowHTML ? 'innerHTML' : 'innerText']: label, className: `${item} ${itemChoice}`, }); @@ -263,7 +254,7 @@ const templates = { }, input( - { input, inputCloned }: Pick, + { classNames: { input, inputCloned } }: Options, placeholderValue: string, ): HTMLInputElement { const inp = Object.assign(document.createElement('input'), { @@ -283,9 +274,11 @@ const templates = { }, dropdown({ - list, - listDropdown, - }: Pick): HTMLDivElement { + classNames: { + list, + listDropdown, + } + }: Options): HTMLDivElement { const div = document.createElement('div'); div.classList.add(list, listDropdown); @@ -294,14 +287,16 @@ const templates = { return div; }, - notice( - { + notice({ + allowHTML, + classNames: { item, itemChoice, noResults, noChoices, - }: Pick, - innerHTML: string, + } + }: Options, + innerText: string, type: 'no-choices' | 'no-results' | '' = '', ): HTMLDivElement { const classes = [item, itemChoice]; @@ -313,7 +308,7 @@ const templates = { } return Object.assign(document.createElement('div'), { - innerHTML, + [allowHTML ? 'innerHTML' : 'innerText']: innerText, className: classes.join(' '), }); }, From 6b16e939770b0ed0938fe7b2696c1fa689d3cbca Mon Sep 17 00:00:00 2001 From: viction Date: Fri, 24 Dec 2021 17:32:50 +0000 Subject: [PATCH 2/9] fix: template testing & type errors --- src/scripts/choices.ts | 4 +- src/scripts/interfaces/options.ts | 6 +- src/scripts/templates.test.ts | 177 +++++++++++++++++++----------- 3 files changed, 117 insertions(+), 70 deletions(-) diff --git a/src/scripts/choices.ts b/src/scripts/choices.ts index 7c79684..f663955 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -152,7 +152,9 @@ class Choices implements Choices { userConfig: Partial = {}, ) { if (userConfig.allowHTML === undefined) { - console.warn('Deprecation warning: allowHTML in the future will be defaulted to false. You must explicitly set it to true to properly display html tags in choices.'); + console.warn( + 'Deprecation warning: allowHTML in the future will be defaulted to false. You must explicitly set it to true to properly display html tags in choices.', + ); } this.config = merge.all( diff --git a/src/scripts/interfaces/options.ts b/src/scripts/interfaces/options.ts index 6819873..ca0b81c 100644 --- a/src/scripts/interfaces/options.ts +++ b/src/scripts/interfaces/options.ts @@ -160,11 +160,11 @@ export interface Options { editItems: boolean; /** - * Whether HTML should be shown properly when showing choices. + * Whether HTML should be shown properly when showing choices. * (Can be used to perform XSS attacks if not disabled or handled correctly) - * + * * **Input types affected:** text, select-one, select-multiple - * + * * @default true */ allowHTML: boolean; diff --git a/src/scripts/templates.test.ts b/src/scripts/templates.test.ts index 1c75ca7..83fdc30 100644 --- a/src/scripts/templates.test.ts +++ b/src/scripts/templates.test.ts @@ -1,6 +1,9 @@ import { expect } from 'chai'; import templates from './templates'; import { strToEl } from './lib/utils'; +import { DEFAULT_CLASSNAMES, DEFAULT_CONFIG } from './defaults'; +import { Options } from './interfaces/options'; +import { ClassNames } from './interfaces/class-names'; /** * @param {HTMLElement} element1 @@ -21,11 +24,25 @@ function expectEqualElements(element1, element2): void { } } +function createOptionsWithPartialClasses( + classNames: Partial, + options: Partial = {}, +): Options { + return { + ...DEFAULT_CONFIG, + ...options, + classNames: { + ...DEFAULT_CLASSNAMES, + ...classNames, + }, + }; +} + describe('templates', () => { describe('containerOuter', () => { - const classes = { + const options = createOptionsWithPartialClasses({ containerOuter: 'class-1', - }; + }); const direction = 'rtl'; describe('select element', () => { @@ -38,7 +55,7 @@ describe('templates', () => { const expectedOutput = strToEl(`
{
`); const actualOutput = templates.containerOuter( - classes, + options, direction, isSelectElement, isSelectOneElement, @@ -69,7 +86,7 @@ describe('templates', () => { const expectedOutput = strToEl(`
{
`); const actualOutput = templates.containerOuter( - classes, + options, direction, isSelectElement, isSelectOneElement, @@ -100,7 +117,7 @@ describe('templates', () => { const expectedOutput = strToEl(`
{
`); const actualOutput = templates.containerOuter( - classes, + options, direction, isSelectElement, isSelectOneElement, @@ -133,7 +150,7 @@ describe('templates', () => { const expectedOutput = strToEl(` `); const actualOutput = templates.containerOuter( - classes, + options, direction, isSelectElement, isSelectOneElement, @@ -157,31 +174,31 @@ describe('templates', () => { describe('containerInner', () => { it('returns expected html', () => { - const classes = { + const innerOptions = createOptionsWithPartialClasses({ containerInner: 'class-1', - }; + }); const expectedOutput = strToEl( - `
`, + `
`, ); - const actualOutput = templates.containerInner(classes); + const actualOutput = templates.containerInner(innerOptions); expectEqualElements(actualOutput, expectedOutput); }); }); describe('itemList', () => { - const classes = { + const itemOptions = createOptionsWithPartialClasses({ list: 'class-1', listSingle: 'class-2', listItems: 'class-3', - }; + }); describe('select one element', () => { it('returns expected html', () => { const expectedOutput = strToEl( - `
`, + `
`, ); - const actualOutput = templates.itemList(classes, true); + const actualOutput = templates.itemList(itemOptions, true); expectEqualElements(actualOutput, expectedOutput); }); @@ -190,9 +207,9 @@ describe('templates', () => { describe('non select one element', () => { it('returns expected html', () => { const expectedOutput = strToEl( - `
`, + `
`, ); - const actualOutput = templates.itemList(classes, false); + const actualOutput = templates.itemList(itemOptions, false); expectEqualElements(actualOutput, expectedOutput); }); @@ -201,33 +218,33 @@ describe('templates', () => { describe('placeholder', () => { it('returns expected html', () => { - const classes = { + const placeholderOptions = createOptionsWithPartialClasses({ placeholder: 'class-1', - }; + }); const value = 'test'; const expectedOutput = strToEl(` -
${value}
`); - const actualOutput = templates.placeholder(classes, value); +
${value}
`); + const actualOutput = templates.placeholder(placeholderOptions, value); expectEqualElements(actualOutput, expectedOutput); }); }); describe('choiceList', () => { - const classes = { + const choiceListOptions = createOptionsWithPartialClasses({ list: 'class-1', - }; + }); describe('select one element', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
`); - const actualOutput = templates.choiceList(classes, true); + const actualOutput = templates.choiceList(choiceListOptions, true); expectEqualElements(actualOutput, expectedOutput); }); @@ -237,13 +254,13 @@ describe('templates', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
`); - const actualOutput = templates.choiceList(classes, false); + const actualOutput = templates.choiceList(choiceListOptions, false); expectEqualElements(actualOutput, expectedOutput); }); @@ -251,11 +268,11 @@ describe('templates', () => { }); describe('choiceGroup', () => { - const classes = { + const groupOptions = createOptionsWithPartialClasses({ group: 'class-1', groupHeading: 'class-2', itemDisabled: 'class-3', - }; + }); let data; @@ -271,16 +288,16 @@ describe('templates', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
-
${data.value}
+
${data.value}
`); - const actualOutput = templates.choiceGroup(classes, data); + const actualOutput = templates.choiceGroup(groupOptions, data); expectEqualElements(actualOutput, expectedOutput); }); @@ -297,17 +314,17 @@ describe('templates', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
-
${data.value}
+
${data.value}
`); - const actualOutput = templates.choiceGroup(classes, data); + const actualOutput = templates.choiceGroup(groupOptions, data); expectEqualElements(actualOutput, expectedOutput); }); @@ -315,14 +332,14 @@ describe('templates', () => { }); describe('choice', () => { - const classes = { + const choiceOptions = createOptionsWithPartialClasses({ item: 'class-1', itemChoice: 'class-2', itemDisabled: 'class-3', itemSelectable: 'class-4', placeholder: 'class-5', selectedState: 'class-6', - }; + }); const itemSelectText = 'test 6'; @@ -344,7 +361,7 @@ describe('templates', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
{ ${data.label}
`); - const actualOutput = templates.choice(classes, data, itemSelectText); + const actualOutput = templates.choice( + choiceOptions, + data, + itemSelectText, + ); expectEqualElements(actualOutput, expectedOutput); }); @@ -373,7 +394,7 @@ describe('templates', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
{ ${data.label}
`); - const actualOutput = templates.choice(classes, data, itemSelectText); + const actualOutput = templates.choice( + choiceOptions, + data, + itemSelectText, + ); expectEqualElements(actualOutput, expectedOutput); }); @@ -403,7 +428,7 @@ describe('templates', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
{ ${data.label}
`); - const actualOutput = templates.choice(classes, data, itemSelectText); + const actualOutput = templates.choice( + choiceOptions, + data, + itemSelectText, + ); expectEqualElements(actualOutput, expectedOutput); }); @@ -432,7 +461,7 @@ describe('templates', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
{ ${data.label}
`); - const actualOutput = templates.choice(classes, data, itemSelectText); + const actualOutput = templates.choice( + choiceOptions, + data, + itemSelectText, + ); expectEqualElements(actualOutput, expectedOutput); }); @@ -461,7 +494,7 @@ describe('templates', () => { it('returns expected html', () => { const expectedOutput = strToEl(`
{ ${data.label}
`); - const actualOutput = templates.choice(classes, data, itemSelectText); + const actualOutput = templates.choice( + choiceOptions, + data, + itemSelectText, + ); expectEqualElements(actualOutput, expectedOutput); }); @@ -481,10 +518,10 @@ describe('templates', () => { }); describe('input', () => { - const classes = { + const inputOptions = createOptionsWithPartialClasses({ input: 'class-1', inputCloned: 'class-2', - }; + }); it('returns expected html', () => { /* @@ -496,52 +533,52 @@ describe('templates', () => { `); - const actualOutput = templates.input(classes, 'test placeholder'); + const actualOutput = templates.input(inputOptions, 'test placeholder'); expectEqualElements(actualOutput, expectedOutput); }); }); describe('dropdown', () => { - const classes = { + const dropdownOptions = createOptionsWithPartialClasses({ list: 'class-1', listDropdown: 'class-2', - }; + }); it('returns expected html', () => { const expectedOutput = strToEl( - ``, + ``, ); - const actualOutput = templates.dropdown(classes); + const actualOutput = templates.dropdown(dropdownOptions); expectEqualElements(actualOutput, expectedOutput); }); }); describe('notice', () => { - const classes = { + const noticeOptions = createOptionsWithPartialClasses({ item: 'class-1', itemChoice: 'class-2', noResults: 'class-3', noChoices: 'class-4', - }; + }); const label = 'test'; it('returns expected html', () => { const expectedOutput = strToEl(` -
+
${label}
`); - const actualOutput = templates.notice(classes, label); + const actualOutput = templates.notice(noticeOptions, label); expectEqualElements(actualOutput, expectedOutput); }); @@ -550,11 +587,15 @@ describe('templates', () => { describe('no results', () => { it('adds no results classname', () => { const expectedOutput = strToEl(` -
+
${label}
`); - const actualOutput = templates.notice(classes, label, 'no-results'); + const actualOutput = templates.notice( + noticeOptions, + label, + 'no-results', + ); expectEqualElements(actualOutput, expectedOutput); }); @@ -563,11 +604,15 @@ describe('templates', () => { describe('no choices', () => { it('adds no choices classname', () => { const expectedOutput = strToEl(` -
+
${label}
`); - const actualOutput = templates.notice(classes, label, 'no-choices'); + const actualOutput = templates.notice( + noticeOptions, + label, + 'no-choices', + ); expectEqualElements(actualOutput, expectedOutput); }); From 859f6262eb698e0d90e5ea4fc19f3355c2168038 Mon Sep 17 00:00:00 2001 From: viction Date: Fri, 24 Dec 2021 17:33:32 +0000 Subject: [PATCH 3/9] test: Coverage for allowHTML --- cypress/integration/text.spec.ts | 88 +++++++++++++---- public/assets/scripts/choices.js | 138 +++++++++++++++------------ public/assets/scripts/choices.min.js | 2 +- public/test/text/index.html | 56 ++++++++++- 4 files changed, 199 insertions(+), 85 deletions(-) diff --git a/cypress/integration/text.spec.ts b/cypress/integration/text.spec.ts index 5cbea84..e5dffe2 100644 --- a/cypress/integration/text.spec.ts +++ b/cypress/integration/text.spec.ts @@ -1,6 +1,10 @@ describe('Choices - text element', () => { beforeEach(() => { - cy.visit('/text'); + cy.visit('/text', { + onBeforeLoad(win) { + cy.stub(win.console, 'warn').as('consoleWarn'); + }, + }); }); describe('scenarios', () => { @@ -17,7 +21,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=basic]') .find('.choices__list--multiple .choices__item') .last() - .should($el => { + .should(($el) => { expect($el).to.contain(textInput); }); }); @@ -42,7 +46,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=basic]') .find('.choices__list--dropdown') .should('be.visible') - .should($dropdown => { + .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal( `Press Enter to add "${textInput}"`, @@ -74,7 +78,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=edit-items]') .find('.choices__list--multiple .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.data('value')).to.equal(`${textInput}-edited`); }); }); @@ -90,7 +94,7 @@ describe('Choices - text element', () => { it('highlights all items', () => { cy.get('[data-test-hook=edit-items]') .find('.choices__list--multiple .choices__item') - .each($choice => { + .each(($choice) => { expect($choice.hasClass('is-highlighted')).to.equal(true); }); }); @@ -124,7 +128,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=remove-button]') .find('.choices__list--multiple') .children() - .should($items => { + .should(($items) => { expect($items.length).to.equal(1); }); @@ -137,7 +141,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=remove-button]') .find('.choices__list--multiple .choices__item') - .should($items => { + .should(($items) => { expect($items.length).to.equal(0); }); }); @@ -152,7 +156,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=remove-button]') .find('.choices__input[hidden]') - .then($input => { + .then(($input) => { expect($input.val()).to.not.contain(textInput); }); }); @@ -175,7 +179,7 @@ describe('Choices - text element', () => { .find('.choices__list--multiple') .first() .children() - .should($items => { + .should(($items) => { expect($items.length).to.equal(1); }); }); @@ -185,7 +189,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=unique-values]') .find('.choices__list--dropdown') .should('be.visible') - .should($dropdown => { + .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal( 'Only unique values can be added', @@ -212,7 +216,7 @@ describe('Choices - text element', () => { .find('.choices__list--multiple') .first() .children() - .should($items => { + .should(($items) => { expect($items.length).to.equal(inputLimit); }); }); @@ -222,7 +226,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=input-limit]') .find('.choices__list--dropdown') .should('be.visible') - .should($dropdown => { + .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal( `Only ${inputLimit} values can be added`, @@ -245,7 +249,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=add-item-filter]') .find('.choices__list--multiple .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal(input); }); }); @@ -261,7 +265,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=add-item-filter]') .find('.choices__list--dropdown') .should('be.visible') - .should($dropdown => { + .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal( 'Only values matching specific conditions can be added', @@ -283,7 +287,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=prepend-append]') .find('.choices__list--multiple .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.data('value')).to.equal(`before-${textInput}-after`); }); }); @@ -292,7 +296,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=prepend-append]') .find('.choices__list--multiple .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.text()).to.not.contain(`before-${textInput}-after`); expect($choice.text()).to.contain(textInput); }); @@ -319,21 +323,21 @@ describe('Choices - text element', () => { it('pre-populates choices', () => { cy.get('[data-test-hook=prepopulated]') .find('.choices__list--multiple .choices__item') - .should($choices => { + .should(($choices) => { expect($choices.length).to.equal(2); }); cy.get('[data-test-hook=prepopulated]') .find('.choices__list--multiple .choices__item') .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal('Josh Johnson'); }); cy.get('[data-test-hook=prepopulated]') .find('.choices__list--multiple .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal('Joe Bloggs'); }); }); @@ -355,11 +359,53 @@ describe('Choices - text element', () => { }); }); + describe('allow html', () => { + describe('is undefined', () => { + it('logs a deprecation warning', () => { + cy.get('@consoleWarn').should( + 'be.calledOnceWithExactly', + 'Deprecation warning: allowHTML in the future will be defaulted to false. You must explicitly set it to true to properly display html tags in choices.', + ); + }); + + it('does not show html as text', () => { + cy.get('[data-test-hook=allowhtml-undefined]') + .find('.choices__list--multiple .choices__item') + .first() + .should(($choice) => { + expect($choice.text().trim()).to.equal('Mason Rogers'); + }); + }); + }); + + describe('set to true', () => { + it('does not show html as text', () => { + cy.get('[data-test-hook=allowhtml-true]') + .find('.choices__list--multiple .choices__item') + .first() + .should(($choice) => { + expect($choice.text().trim()).to.equal('Mason Rogers'); + }); + }); + }); + + describe('set to false', () => { + it('shows html as text', () => { + cy.get('[data-test-hook=allowhtml-false]') + .find('.choices__list--multiple .choices__item') + .first() + .should(($choice) => { + expect($choice.text().trim()).to.equal('Mason Rogers'); + }); + }); + }); + }); + describe('within form', () => { describe('inputting item', () => { describe('on enter key', () => { it('does not submit form', () => { - cy.get('[data-test-hook=within-form] form').then($form => { + cy.get('[data-test-hook=within-form] form').then(($form) => { $form.submit(() => { // this will fail the test if the form submits throw new Error('Form submitted'); @@ -374,7 +420,7 @@ describe('Choices - text element', () => { cy.get('[data-test-hook=within-form]') .find('.choices__list--multiple .choices__item') .last() - .should($el => { + .should(($el) => { expect($el).to.contain(textInput); }); }); diff --git a/public/assets/scripts/choices.js b/public/assets/scripts/choices.js index 40d4167..47acf82 100644 --- a/public/assets/scripts/choices.js +++ b/public/assets/scripts/choices.js @@ -1,4 +1,4 @@ -/*! choices.js v9.0.1 | © 2021 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ +/*! choices.js v9.1.0 | © 2021 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); @@ -291,6 +291,10 @@ function () { userConfig = {}; } + if (userConfig.allowHTML === undefined) { + console.warn('Deprecation warning: allowHTML in the future will be defaulted to false. You must explicitly set it to true to properly display html tags in choices.'); + } + this.config = deepmerge_1.default.all([defaults_1.DEFAULT_CONFIG, Choices.defaults.options, userConfig], // When merging array configs, replace with a copy of the userConfig array, // instead of concatenating with the default array { @@ -2209,8 +2213,7 @@ function () { args[_i - 1] = arguments[_i]; } - var classNames = this.config.classNames; - return (_a = this._templates[template]).call.apply(_a, __spreadArray([this, classNames], args, false)); + return (_a = this._templates[template]).call.apply(_a, __spreadArray([this, this.config], args, false)); }; Choices.prototype._createTemplates = function () { @@ -3483,6 +3486,7 @@ exports.DEFAULT_CONFIG = { removeItems: true, removeItemButton: false, editItems: false, + allowHTML: true, duplicateItemsAllowed: true, delimiter: ',', paste: true, @@ -3644,7 +3648,7 @@ var sanitise = function (value) { return value; } - return value.replace(/&/g, '&').replace(/>/g, '&rt;').replace(//g, '>').replace(/=0?this._store.getGroupById(o):null;return this._store.dispatch((0,l.highlightItem)(i,!0)),t&&this.passedElement.triggerEvent(d.EVENTS.highlightItem,{id:i,value:s,label:c,groupValue:h&&h.value?h.value:null}),this},e.prototype.unhighlightItem=function(e){if(!e||!e.id)return this;var t=e.id,i=e.groupId,n=void 0===i?-1:i,o=e.value,r=void 0===o?"":o,s=e.label,a=void 0===s?"":s,c=n>=0?this._store.getGroupById(n):null;return this._store.dispatch((0,l.highlightItem)(t,!1)),this.passedElement.triggerEvent(d.EVENTS.highlightItem,{id:t,value:r,label:a,groupValue:c&&c.value?c.value:null}),this},e.prototype.highlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.highlightItem(t)})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.unhighlightItem(t)})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent(d.EVENTS.showDropdown,{})})),this},e.prototype.hideDropdown=function(e){var t=this;return this.dropdown.isActive?(requestAnimationFrame((function(){t.dropdown.hide(),t.containerOuter.close(),!e&&t._canSearch&&(t.input.removeActiveDescendant(),t.input.blur()),t.passedElement.triggerEvent(d.EVENTS.hideDropdown,{})})),this):this},e.prototype.getValue=function(e){void 0===e&&(e=!1);var t=this._store.activeItems.reduce((function(t,i){var n=e?i.value:i;return t.push(n),t}),[]);return this._isSelectOneElement?t[0]:t},e.prototype.setValue=function(e){var t=this;return this.initialised?(e.forEach((function(e){return t._setChoiceOrItem(e)})),this):this},e.prototype.setChoiceByValue=function(e){var t=this;return!this.initialised||this._isTextElement||(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)})),this},e.prototype.setChoices=function(e,t,i,n){var o=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===i&&(i="label"),void 0===n&&(n=!1),!this.initialised)throw new ReferenceError("setChoices was called on a non-initialized instance of Choices");if(!this._isSelectElement)throw new TypeError("setChoices can't be used with INPUT based Choices");if("string"!=typeof t||!t)throw new TypeError("value parameter must be a name of 'value' field in passed objects");if(n&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return o._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return o.setChoices(e,t,i,n)})).catch((function(e){o.config.silent||console.error(e)})).then((function(){return o._handleLoadingState(!1)})).then((function(){return o}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,i,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._startLoading(),e.forEach((function(e){if(e.choices)o._addGroup({id:e.id?parseInt("".concat(e.id),10):null,group:e,valueKey:t,labelKey:i});else{var n=e;o._addChoice({value:n[t],label:n[i],isSelected:!!n.selected,isDisabled:!!n.disabled,placeholder:!!n.placeholder,customProperties:n.customProperties})}})),this._stopLoading(),this},e.prototype.clearChoices=function(){return this._store.dispatch((0,a.clearChoices)()),this},e.prototype.clearStore=function(){return this._store.dispatch((0,h.clearAll)()),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),!this._isTextElement&&this._canSearch&&(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0))),this},e.prototype._render=function(){if(!this._store.isLoading()){this._currentState=this._store.state;var e=this._currentState.choices!==this._prevState.choices||this._currentState.groups!==this._prevState.groups||this._currentState.items!==this._prevState.items,t=this._isSelectElement,i=this._currentState.items!==this._prevState.items;e&&(t&&this._renderChoices(),i&&this._renderItems(),this._prevState=this._currentState)}},e.prototype._renderChoices=function(){var e=this,t=this._store,i=t.activeGroups,n=t.activeChoices,o=document.createDocumentFragment();if(this.choiceList.clear(),this.config.resetScrollPosition&&requestAnimationFrame((function(){return e.choiceList.scrollToTop()})),i.length>=1&&!this._isSearching){var r=n.filter((function(e){return!0===e.placeholder&&-1===e.groupId}));r.length>=1&&(o=this._createChoicesFragment(r,o)),o=this._createGroupsFragment(i,n,o)}else n.length>=1&&(o=this._createChoicesFragment(n,o));if(o.childNodes&&o.childNodes.length>0){var s=this._store.activeItems,a=this._canAddItem(s,this.input.value);if(a.response)this.choiceList.append(o),this._highlightChoice();else{var c=this._getTemplate("notice",a.notice);this.choiceList.append(c)}}else{var l=void 0;c=void 0,this._isSearching?(c="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText,l=this._getTemplate("notice",c,"no-results")):(c="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText,l=this._getTemplate("notice",c,"no-choices")),this.choiceList.append(l)}},e.prototype._renderItems=function(){var e=this._store.activeItems||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;return void 0===i&&(i=document.createDocumentFragment()),this.config.shouldSort&&e.sort(this.config.sorter),e.forEach((function(e){var o=function(e){return t.filter((function(t){return n._isSelectOneElement?t.groupId===e.id:t.groupId===e.id&&("always"===n.config.renderSelectedChoices||!t.selected)}))}(e);if(o.length>=1){var r=n._getTemplate("choiceGroup",e);i.appendChild(r),n._createChoicesFragment(o,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var o=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var r=this.config,s=r.renderSelectedChoices,a=r.searchResultLimit,c=r.renderChoiceLimit,l=this._isSearching?f.sortByScore:this.config.sorter,h=function(e){if("auto"!==s||o._isSelectOneElement||!e.selected){var i=o._getTemplate("choice",e,o.config.itemSelectText);t.appendChild(i)}},u=e;"auto"!==s||this._isSelectOneElement||(u=e.filter((function(e){return!e.selected})));var d=u.reduce((function(e,t){return t.placeholder?e.placeholderChoices.push(t):e.normalChoices.push(t),e}),{placeholderChoices:[],normalChoices:[]}),p=d.placeholderChoices,m=d.normalChoices;(this.config.shouldSort||this._isSearching)&&m.sort(l);var v=u.length,_=this._isSelectOneElement?n(n([],p,!0),m,!0):m;this._isSearching?v=a:c&&c>0&&!i&&(v=c);for(var g=0;g=n){var s=o?this._searchChoices(e):0;this.passedElement.triggerEvent(d.EVENTS.search,{value:e,resultCount:s})}else r&&(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0)))}},e.prototype._canAddItem=function(e,t){var i=!0,n="function"==typeof this.config.addItemText?this.config.addItemText(t):this.config.addItemText;if(!this._isSelectOneElement){var o=(0,f.existsInArray)(e,t);this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(i=!1,n="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText),!this.config.duplicateItemsAllowed&&o&&i&&(i=!1,n="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(t):this.config.uniqueItemText),this._isTextElement&&this.config.addItems&&i&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(i=!1,n="function"==typeof this.config.customAddItemText?this.config.customAddItemText(t):this.config.customAddItemText)}return{response:i,notice:n}},e.prototype._searchChoices=function(e){var t="string"==typeof e?e.trim():e,i="string"==typeof this._currentValue?this._currentValue.trim():this._currentValue;if(t.length<1&&t==="".concat(i," "))return 0;var o=this._store.searchableChoices,r=t,c=n([],this.config.searchFields,!0),l=Object.assign(this.config.fuseOptions,{keys:c,includeMatches:!0}),h=new s.default(o,l).search(r);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch((0,a.filterChoices)(h)),h.length},e.prototype._addEventListeners=function(){var e=document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.addEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.addEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.addEventListener("blur",this._onBlur,{passive:!0})),this.input.element.addEventListener("keyup",this._onKeyUp,{passive:!0}),this.input.element.addEventListener("focus",this._onFocus,{passive:!0}),this.input.element.addEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.addEventListener("reset",this._onFormReset,{passive:!0}),this.input.addEventListeners()},e.prototype._removeEventListeners=function(){var e=document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("focus",this._onFocus),this.input.element.removeEventListener("blur",this._onBlur),this.input.element.form&&this.input.element.form.removeEventListener("reset",this._onFormReset),this.input.removeEventListeners()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.activeItems,n=this.input.isFocussed,o=this.dropdown.isActive,r=this.itemList.hasChildren(),s=String.fromCharCode(t),a=/[a-zA-Z0-9-_ ]/.test(s),c=d.KEY_CODES.BACK_KEY,l=d.KEY_CODES.DELETE_KEY,h=d.KEY_CODES.ENTER_KEY,u=d.KEY_CODES.A_KEY,p=d.KEY_CODES.ESC_KEY,f=d.KEY_CODES.UP_KEY,m=d.KEY_CODES.DOWN_KEY,v=d.KEY_CODES.PAGE_UP_KEY,_=d.KEY_CODES.PAGE_DOWN_KEY;switch(this._isTextElement||o||!a||(this.showDropdown(),this.input.isFocussed||(this.input.value+=s.toLowerCase())),t){case u:return this._onSelectKey(e,r);case h:return this._onEnterKey(e,i,o);case p:return this._onEscapeKey(o);case f:case v:case m:case _:return this._onDirectionKey(e,o);case l:case c:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(e){var t=e.target,i=e.keyCode,n=this.input.value,o=this._store.activeItems,r=this._canAddItem(o,n),s=d.KEY_CODES.BACK_KEY,c=d.KEY_CODES.DELETE_KEY;if(this._isTextElement)if(r.notice&&n){var l=this._getTemplate("notice",r.notice);this.dropdown.element.innerHTML=l.outerHTML,this.showDropdown(!0)}else this.hideDropdown(!0);else{var h=(i===s||i===c)&&t&&!t.value,u=!this._isTextElement&&this._isSearching,p=this._canSearch&&r.response;h&&u?(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0))):p&&this._handleSearch(this.input.value)}this._canSearch=this.config.searchEnabled},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=e.target,o=d.KEY_CODES.ENTER_KEY,r=n&&n.hasAttribute("data-button");if(this._isTextElement&&n&&n.value){var s=this.input.value;this._canAddItem(t,s).response&&(this.hideDropdown(!0),this._addItem({value:s}),this._triggerChange(s),this.clearInput())}if(r&&(this._handleButtonAction(t,n),e.preventDefault()),i){var a=this.dropdown.getChild(".".concat(this.config.classNames.highlightedState));a&&(t[0]&&(t[0].keyCode=o),this._handleChoiceAction(t,a)),e.preventDefault()}else this._isSelectOneElement&&(this.showDropdown(),e.preventDefault())},e.prototype._onEscapeKey=function(e){e&&(this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i=e.keyCode,n=e.metaKey,o=d.KEY_CODES.DOWN_KEY,r=d.KEY_CODES.PAGE_UP_KEY,s=d.KEY_CODES.PAGE_DOWN_KEY;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=i===o||i===s?1:-1,c="[data-choice-selectable]",l=void 0;if(n||i===s||i===r)l=a>0?this.dropdown.element.querySelector("".concat(c,":last-of-type")):this.dropdown.element.querySelector(c);else{var h=this.dropdown.element.querySelector(".".concat(this.config.classNames.highlightedState));l=h?(0,f.getAdjacentEl)(h,c,a):this.dropdown.element.querySelector(c)}l&&((0,f.isScrolledIntoView)(l,this.choiceList.element,a)||this.choiceList.scrollToChildElement(l,a),this._highlightChoice(l)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._onTouchEnd=function(e){var t=(e||e.touches[0]).target;this._wasTap&&this.containerOuter.element.contains(t)&&((t===this.containerOuter.element||t===this.containerInner.element)&&(this._isTextElement?this.input.focus():this._isSelectMultipleElement&&this.showDropdown()),e.stopPropagation()),this._wasTap=!0},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(g&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild,n="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[d.TEXT_TYPE]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[d.SELECT_ONE_TYPE]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[d.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this.passedElement.element.type]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var o=this._store.activeItems.some((function(e){return e.highlighted}));((t={})[d.TEXT_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),o&&i.unhighlightAll(),i.hideDropdown(!0))},t[d.SELECT_ONE_TYPE]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[d.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),o&&i.unhighlightAll())},t)[this.passedElement.element.type]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){this._store.dispatch((0,h.resetTo)(this._initialState))},e.prototype._highlightChoice=function(e){var t=this;void 0===e&&(e=null);var i=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(i.length){var n=e;Array.from(this.dropdown.element.querySelectorAll(".".concat(this.config.classNames.highlightedState))).forEach((function(e){e.classList.remove(t.config.classNames.highlightedState),e.setAttribute("aria-selected","false")})),n?this._highlightPosition=i.indexOf(n):(n=i.length>this._highlightPosition?i[this._highlightPosition]:i[i.length-1])||(n=i[0]),n.classList.add(this.config.classNames.highlightedState),n.setAttribute("aria-selected","true"),this.passedElement.triggerEvent(d.EVENTS.highlightChoice,{el:n}),this.dropdown.isActive&&(this.input.setActiveDescendant(n.id),this.containerOuter.setActiveDescendant(n.id))}},e.prototype._addItem=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,o=e.choiceId,r=void 0===o?-1:o,s=e.groupId,a=void 0===s?-1:s,c=e.customProperties,h=void 0===c?{}:c,u=e.placeholder,p=void 0!==u&&u,f=e.keyCode,m=void 0===f?-1:f,v="string"==typeof t?t.trim():t,_=this._store.items,g=n||v,y=r||-1,E=a>=0?this._store.getGroupById(a):null,b=_?_.length+1:1;this.config.prependValue&&(v=this.config.prependValue+v.toString()),this.config.appendValue&&(v+=this.config.appendValue.toString()),this._store.dispatch((0,l.addItem)({value:v,label:g,id:b,choiceId:y,groupId:a,customProperties:h,placeholder:p,keyCode:m})),this._isSelectOneElement&&this.removeActiveItems(b),this.passedElement.triggerEvent(d.EVENTS.addItem,{id:b,value:v,label:g,customProperties:h,groupValue:E&&E.value?E.value:null,keyCode:m})},e.prototype._removeItem=function(e){var t=e.id,i=e.value,n=e.label,o=e.customProperties,r=e.choiceId,s=e.groupId,a=s&&s>=0?this._store.getGroupById(s):null;t&&r&&(this._store.dispatch((0,l.removeItem)(t,r)),this.passedElement.triggerEvent(d.EVENTS.removeItem,{id:t,value:i,label:n,customProperties:o,groupValue:a&&a.value?a.value:null}))},e.prototype._addChoice=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,o=e.isSelected,r=void 0!==o&&o,s=e.isDisabled,c=void 0!==s&&s,l=e.groupId,h=void 0===l?-1:l,u=e.customProperties,d=void 0===u?{}:u,p=e.placeholder,f=void 0!==p&&p,m=e.keyCode,v=void 0===m?-1:m;if(null!=t){var _=this._store.choices,g=n||t,y=_?_.length+1:1,E="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(y);this._store.dispatch((0,a.addChoice)({id:y,groupId:h,elementId:E,value:t,label:g,disabled:c,customProperties:d,placeholder:f,keyCode:v})),r&&this._addItem({value:t,label:g,choiceId:y,customProperties:d,placeholder:f,keyCode:v})}},e.prototype._addGroup=function(e){var t=this,i=e.group,n=e.id,o=e.valueKey,r=void 0===o?"value":o,s=e.labelKey,a=void 0===s?"label":s,l=(0,f.isType)("Object",i)?i.choices:Array.from(i.getElementsByTagName("OPTION")),h=n||Math.floor((new Date).valueOf()*Math.random()),u=!!i.disabled&&i.disabled;l?(this._store.dispatch((0,c.addGroup)({value:i.label,id:h,active:!0,disabled:u})),l.forEach((function(e){var i=e.disabled||e.parentNode&&e.parentNode.disabled;t._addChoice({value:e[r],label:(0,f.isType)("Object",e)?e[a]:e.innerHTML,isSelected:e.selected,isDisabled:i,groupId:h,customProperties:e.customProperties,placeholder:e.placeholder})}))):this._store.dispatch((0,c.addGroup)({value:i.label,id:i.id,active:!1,disabled:i.disabled}))},e.prototype._getTemplate=function(e){for(var t,i=[],o=1;o0?this.element.scrollTop+s-o:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(a,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,o=n>1?n:1;this.element.scrollTop=e+o},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,o=n>1?n:1;this.element.scrollTop=e-o},e.prototype._animateScroll=function(e,t){var i=this,o=n.SCROLLING_SPEED,r=this.element.scrollTop,s=!1;t>0?(this._scrollDown(r,o,e),re&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}();t.default=o},730:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=i(799),o=function(){function e(e){var t=e.element,i=e.classNames;if(this.element=t,this.classNames=i,!(t instanceof HTMLInputElement||t instanceof HTMLSelectElement))throw new TypeError("Invalid element passed");this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){this.element.classList.add(this.classNames.input),this.element.hidden=!0,this.element.tabIndex=-1;var e=this.element.getAttribute("style");e&&this.element.setAttribute("data-choice-orig-style",e),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){this.element.classList.remove(this.classNames.input),this.element.hidden=!1,this.element.removeAttribute("tabindex");var e=this.element.getAttribute("data-choice-orig-style");e?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",e)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){(0,n.dispatchEvent)(this.element,e,t)},e}();t.default=o},541:function(e,t,i){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var s=function(e){function t(t){var i=t.element,n=t.classNames,o=t.delimiter,r=e.call(this,{element:i,classNames:n})||this;return r.delimiter=o,r}return o(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),t}(r(i(730)).default);t.default=s},982:function(e,t,i){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var s=function(e){function t(t){var i=t.element,n=t.classNames,o=t.template,r=e.call(this,{element:i,classNames:n})||this;return r.template=o,r}return o(t,e),Object.defineProperty(t.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"optionGroups",{get:function(){return Array.from(this.element.getElementsByTagName("OPTGROUP"))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return Array.from(this.element.options)},set:function(e){var t=this,i=document.createDocumentFragment();e.forEach((function(e){return n=e,o=t.template(n),void i.appendChild(o);var n,o})),this.appendDocFragment(i)},enumerable:!1,configurable:!0}),t.prototype.appendDocFragment=function(e){this.element.innerHTML="",this.element.appendChild(e)},t}(r(i(730)).default);t.default=s},883:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SCROLLING_SPEED=t.SELECT_MULTIPLE_TYPE=t.SELECT_ONE_TYPE=t.TEXT_TYPE=t.KEY_CODES=t.ACTION_TYPES=t.EVENTS=void 0,t.EVENTS={showDropdown:"showDropdown",hideDropdown:"hideDropdown",change:"change",choice:"choice",search:"search",addItem:"addItem",removeItem:"removeItem",highlightItem:"highlightItem",highlightChoice:"highlightChoice",unhighlightItem:"unhighlightItem"},t.ACTION_TYPES={ADD_CHOICE:"ADD_CHOICE",FILTER_CHOICES:"FILTER_CHOICES",ACTIVATE_CHOICES:"ACTIVATE_CHOICES",CLEAR_CHOICES:"CLEAR_CHOICES",ADD_GROUP:"ADD_GROUP",ADD_ITEM:"ADD_ITEM",REMOVE_ITEM:"REMOVE_ITEM",HIGHLIGHT_ITEM:"HIGHLIGHT_ITEM",CLEAR_ALL:"CLEAR_ALL",RESET_TO:"RESET_TO",SET_IS_LOADING:"SET_IS_LOADING"},t.KEY_CODES={BACK_KEY:46,DELETE_KEY:8,ENTER_KEY:13,A_KEY:65,ESC_KEY:27,UP_KEY:38,DOWN_KEY:40,PAGE_UP_KEY:33,PAGE_DOWN_KEY:34},t.TEXT_TYPE="text",t.SELECT_ONE_TYPE="select-one",t.SELECT_MULTIPLE_TYPE="select-multiple",t.SCROLLING_SPEED=4},789:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CONFIG=t.DEFAULT_CLASSNAMES=void 0;var n=i(799);t.DEFAULT_CLASSNAMES={containerOuter:"choices",containerInner:"choices__inner",input:"choices__input",inputCloned:"choices__input--cloned",list:"choices__list",listItems:"choices__list--multiple",listSingle:"choices__list--single",listDropdown:"choices__list--dropdown",item:"choices__item",itemSelectable:"choices__item--selectable",itemDisabled:"choices__item--disabled",itemChoice:"choices__item--choice",placeholder:"choices__placeholder",group:"choices__group",groupHeading:"choices__heading",button:"choices__button",activeState:"is-active",focusState:"is-focused",openState:"is-open",disabledState:"is-disabled",highlightedState:"is-highlighted",selectedState:"is-selected",flippedState:"is-flipped",loadingState:"is-loading",noResults:"has-no-results",noChoices:"has-no-choices"},t.DEFAULT_CONFIG={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,addItems:!0,addItemFilter:null,removeItems:!0,removeItemButton:!1,editItems:!1,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:n.sortByAlpha,placeholder:!0,placeholderValue:null,searchPlaceholderValue:null,prependValue:null,appendValue:null,renderSelectedChoices:"auto",loadingText:"Loading...",noResultsText:"No results found",noChoicesText:"No choices to choose from",itemSelectText:"Press to select",uniqueItemText:"Only unique values can be added",customAddItemText:"Only values matching specific conditions can be added",addItemText:function(e){return'Press Enter to add "'.concat((0,n.sanitise)(e),'"')},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},callbackOnInit:null,callbackOnCreateTemplates:null,classNames:t.DEFAULT_CLASSNAMES}},799:function(e,t){"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.cloneObject=t.existsInArray=t.dispatchEvent=t.sortByScore=t.sortByAlpha=t.strToEl=t.sanitise=t.isScrolledIntoView=t.getAdjacentEl=t.wrap=t.isType=t.getType=t.generateId=t.generateChars=t.getRandomNumber=void 0,t.getRandomNumber=function(e,t){return Math.floor(Math.random()*(t-e)+e)},t.generateChars=function(e){return Array.from({length:e},(function(){return(0,t.getRandomNumber)(0,36).toString(36)})).join("")},t.generateId=function(e,i){var n=e.id||e.name&&"".concat(e.name,"-").concat((0,t.generateChars)(2))||(0,t.generateChars)(4);return n=n.replace(/(:|\.|\[|\]|,)/g,""),"".concat(i,"-").concat(n)},t.getType=function(e){return Object.prototype.toString.call(e).slice(8,-1)},t.isType=function(e,i){return null!=i&&(0,t.getType)(i)===e},t.wrap=function(e,t){return void 0===t&&(t=document.createElement("div")),e.parentNode&&(e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t)),t.appendChild(e)},t.getAdjacentEl=function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),o=e[n];o;){if(o.matches(t))return o;o=o[n]}return o},t.isScrolledIntoView=function(e,t,i){return void 0===i&&(i=1),!!e&&(i>0?t.scrollTop+t.offsetHeight>=e.offsetTop+e.offsetHeight:e.offsetTop>=t.scrollTop)},t.sanitise=function(e){return"string"!=typeof e?e:e.replace(/&/g,"&").replace(/>/g,"&rt;").replace(/-1?e.map((function(e){var t=e;return t.id===parseInt("".concat(s.choiceId),10)&&(t.selected=!0),t})):e;case"REMOVE_ITEM":var a=n;return a.choiceId&&a.choiceId>-1?e.map((function(e){var t=e;return t.id===parseInt("".concat(a.choiceId),10)&&(t.selected=!1),t})):e;case"FILTER_CHOICES":var c=n;return e.map((function(e){var t=e;return t.active=c.results.some((function(e){var i=e.item,n=e.score;return i.id===t.id&&(t.score=n,!0)})),t}));case"ACTIVATE_CHOICES":var l=n;return e.map((function(e){var t=e;return t.active=l.active,t}));case"CLEAR_CHOICES":return t.defaultState;default:return e}}},871:function(e,t){"use strict";var i=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,o=0,r=t.length;o0?"treeitem":"option"),Object.assign(_.dataset,{choice:"",id:l,value:h,selectText:i}),f?(_.classList.add(a),_.dataset.choiceDisabled="",_.setAttribute("aria-disabled","true")):(_.classList.add(r),_.dataset.choiceSelectable=""),_},input:function(e,t){var i=e.input,n=e.inputCloned,o=Object.assign(document.createElement("input"),{type:"text",className:"".concat(i," ").concat(n),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return o.setAttribute("role","textbox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-label",t),o},dropdown:function(e){var t=e.list,i=e.listDropdown,n=document.createElement("div");return n.classList.add(t,i),n.setAttribute("aria-expanded","false"),n},notice:function(e,t,i){var n=e.item,o=e.itemChoice,r=e.noResults,s=e.noChoices;void 0===i&&(i="");var a=[n,o];return"no-choices"===i?a.push(s):"no-results"===i&&a.push(r),Object.assign(document.createElement("div"),{innerHTML:t,className:a.join(" ")})},option:function(e){var t=e.label,i=e.value,n=e.customProperties,o=e.active,r=e.disabled,s=new Option(t,i,!1,o);return n&&(s.dataset.customProperties="".concat(n)),s.disabled=!!r,s}};t.default=i},996:function(e){"use strict";var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===i}(e)}(e)},i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((i=e,Array.isArray(i)?[]:{}),e,t):e;var i}function o(e,t,i){return e.concat(t).map((function(e){return n(e,i)}))}function r(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return e.propertyIsEnumerable(t)})):[]}(e))}function s(e,t){try{return t in e}catch(e){return!1}}function a(e,i,c){(c=c||{}).arrayMerge=c.arrayMerge||o,c.isMergeableObject=c.isMergeableObject||t,c.cloneUnlessOtherwiseSpecified=n;var l=Array.isArray(i);return l===Array.isArray(e)?l?c.arrayMerge(e,i,c):function(e,t,i){var o={};return i.isMergeableObject(e)&&r(e).forEach((function(t){o[t]=n(e[t],i)})),r(t).forEach((function(r){(function(e,t){return s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,r)||(s(e,r)&&i.isMergeableObject(t[r])?o[r]=function(e,t){if(!t.customMerge)return a;var i=t.customMerge(e);return"function"==typeof i?i:a}(r,i)(e[r],t[r],i):o[r]=n(t[r],i))})),o}(e,i,c):n(i,c)}a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,i){return a(e,i,t)}),{})};var c=a;e.exports=c},70:function(e){e.exports=function(e){var t={};function i(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,i),o.l=!0,o.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)i.d(n,o,function(t){return e[t]}.bind(null,o));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=1)}([function(e,t){e.exports=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)}},function(e,t,i){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:{limit:!1};this._log('---------\nSearch pattern: "'.concat(e,'"'));var i=this._prepareSearchers(e),n=i.tokenSearchers,o=i.fullSearcher,r=this._search(n,o),s=r.weights,a=r.results;return this._computeScore(s,a),this.options.shouldSort&&this._sort(a),t.limit&&"number"==typeof t.limit&&(a=a.slice(0,t.limit)),this._format(a)}},{key:"_prepareSearchers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=[];if(this.options.tokenize)for(var i=e.split(this.options.tokenSeparator),n=0,o=i.length;n0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,i=this.list,n={},o=[];if("string"==typeof i[0]){for(var r=0,s=i.length;r1)throw new Error("Key weight has to be > 0 and <= 1");p=p.name}else a[p]={weight:1};this._analyze({key:p,value:this.options.getFn(h,p),record:h,index:c},{resultMap:n,results:o,tokenSearchers:e,fullSearcher:t})}return{weights:a,results:o}}},{key:"_analyze",value:function(e,t){var i=e.key,n=e.arrayIndex,o=void 0===n?-1:n,r=e.value,s=e.record,c=e.index,l=t.tokenSearchers,h=void 0===l?[]:l,u=t.fullSearcher,d=void 0===u?[]:u,p=t.resultMap,f=void 0===p?{}:p,m=t.results,v=void 0===m?[]:m;if(null!=r){var _=!1,g=-1,y=0;if("string"==typeof r){this._log("\nKey: ".concat(""===i?"-":i));var E=d.search(r);if(this._log('Full text: "'.concat(r,'", score: ').concat(E.score)),this.options.tokenize){for(var b=r.split(this.options.tokenSeparator),S=[],I=0;I-1&&(N=(N+g)/2),this._log("Score average:",N);var M=!this.options.tokenize||!this.options.matchAllTokens||y>=h.length;if(this._log("\nCheck Matches: ".concat(M)),(_||E.isMatch)&&M){var x=f[c];x?x.output.push({key:i,arrayIndex:o,value:r,score:N,matchedIndices:E.matchedIndices}):(f[c]={item:s,output:[{key:i,arrayIndex:o,value:r,score:N,matchedIndices:E.matchedIndices}]},v.push(f[c]))}}else if(a(r))for(var j=0,F=r.length;j-1&&(s.arrayIndex=r.arrayIndex),t.matches.push(s)}}})),this.options.includeScore&&o.push((function(e,t){t.score=e.score}));for(var r=0,s=e.length;ri)return o(e,this.pattern,n);var s=this.options,a=s.location,c=s.distance,l=s.threshold,h=s.findAllMatches,u=s.minMatchCharLength;return r(e,this.pattern,this.patternAlphabet,{location:a,distance:c,threshold:l,findAllMatches:h,minMatchCharLength:u})}}])&&n(t.prototype,i),e}();e.exports=a},function(e,t){var i=/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g;e.exports=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:/ +/g,o=new RegExp(t.replace(i,"\\$&").replace(n,"|")),r=e.match(o),s=!!r,a=[];if(s)for(var c=0,l=r.length;c=N;j-=1){var F=j-1,k=i[e.charAt(F)];if(k&&(b[F]=1),x[j]=(x[j+1]<<1|1)&k,0!==w&&(x[j]|=(C[j+1]|C[j])<<1|1|C[j+1]),x[j]&L&&(T=n(t,{errors:w,currentLocation:F,expectedLocation:v,distance:l}))<=g){if(g=T,(y=F)<=v)break;N=Math.max(1,2*v-y)}}if(n(t,{errors:w+1,currentLocation:v,expectedLocation:v,distance:l})>g)break;C=x}return{isMatch:y>=0,score:0===T?.001:T,matchedIndices:o(b,m)}}},function(e,t){e.exports=function(e,t){var i=t.errors,n=void 0===i?0:i,o=t.currentLocation,r=void 0===o?0:o,s=t.expectedLocation,a=void 0===s?0:s,c=t.distance,l=void 0===c?100:c,h=n/e.length,u=Math.abs(a-r);return l?h+u/l:u?1:h}},function(e,t){e.exports=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=[],n=-1,o=-1,r=0,s=e.length;r=t&&i.push([n,o]),n=-1)}return e[r-1]&&r-n>=t&&i.push([n,r-1]),i}},function(e,t){e.exports=function(e){for(var t={},i=e.length,n=0;n=0?this._store.getGroupById(o):null;return this._store.dispatch((0,l.highlightItem)(i,!0)),t&&this.passedElement.triggerEvent(d.EVENTS.highlightItem,{id:i,value:s,label:c,groupValue:h&&h.value?h.value:null}),this},e.prototype.unhighlightItem=function(e){if(!e||!e.id)return this;var t=e.id,i=e.groupId,n=void 0===i?-1:i,o=e.value,r=void 0===o?"":o,s=e.label,a=void 0===s?"":s,c=n>=0?this._store.getGroupById(n):null;return this._store.dispatch((0,l.highlightItem)(t,!1)),this.passedElement.triggerEvent(d.EVENTS.highlightItem,{id:t,value:r,label:a,groupValue:c&&c.value?c.value:null}),this},e.prototype.highlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.highlightItem(t)})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.unhighlightItem(t)})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent(d.EVENTS.showDropdown,{})})),this},e.prototype.hideDropdown=function(e){var t=this;return this.dropdown.isActive?(requestAnimationFrame((function(){t.dropdown.hide(),t.containerOuter.close(),!e&&t._canSearch&&(t.input.removeActiveDescendant(),t.input.blur()),t.passedElement.triggerEvent(d.EVENTS.hideDropdown,{})})),this):this},e.prototype.getValue=function(e){void 0===e&&(e=!1);var t=this._store.activeItems.reduce((function(t,i){var n=e?i.value:i;return t.push(n),t}),[]);return this._isSelectOneElement?t[0]:t},e.prototype.setValue=function(e){var t=this;return this.initialised?(e.forEach((function(e){return t._setChoiceOrItem(e)})),this):this},e.prototype.setChoiceByValue=function(e){var t=this;return!this.initialised||this._isTextElement||(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)})),this},e.prototype.setChoices=function(e,t,i,n){var o=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===i&&(i="label"),void 0===n&&(n=!1),!this.initialised)throw new ReferenceError("setChoices was called on a non-initialized instance of Choices");if(!this._isSelectElement)throw new TypeError("setChoices can't be used with INPUT based Choices");if("string"!=typeof t||!t)throw new TypeError("value parameter must be a name of 'value' field in passed objects");if(n&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return o._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return o.setChoices(e,t,i,n)})).catch((function(e){o.config.silent||console.error(e)})).then((function(){return o._handleLoadingState(!1)})).then((function(){return o}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,i,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._startLoading(),e.forEach((function(e){if(e.choices)o._addGroup({id:e.id?parseInt("".concat(e.id),10):null,group:e,valueKey:t,labelKey:i});else{var n=e;o._addChoice({value:n[t],label:n[i],isSelected:!!n.selected,isDisabled:!!n.disabled,placeholder:!!n.placeholder,customProperties:n.customProperties})}})),this._stopLoading(),this},e.prototype.clearChoices=function(){return this._store.dispatch((0,a.clearChoices)()),this},e.prototype.clearStore=function(){return this._store.dispatch((0,h.clearAll)()),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),!this._isTextElement&&this._canSearch&&(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0))),this},e.prototype._render=function(){if(!this._store.isLoading()){this._currentState=this._store.state;var e=this._currentState.choices!==this._prevState.choices||this._currentState.groups!==this._prevState.groups||this._currentState.items!==this._prevState.items,t=this._isSelectElement,i=this._currentState.items!==this._prevState.items;e&&(t&&this._renderChoices(),i&&this._renderItems(),this._prevState=this._currentState)}},e.prototype._renderChoices=function(){var e=this,t=this._store,i=t.activeGroups,n=t.activeChoices,o=document.createDocumentFragment();if(this.choiceList.clear(),this.config.resetScrollPosition&&requestAnimationFrame((function(){return e.choiceList.scrollToTop()})),i.length>=1&&!this._isSearching){var r=n.filter((function(e){return!0===e.placeholder&&-1===e.groupId}));r.length>=1&&(o=this._createChoicesFragment(r,o)),o=this._createGroupsFragment(i,n,o)}else n.length>=1&&(o=this._createChoicesFragment(n,o));if(o.childNodes&&o.childNodes.length>0){var s=this._store.activeItems,a=this._canAddItem(s,this.input.value);if(a.response)this.choiceList.append(o),this._highlightChoice();else{var c=this._getTemplate("notice",a.notice);this.choiceList.append(c)}}else{var l=void 0;c=void 0,this._isSearching?(c="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText,l=this._getTemplate("notice",c,"no-results")):(c="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText,l=this._getTemplate("notice",c,"no-choices")),this.choiceList.append(l)}},e.prototype._renderItems=function(){var e=this._store.activeItems||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;return void 0===i&&(i=document.createDocumentFragment()),this.config.shouldSort&&e.sort(this.config.sorter),e.forEach((function(e){var o=function(e){return t.filter((function(t){return n._isSelectOneElement?t.groupId===e.id:t.groupId===e.id&&("always"===n.config.renderSelectedChoices||!t.selected)}))}(e);if(o.length>=1){var r=n._getTemplate("choiceGroup",e);i.appendChild(r),n._createChoicesFragment(o,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var o=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var r=this.config,s=r.renderSelectedChoices,a=r.searchResultLimit,c=r.renderChoiceLimit,l=this._isSearching?f.sortByScore:this.config.sorter,h=function(e){if("auto"!==s||o._isSelectOneElement||!e.selected){var i=o._getTemplate("choice",e,o.config.itemSelectText);t.appendChild(i)}},u=e;"auto"!==s||this._isSelectOneElement||(u=e.filter((function(e){return!e.selected})));var d=u.reduce((function(e,t){return t.placeholder?e.placeholderChoices.push(t):e.normalChoices.push(t),e}),{placeholderChoices:[],normalChoices:[]}),p=d.placeholderChoices,m=d.normalChoices;(this.config.shouldSort||this._isSearching)&&m.sort(l);var v=u.length,_=this._isSelectOneElement?n(n([],p,!0),m,!0):m;this._isSearching?v=a:c&&c>0&&!i&&(v=c);for(var g=0;g=n){var s=o?this._searchChoices(e):0;this.passedElement.triggerEvent(d.EVENTS.search,{value:e,resultCount:s})}else r&&(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0)))}},e.prototype._canAddItem=function(e,t){var i=!0,n="function"==typeof this.config.addItemText?this.config.addItemText(t):this.config.addItemText;if(!this._isSelectOneElement){var o=(0,f.existsInArray)(e,t);this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(i=!1,n="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText),!this.config.duplicateItemsAllowed&&o&&i&&(i=!1,n="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(t):this.config.uniqueItemText),this._isTextElement&&this.config.addItems&&i&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(i=!1,n="function"==typeof this.config.customAddItemText?this.config.customAddItemText(t):this.config.customAddItemText)}return{response:i,notice:n}},e.prototype._searchChoices=function(e){var t="string"==typeof e?e.trim():e,i="string"==typeof this._currentValue?this._currentValue.trim():this._currentValue;if(t.length<1&&t==="".concat(i," "))return 0;var o=this._store.searchableChoices,r=t,c=n([],this.config.searchFields,!0),l=Object.assign(this.config.fuseOptions,{keys:c,includeMatches:!0}),h=new s.default(o,l).search(r);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch((0,a.filterChoices)(h)),h.length},e.prototype._addEventListeners=function(){var e=document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.addEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.addEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.addEventListener("blur",this._onBlur,{passive:!0})),this.input.element.addEventListener("keyup",this._onKeyUp,{passive:!0}),this.input.element.addEventListener("focus",this._onFocus,{passive:!0}),this.input.element.addEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.addEventListener("reset",this._onFormReset,{passive:!0}),this.input.addEventListeners()},e.prototype._removeEventListeners=function(){var e=document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("focus",this._onFocus),this.input.element.removeEventListener("blur",this._onBlur),this.input.element.form&&this.input.element.form.removeEventListener("reset",this._onFormReset),this.input.removeEventListeners()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.activeItems,n=this.input.isFocussed,o=this.dropdown.isActive,r=this.itemList.hasChildren(),s=String.fromCharCode(t),a=/[a-zA-Z0-9-_ ]/.test(s),c=d.KEY_CODES.BACK_KEY,l=d.KEY_CODES.DELETE_KEY,h=d.KEY_CODES.ENTER_KEY,u=d.KEY_CODES.A_KEY,p=d.KEY_CODES.ESC_KEY,f=d.KEY_CODES.UP_KEY,m=d.KEY_CODES.DOWN_KEY,v=d.KEY_CODES.PAGE_UP_KEY,_=d.KEY_CODES.PAGE_DOWN_KEY;switch(this._isTextElement||o||!a||(this.showDropdown(),this.input.isFocussed||(this.input.value+=s.toLowerCase())),t){case u:return this._onSelectKey(e,r);case h:return this._onEnterKey(e,i,o);case p:return this._onEscapeKey(o);case f:case v:case m:case _:return this._onDirectionKey(e,o);case l:case c:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(e){var t=e.target,i=e.keyCode,n=this.input.value,o=this._store.activeItems,r=this._canAddItem(o,n),s=d.KEY_CODES.BACK_KEY,c=d.KEY_CODES.DELETE_KEY;if(this._isTextElement)if(r.notice&&n){var l=this._getTemplate("notice",r.notice);this.dropdown.element.innerHTML=l.outerHTML,this.showDropdown(!0)}else this.hideDropdown(!0);else{var h=(i===s||i===c)&&t&&!t.value,u=!this._isTextElement&&this._isSearching,p=this._canSearch&&r.response;h&&u?(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0))):p&&this._handleSearch(this.input.value)}this._canSearch=this.config.searchEnabled},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=e.target,o=d.KEY_CODES.ENTER_KEY,r=n&&n.hasAttribute("data-button");if(this._isTextElement&&n&&n.value){var s=this.input.value;this._canAddItem(t,s).response&&(this.hideDropdown(!0),this._addItem({value:s}),this._triggerChange(s),this.clearInput())}if(r&&(this._handleButtonAction(t,n),e.preventDefault()),i){var a=this.dropdown.getChild(".".concat(this.config.classNames.highlightedState));a&&(t[0]&&(t[0].keyCode=o),this._handleChoiceAction(t,a)),e.preventDefault()}else this._isSelectOneElement&&(this.showDropdown(),e.preventDefault())},e.prototype._onEscapeKey=function(e){e&&(this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i=e.keyCode,n=e.metaKey,o=d.KEY_CODES.DOWN_KEY,r=d.KEY_CODES.PAGE_UP_KEY,s=d.KEY_CODES.PAGE_DOWN_KEY;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=i===o||i===s?1:-1,c="[data-choice-selectable]",l=void 0;if(n||i===s||i===r)l=a>0?this.dropdown.element.querySelector("".concat(c,":last-of-type")):this.dropdown.element.querySelector(c);else{var h=this.dropdown.element.querySelector(".".concat(this.config.classNames.highlightedState));l=h?(0,f.getAdjacentEl)(h,c,a):this.dropdown.element.querySelector(c)}l&&((0,f.isScrolledIntoView)(l,this.choiceList.element,a)||this.choiceList.scrollToChildElement(l,a),this._highlightChoice(l)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._onTouchEnd=function(e){var t=(e||e.touches[0]).target;this._wasTap&&this.containerOuter.element.contains(t)&&((t===this.containerOuter.element||t===this.containerInner.element)&&(this._isTextElement?this.input.focus():this._isSelectMultipleElement&&this.showDropdown()),e.stopPropagation()),this._wasTap=!0},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(g&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild,n="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[d.TEXT_TYPE]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[d.SELECT_ONE_TYPE]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[d.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this.passedElement.element.type]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var o=this._store.activeItems.some((function(e){return e.highlighted}));((t={})[d.TEXT_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),o&&i.unhighlightAll(),i.hideDropdown(!0))},t[d.SELECT_ONE_TYPE]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[d.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),o&&i.unhighlightAll())},t)[this.passedElement.element.type]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){this._store.dispatch((0,h.resetTo)(this._initialState))},e.prototype._highlightChoice=function(e){var t=this;void 0===e&&(e=null);var i=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(i.length){var n=e;Array.from(this.dropdown.element.querySelectorAll(".".concat(this.config.classNames.highlightedState))).forEach((function(e){e.classList.remove(t.config.classNames.highlightedState),e.setAttribute("aria-selected","false")})),n?this._highlightPosition=i.indexOf(n):(n=i.length>this._highlightPosition?i[this._highlightPosition]:i[i.length-1])||(n=i[0]),n.classList.add(this.config.classNames.highlightedState),n.setAttribute("aria-selected","true"),this.passedElement.triggerEvent(d.EVENTS.highlightChoice,{el:n}),this.dropdown.isActive&&(this.input.setActiveDescendant(n.id),this.containerOuter.setActiveDescendant(n.id))}},e.prototype._addItem=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,o=e.choiceId,r=void 0===o?-1:o,s=e.groupId,a=void 0===s?-1:s,c=e.customProperties,h=void 0===c?{}:c,u=e.placeholder,p=void 0!==u&&u,f=e.keyCode,m=void 0===f?-1:f,v="string"==typeof t?t.trim():t,_=this._store.items,g=n||v,y=r||-1,E=a>=0?this._store.getGroupById(a):null,b=_?_.length+1:1;this.config.prependValue&&(v=this.config.prependValue+v.toString()),this.config.appendValue&&(v+=this.config.appendValue.toString()),this._store.dispatch((0,l.addItem)({value:v,label:g,id:b,choiceId:y,groupId:a,customProperties:h,placeholder:p,keyCode:m})),this._isSelectOneElement&&this.removeActiveItems(b),this.passedElement.triggerEvent(d.EVENTS.addItem,{id:b,value:v,label:g,customProperties:h,groupValue:E&&E.value?E.value:null,keyCode:m})},e.prototype._removeItem=function(e){var t=e.id,i=e.value,n=e.label,o=e.customProperties,r=e.choiceId,s=e.groupId,a=s&&s>=0?this._store.getGroupById(s):null;t&&r&&(this._store.dispatch((0,l.removeItem)(t,r)),this.passedElement.triggerEvent(d.EVENTS.removeItem,{id:t,value:i,label:n,customProperties:o,groupValue:a&&a.value?a.value:null}))},e.prototype._addChoice=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,o=e.isSelected,r=void 0!==o&&o,s=e.isDisabled,c=void 0!==s&&s,l=e.groupId,h=void 0===l?-1:l,u=e.customProperties,d=void 0===u?{}:u,p=e.placeholder,f=void 0!==p&&p,m=e.keyCode,v=void 0===m?-1:m;if(null!=t){var _=this._store.choices,g=n||t,y=_?_.length+1:1,E="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(y);this._store.dispatch((0,a.addChoice)({id:y,groupId:h,elementId:E,value:t,label:g,disabled:c,customProperties:d,placeholder:f,keyCode:v})),r&&this._addItem({value:t,label:g,choiceId:y,customProperties:d,placeholder:f,keyCode:v})}},e.prototype._addGroup=function(e){var t=this,i=e.group,n=e.id,o=e.valueKey,r=void 0===o?"value":o,s=e.labelKey,a=void 0===s?"label":s,l=(0,f.isType)("Object",i)?i.choices:Array.from(i.getElementsByTagName("OPTION")),h=n||Math.floor((new Date).valueOf()*Math.random()),u=!!i.disabled&&i.disabled;l?(this._store.dispatch((0,c.addGroup)({value:i.label,id:h,active:!0,disabled:u})),l.forEach((function(e){var i=e.disabled||e.parentNode&&e.parentNode.disabled;t._addChoice({value:e[r],label:(0,f.isType)("Object",e)?e[a]:e.innerHTML,isSelected:e.selected,isDisabled:i,groupId:h,customProperties:e.customProperties,placeholder:e.placeholder})}))):this._store.dispatch((0,c.addGroup)({value:i.label,id:i.id,active:!1,disabled:i.disabled}))},e.prototype._getTemplate=function(e){for(var t,i=[],o=1;o0?this.element.scrollTop+s-o:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(a,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,o=n>1?n:1;this.element.scrollTop=e+o},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,o=n>1?n:1;this.element.scrollTop=e-o},e.prototype._animateScroll=function(e,t){var i=this,o=n.SCROLLING_SPEED,r=this.element.scrollTop,s=!1;t>0?(this._scrollDown(r,o,e),re&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}();t.default=o},730:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=i(799),o=function(){function e(e){var t=e.element,i=e.classNames;if(this.element=t,this.classNames=i,!(t instanceof HTMLInputElement||t instanceof HTMLSelectElement))throw new TypeError("Invalid element passed");this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){this.element.classList.add(this.classNames.input),this.element.hidden=!0,this.element.tabIndex=-1;var e=this.element.getAttribute("style");e&&this.element.setAttribute("data-choice-orig-style",e),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){this.element.classList.remove(this.classNames.input),this.element.hidden=!1,this.element.removeAttribute("tabindex");var e=this.element.getAttribute("data-choice-orig-style");e?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",e)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){(0,n.dispatchEvent)(this.element,e,t)},e}();t.default=o},541:function(e,t,i){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var s=function(e){function t(t){var i=t.element,n=t.classNames,o=t.delimiter,r=e.call(this,{element:i,classNames:n})||this;return r.delimiter=o,r}return o(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),t}(r(i(730)).default);t.default=s},982:function(e,t,i){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var s=function(e){function t(t){var i=t.element,n=t.classNames,o=t.template,r=e.call(this,{element:i,classNames:n})||this;return r.template=o,r}return o(t,e),Object.defineProperty(t.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"optionGroups",{get:function(){return Array.from(this.element.getElementsByTagName("OPTGROUP"))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return Array.from(this.element.options)},set:function(e){var t=this,i=document.createDocumentFragment();e.forEach((function(e){return n=e,o=t.template(n),void i.appendChild(o);var n,o})),this.appendDocFragment(i)},enumerable:!1,configurable:!0}),t.prototype.appendDocFragment=function(e){this.element.innerHTML="",this.element.appendChild(e)},t}(r(i(730)).default);t.default=s},883:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SCROLLING_SPEED=t.SELECT_MULTIPLE_TYPE=t.SELECT_ONE_TYPE=t.TEXT_TYPE=t.KEY_CODES=t.ACTION_TYPES=t.EVENTS=void 0,t.EVENTS={showDropdown:"showDropdown",hideDropdown:"hideDropdown",change:"change",choice:"choice",search:"search",addItem:"addItem",removeItem:"removeItem",highlightItem:"highlightItem",highlightChoice:"highlightChoice",unhighlightItem:"unhighlightItem"},t.ACTION_TYPES={ADD_CHOICE:"ADD_CHOICE",FILTER_CHOICES:"FILTER_CHOICES",ACTIVATE_CHOICES:"ACTIVATE_CHOICES",CLEAR_CHOICES:"CLEAR_CHOICES",ADD_GROUP:"ADD_GROUP",ADD_ITEM:"ADD_ITEM",REMOVE_ITEM:"REMOVE_ITEM",HIGHLIGHT_ITEM:"HIGHLIGHT_ITEM",CLEAR_ALL:"CLEAR_ALL",RESET_TO:"RESET_TO",SET_IS_LOADING:"SET_IS_LOADING"},t.KEY_CODES={BACK_KEY:46,DELETE_KEY:8,ENTER_KEY:13,A_KEY:65,ESC_KEY:27,UP_KEY:38,DOWN_KEY:40,PAGE_UP_KEY:33,PAGE_DOWN_KEY:34},t.TEXT_TYPE="text",t.SELECT_ONE_TYPE="select-one",t.SELECT_MULTIPLE_TYPE="select-multiple",t.SCROLLING_SPEED=4},789:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CONFIG=t.DEFAULT_CLASSNAMES=void 0;var n=i(799);t.DEFAULT_CLASSNAMES={containerOuter:"choices",containerInner:"choices__inner",input:"choices__input",inputCloned:"choices__input--cloned",list:"choices__list",listItems:"choices__list--multiple",listSingle:"choices__list--single",listDropdown:"choices__list--dropdown",item:"choices__item",itemSelectable:"choices__item--selectable",itemDisabled:"choices__item--disabled",itemChoice:"choices__item--choice",placeholder:"choices__placeholder",group:"choices__group",groupHeading:"choices__heading",button:"choices__button",activeState:"is-active",focusState:"is-focused",openState:"is-open",disabledState:"is-disabled",highlightedState:"is-highlighted",selectedState:"is-selected",flippedState:"is-flipped",loadingState:"is-loading",noResults:"has-no-results",noChoices:"has-no-choices"},t.DEFAULT_CONFIG={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,addItems:!0,addItemFilter:null,removeItems:!0,removeItemButton:!1,editItems:!1,allowHTML:!0,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:n.sortByAlpha,placeholder:!0,placeholderValue:null,searchPlaceholderValue:null,prependValue:null,appendValue:null,renderSelectedChoices:"auto",loadingText:"Loading...",noResultsText:"No results found",noChoicesText:"No choices to choose from",itemSelectText:"Press to select",uniqueItemText:"Only unique values can be added",customAddItemText:"Only values matching specific conditions can be added",addItemText:function(e){return'Press Enter to add "'.concat((0,n.sanitise)(e),'"')},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},callbackOnInit:null,callbackOnCreateTemplates:null,classNames:t.DEFAULT_CLASSNAMES}},799:function(e,t){"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.cloneObject=t.existsInArray=t.dispatchEvent=t.sortByScore=t.sortByAlpha=t.strToEl=t.sanitise=t.isScrolledIntoView=t.getAdjacentEl=t.wrap=t.isType=t.getType=t.generateId=t.generateChars=t.getRandomNumber=void 0,t.getRandomNumber=function(e,t){return Math.floor(Math.random()*(t-e)+e)},t.generateChars=function(e){return Array.from({length:e},(function(){return(0,t.getRandomNumber)(0,36).toString(36)})).join("")},t.generateId=function(e,i){var n=e.id||e.name&&"".concat(e.name,"-").concat((0,t.generateChars)(2))||(0,t.generateChars)(4);return n=n.replace(/(:|\.|\[|\]|,)/g,""),"".concat(i,"-").concat(n)},t.getType=function(e){return Object.prototype.toString.call(e).slice(8,-1)},t.isType=function(e,i){return null!=i&&(0,t.getType)(i)===e},t.wrap=function(e,t){return void 0===t&&(t=document.createElement("div")),e.parentNode&&(e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t)),t.appendChild(e)},t.getAdjacentEl=function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),o=e[n];o;){if(o.matches(t))return o;o=o[n]}return o},t.isScrolledIntoView=function(e,t,i){return void 0===i&&(i=1),!!e&&(i>0?t.scrollTop+t.offsetHeight>=e.offsetTop+e.offsetHeight:e.offsetTop>=t.scrollTop)},t.sanitise=function(e){return"string"!=typeof e?e:e.replace(/&/g,"&").replace(/>/g,">").replace(/-1?e.map((function(e){var t=e;return t.id===parseInt("".concat(s.choiceId),10)&&(t.selected=!0),t})):e;case"REMOVE_ITEM":var a=n;return a.choiceId&&a.choiceId>-1?e.map((function(e){var t=e;return t.id===parseInt("".concat(a.choiceId),10)&&(t.selected=!1),t})):e;case"FILTER_CHOICES":var c=n;return e.map((function(e){var t=e;return t.active=c.results.some((function(e){var i=e.item,n=e.score;return i.id===t.id&&(t.score=n,!0)})),t}));case"ACTIVATE_CHOICES":var l=n;return e.map((function(e){var t=e;return t.active=l.active,t}));case"CLEAR_CHOICES":return t.defaultState;default:return e}}},871:function(e,t){"use strict";var i=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,o=0,r=t.length;o0?"treeitem":"option"),Object.assign(E.dataset,{choice:"",id:d,value:p,selectText:i}),_?(E.classList.add(h),E.dataset.choiceDisabled="",E.setAttribute("aria-disabled","true")):(E.classList.add(c),E.dataset.choiceSelectable=""),E},input:function(e,t){var i=e.classNames,n=i.input,o=i.inputCloned,r=Object.assign(document.createElement("input"),{type:"search",name:"search_terms",className:"".concat(n," ").concat(o),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return r.setAttribute("role","textbox"),r.setAttribute("aria-autocomplete","list"),r.setAttribute("aria-label",t),r},dropdown:function(e){var t=e.classNames,i=t.list,n=t.listDropdown,o=document.createElement("div");return o.classList.add(i,n),o.setAttribute("aria-expanded","false"),o},notice:function(e,t,i){var n,o=e.allowHTML,r=e.classNames,s=r.item,a=r.itemChoice,c=r.noResults,l=r.noChoices;void 0===i&&(i="");var h=[s,a];return"no-choices"===i?h.push(l):"no-results"===i&&h.push(c),Object.assign(document.createElement("div"),((n={})[o?"innerHTML":"innerText"]=t,n.className=h.join(" "),n))},option:function(e){var t=e.label,i=e.value,n=e.customProperties,o=e.active,r=e.disabled,s=new Option(t,i,!1,o);return n&&(s.dataset.customProperties="".concat(n)),s.disabled=!!r,s}};t.default=i},996:function(e){"use strict";var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===i}(e)}(e)},i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((i=e,Array.isArray(i)?[]:{}),e,t):e;var i}function o(e,t,i){return e.concat(t).map((function(e){return n(e,i)}))}function r(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return e.propertyIsEnumerable(t)})):[]}(e))}function s(e,t){try{return t in e}catch(e){return!1}}function a(e,i,c){(c=c||{}).arrayMerge=c.arrayMerge||o,c.isMergeableObject=c.isMergeableObject||t,c.cloneUnlessOtherwiseSpecified=n;var l=Array.isArray(i);return l===Array.isArray(e)?l?c.arrayMerge(e,i,c):function(e,t,i){var o={};return i.isMergeableObject(e)&&r(e).forEach((function(t){o[t]=n(e[t],i)})),r(t).forEach((function(r){(function(e,t){return s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,r)||(s(e,r)&&i.isMergeableObject(t[r])?o[r]=function(e,t){if(!t.customMerge)return a;var i=t.customMerge(e);return"function"==typeof i?i:a}(r,i)(e[r],t[r],i):o[r]=n(t[r],i))})),o}(e,i,c):n(i,c)}a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,i){return a(e,i,t)}),{})};var c=a;e.exports=c},70:function(e){e.exports=function(e){var t={};function i(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,i),o.l=!0,o.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)i.d(n,o,function(t){return e[t]}.bind(null,o));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=1)}([function(e,t){e.exports=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)}},function(e,t,i){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:{limit:!1};this._log('---------\nSearch pattern: "'.concat(e,'"'));var i=this._prepareSearchers(e),n=i.tokenSearchers,o=i.fullSearcher,r=this._search(n,o),s=r.weights,a=r.results;return this._computeScore(s,a),this.options.shouldSort&&this._sort(a),t.limit&&"number"==typeof t.limit&&(a=a.slice(0,t.limit)),this._format(a)}},{key:"_prepareSearchers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=[];if(this.options.tokenize)for(var i=e.split(this.options.tokenSeparator),n=0,o=i.length;n0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,i=this.list,n={},o=[];if("string"==typeof i[0]){for(var r=0,s=i.length;r1)throw new Error("Key weight has to be > 0 and <= 1");p=p.name}else a[p]={weight:1};this._analyze({key:p,value:this.options.getFn(h,p),record:h,index:c},{resultMap:n,results:o,tokenSearchers:e,fullSearcher:t})}return{weights:a,results:o}}},{key:"_analyze",value:function(e,t){var i=e.key,n=e.arrayIndex,o=void 0===n?-1:n,r=e.value,s=e.record,c=e.index,l=t.tokenSearchers,h=void 0===l?[]:l,u=t.fullSearcher,d=void 0===u?[]:u,p=t.resultMap,f=void 0===p?{}:p,m=t.results,v=void 0===m?[]:m;if(null!=r){var _=!1,g=-1,y=0;if("string"==typeof r){this._log("\nKey: ".concat(""===i?"-":i));var E=d.search(r);if(this._log('Full text: "'.concat(r,'", score: ').concat(E.score)),this.options.tokenize){for(var b=r.split(this.options.tokenSeparator),S=[],I=0;I-1&&(N=(N+g)/2),this._log("Score average:",N);var M=!this.options.tokenize||!this.options.matchAllTokens||y>=h.length;if(this._log("\nCheck Matches: ".concat(M)),(_||E.isMatch)&&M){var x=f[c];x?x.output.push({key:i,arrayIndex:o,value:r,score:N,matchedIndices:E.matchedIndices}):(f[c]={item:s,output:[{key:i,arrayIndex:o,value:r,score:N,matchedIndices:E.matchedIndices}]},v.push(f[c]))}}else if(a(r))for(var j=0,F=r.length;j-1&&(s.arrayIndex=r.arrayIndex),t.matches.push(s)}}})),this.options.includeScore&&o.push((function(e,t){t.score=e.score}));for(var r=0,s=e.length;ri)return o(e,this.pattern,n);var s=this.options,a=s.location,c=s.distance,l=s.threshold,h=s.findAllMatches,u=s.minMatchCharLength;return r(e,this.pattern,this.patternAlphabet,{location:a,distance:c,threshold:l,findAllMatches:h,minMatchCharLength:u})}}])&&n(t.prototype,i),e}();e.exports=a},function(e,t){var i=/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g;e.exports=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:/ +/g,o=new RegExp(t.replace(i,"\\$&").replace(n,"|")),r=e.match(o),s=!!r,a=[];if(s)for(var c=0,l=r.length;c=N;j-=1){var F=j-1,k=i[e.charAt(F)];if(k&&(b[F]=1),x[j]=(x[j+1]<<1|1)&k,0!==w&&(x[j]|=(T[j+1]|T[j])<<1|1|T[j+1]),x[j]&L&&(C=n(t,{errors:w,currentLocation:F,expectedLocation:v,distance:l}))<=g){if(g=C,(y=F)<=v)break;N=Math.max(1,2*v-y)}}if(n(t,{errors:w+1,currentLocation:v,expectedLocation:v,distance:l})>g)break;T=x}return{isMatch:y>=0,score:0===C?.001:C,matchedIndices:o(b,m)}}},function(e,t){e.exports=function(e,t){var i=t.errors,n=void 0===i?0:i,o=t.currentLocation,r=void 0===o?0:o,s=t.expectedLocation,a=void 0===s?0:s,c=t.distance,l=void 0===c?100:c,h=n/e.length,u=Math.abs(a-r);return l?h+u/l:u?1:h}},function(e,t){e.exports=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=[],n=-1,o=-1,r=0,s=e.length;r=t&&i.push([n,o]),n=-1)}return e[r-1]&&r-n>=t&&i.push([n,r-1]),i}},function(e,t){e.exports=function(e){for(var t={},i=e.length,n=0;n
+
+ + +
+ +
+ + +
+ +
+ + +
+
@@ -134,25 +149,52 @@
From 3633c4ac0f0a8437ea4ffdc44de0b872c8e816c5 Mon Sep 17 00:00:00 2001 From: viction Date: Sat, 25 Dec 2021 20:29:15 +0000 Subject: [PATCH 4/9] test: select-one coverage --- cypress/integration/select-one.spec.ts | 167 +++++++++++++++---------- public/test/select-one/index.html | 133 ++++++++++++++++++-- 2 files changed, 218 insertions(+), 82 deletions(-) diff --git a/cypress/integration/select-one.spec.ts b/cypress/integration/select-one.spec.ts index 3b3b0b0..1fb470e 100644 --- a/cypress/integration/select-one.spec.ts +++ b/cypress/integration/select-one.spec.ts @@ -1,6 +1,10 @@ describe('Choices - select one', () => { beforeEach(() => { - cy.visit('/select-one'); + cy.visit('/select-one', { + onBeforeLoad(win) { + cy.stub(win.console, 'warn').as('consoleWarn'); + }, + }); }); describe('scenarios', () => { @@ -51,9 +55,7 @@ describe('Choices - select one', () => { describe('selecting choices', () => { beforeEach(() => { // open dropdown - cy.get('[data-test-hook=basic]') - .find('.choices') - .click(); + cy.get('[data-test-hook=basic]').find('.choices').click(); }); const selectedChoiceText = 'Choice 1'; @@ -68,7 +70,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=basic]') .find('.choices__list--single .choices__item') .last() - .should($item => { + .should(($item) => { expect($item).to.contain(selectedChoiceText); }); }); @@ -84,7 +86,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .should($item => { + .should(($item) => { expect($item).to.contain(selectedChoiceText); }); }); @@ -93,9 +95,7 @@ describe('Choices - select one', () => { describe('searching choices', () => { beforeEach(() => { // open dropdown - cy.get('[data-test-hook=basic]') - .find('.choices') - .click(); + cy.get('[data-test-hook=basic]').find('.choices').click(); }); describe('on input', () => { @@ -109,7 +109,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal('Choice 2'); }); }); @@ -125,7 +125,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal('Choice 3'); }); }); @@ -140,7 +140,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=basic]') .find('.choices__list--dropdown') .should('be.visible') - .should($dropdown => { + .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal('No results found'); }); @@ -206,7 +206,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=remove-button]') .find('.choices__list--single .choices__item') .last() - .then($choice => { + .then(($choice) => { removedChoiceText = $choice.text().trim(); }) .click(); @@ -229,7 +229,7 @@ describe('Choices - select one', () => { it('updates the value of the original input', () => { cy.get('[data-test-hook=remove-button]') .find('.choices__input[hidden]') - .should($select => { + .should(($select) => { const val = $select.val() || []; expect(val).to.not.contain(removedChoiceText); @@ -248,7 +248,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=disabled-choice]') .find('.choices__list--dropdown .choices__item--disabled') - .then($choice => { + .then(($choice) => { selectedChoiceText = $choice.text().trim(); }) .click(); @@ -258,7 +258,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=prepend-append]') .find('.choices__list--single .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.text()).to.not.contain(selectedChoiceText); }); }); @@ -305,9 +305,7 @@ describe('Choices - select one', () => { describe('on click', () => { it('does not open choice dropdown', () => { - cy.get('[data-test-hook=disabled-via-attr]') - .find('.choices') - .click(); + cy.get('[data-test-hook=disabled-via-attr]').find('.choices').click(); cy.get('[data-test-hook=disabled-via-attr]') .find('.choices__list--dropdown') @@ -335,7 +333,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .last() - .then($choice => { + .then(($choice) => { selectedChoiceText = $choice.text().trim(); }) .click(); @@ -345,7 +343,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=prepend-append]') .find('.choices__list--single .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.data('value')).to.equal( `before-${selectedChoiceText}-after`, ); @@ -356,7 +354,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=prepend-append]') .find('.choices__list--single .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.text()).to.not.contain( `before-${selectedChoiceText}-after`, ); @@ -389,9 +387,7 @@ describe('Choices - select one', () => { const selectedChoiceText = 'Choice 3'; beforeEach(() => { - cy.get('[data-test-hook=search-disabled]') - .find('.choices') - .click(); + cy.get('[data-test-hook=search-disabled]').find('.choices').click(); }); it('does not display a search input', () => { @@ -410,7 +406,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=search-disabled]') .find('.choices__list--single .choices__item') .last() - .should($item => { + .should(($item) => { expect($item).to.contain(selectedChoiceText); }); }); @@ -442,7 +438,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.not.contain(searchTerm); }); }); @@ -460,7 +456,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.contain(searchTerm); }); }); @@ -476,7 +472,7 @@ describe('Choices - select one', () => { .children() .first() .should('have.class', 'choices__placeholder') - .and($placeholder => { + .and(($placeholder) => { expect($placeholder).to.contain('I am a placeholder'); }); }); @@ -524,7 +520,7 @@ describe('Choices - select one', () => { .children() .first() .should('have.class', 'choices__placeholder') - .and($placeholder => { + .and(($placeholder) => { expect($placeholder).to.contain('I am a placeholder'); }); }); @@ -577,7 +573,7 @@ describe('Choices - select one', () => { .should('have.length', 1) .first() .should('have.class', 'choices__placeholder') - .and($placeholder => { + .and(($placeholder) => { expect($placeholder).to.contain('Loading...'); }); }); @@ -620,19 +616,17 @@ describe('Choices - select one', () => { beforeEach(() => { cy.get('[data-test-hook=scrolling-dropdown]') .find('.choices__list--dropdown .choices__list .choices__item') - .then($choices => { + .then(($choices) => { choicesCount = $choices.length; }); - cy.get('[data-test-hook=scrolling-dropdown]') - .find('.choices') - .click(); + cy.get('[data-test-hook=scrolling-dropdown]').find('.choices').click(); }); it('highlights first choice on dropdown open', () => { cy.get('[data-test-hook=scrolling-dropdown]') .find('.choices__list--dropdown .choices__list .is-highlighted') - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal('Choice 1'); }); }); @@ -641,7 +635,7 @@ describe('Choices - select one', () => { for (let index = 0; index < choicesCount; index++) { cy.get('[data-test-hook=scrolling-dropdown]') .find('.choices__list--dropdown .choices__list .is-highlighted') - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal(`Choice ${index + 1}`); }); @@ -665,7 +659,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=scrolling-dropdown]') .find('.choices__list--dropdown .choices__list .is-highlighted') - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal(`Choice ${index}`); }); @@ -684,7 +678,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=groups]') .find('.choices__list--dropdown .choices__list .choices__group') .first() - .then($group => { + .then(($group) => { groupValue = $group.text().trim(); }); }); @@ -705,7 +699,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=groups]') .find('.choices__list--dropdown .choices__list .choices__group') .first() - .should($group => { + .should(($group) => { expect($group.text().trim()).to.not.equal(groupValue); }); }); @@ -736,7 +730,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=groups]') .find('.choices__list--dropdown .choices__list .choices__group') .first() - .should($group => { + .should(($group) => { expect($group.text().trim()).to.equal(groupValue); }); }); @@ -806,9 +800,7 @@ describe('Choices - select one', () => { describe('custom properties', () => { beforeEach(() => { - cy.get('[data-test-hook=custom-properties]') - .find('.choices') - .click(); + cy.get('[data-test-hook=custom-properties]').find('.choices').click(); }); describe('on input', () => { @@ -837,7 +829,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal(city); }); @@ -851,9 +843,7 @@ describe('Choices - select one', () => { describe('non-string values', () => { beforeEach(() => { - cy.get('[data-test-hook=non-string-values]') - .find('.choices') - .click(); + cy.get('[data-test-hook=non-string-values]').find('.choices').click(); }); it('displays expected amount of choices in dropdown', () => { @@ -869,7 +859,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .then($choice => { + .then(($choice) => { $selectedChoice = $choice; }) .click(); @@ -877,7 +867,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=non-string-values]') .find('.choices__list--single .choices__item') .last() - .should($item => { + .should(($item) => { expect($item.text().trim()).to.equal($selectedChoice.text().trim()); }); }); @@ -887,7 +877,7 @@ describe('Choices - select one', () => { describe('selecting choice', () => { describe('on enter key', () => { it('does not submit form', () => { - cy.get('[data-test-hook=within-form] form').then($form => { + cy.get('[data-test-hook=within-form] form').then(($form) => { $form.submit(() => { // this will fail the test if the form submits throw new Error('Form submitted'); @@ -900,14 +890,12 @@ describe('Choices - select one', () => { .find('.choices__input--cloned') .type('{enter}'); - cy.get('[data-test-hook=within-form]') - .find('.choices') - .click(); + cy.get('[data-test-hook=within-form]').find('.choices').click(); cy.get('[data-test-hook=within-form]') .find('.choices__list--single .choices__item') .last() - .should($item => { + .should(($item) => { expect($item).to.contain('Choice 1'); }); }); @@ -922,7 +910,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=set-choice-by-value]') .find('.choices__list--single .choices__item') .last() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal( dynamicallySelectedChoiceValue, ); @@ -932,7 +920,7 @@ describe('Choices - select one', () => { it('does not remove choice from dropdown list', () => { cy.get('[data-test-hook=set-choice-by-value]') .find('.choices__list--dropdown .choices__list') - .then($choicesList => { + .then(($choicesList) => { expect($choicesList).to.contain(dynamicallySelectedChoiceValue); }); }); @@ -940,7 +928,7 @@ describe('Choices - select one', () => { it('updates the value of the original input', () => { cy.get('[data-test-hook=set-choice-by-value]') .find('.choices__input[hidden]') - .should($select => { + .should(($select) => { const val = $select.val() || []; expect(val).to.contain(dynamicallySelectedChoiceValue); }); @@ -949,9 +937,7 @@ describe('Choices - select one', () => { describe('searching by label only', () => { beforeEach(() => { - cy.get('[data-test-hook=search-by-label]') - .find('.choices') - .click(); + cy.get('[data-test-hook=search-by-label]').find('.choices').click(); }); it('gets zero results when searching by value', () => { @@ -963,7 +949,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal('No results found'); }); }); @@ -977,7 +963,7 @@ describe('Choices - select one', () => { .find('.choices__list--dropdown .choices__list') .children() .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.equal('label1'); }); }); @@ -998,7 +984,7 @@ describe('Choices - select one', () => { .children() .first() .should('have.class', 'choices__item--disabled') - .then($choice => { + .then(($choice) => { disabledValue = $choice.val(); }); }); @@ -1006,19 +992,64 @@ describe('Choices - select one', () => { it('selects the first enabled choice', () => { cy.get('[data-test-hook=disabled-first-choice-via-options]') .find('.choices__input[hidden]') - .then($option => { + .then(($option) => { expect($option.text().trim()).to.not.equal(disabledValue); }); cy.get('[data-test-hook=disabled-first-choice-via-options]') .find('.choices__item.choices__item--selectable') .first() - .should($choice => { + .should(($choice) => { expect($choice.text().trim()).to.not.equal(disabledValue); }); }); }); + describe('allow html', () => { + describe('is undefined', () => { + it('logs a deprecation warning', () => { + cy.get('@consoleWarn').should( + 'be.calledOnceWithExactly', + 'Deprecation warning: allowHTML in the future will be defaulted to false. You must explicitly set it to true to properly display html tags in choices.', + ); + }); + + it('does not show html as text', () => { + cy.get('[data-test-hook=allowhtml-undefined]') + .find('.choices__list--dropdown .choices__list') + .children() + .first() + .should(($choice) => { + expect($choice.text().trim()).to.equal('Choice 1'); + }); + }); + }); + + describe('set to true', () => { + it('does not show html as text', () => { + cy.get('[data-test-hook=allowhtml-true]') + .find('.choices__list--dropdown .choices__list') + .children() + .first() + .should(($choice) => { + expect($choice.text().trim()).to.equal('Choice 1'); + }); + }); + }); + + describe('set to false', () => { + it('shows html as text', () => { + cy.get('[data-test-hook=allowhtml-false]') + .find('.choices__list--dropdown .choices__list') + .children() + .first() + .should(($choice) => { + expect($choice.text().trim()).to.equal('Choice 1'); + }); + }); + }); + }); + describe('re-initialising a choices instance', () => { it('preserves the choices list', () => { cy.get('[data-test-hook=new-destroy-init]') @@ -1029,9 +1060,7 @@ describe('Choices - select one', () => { cy.get('[data-test-hook=new-destroy-init]') .find('button.destroy') .click(); - cy.get('[data-test-hook=new-destroy-init]') - .find('button.init') - .click(); + cy.get('[data-test-hook=new-destroy-init]').find('button.init').click(); cy.get('[data-test-hook=new-destroy-init]') .find('.choices__list--dropdown .choices__list') diff --git a/public/test/select-one/index.html b/public/test/select-one/index.html index e54b391..9fb7401 100644 --- a/public/test/select-one/index.html +++ b/public/test/select-one/index.html @@ -354,6 +354,33 @@
+
+ + +
+ +
+ + +
+ +
+ + +
+
`; - instance = new Choices('[data-choice]'); + instance = new Choices('[data-choice]', { allowHTML: true }); expect(instance.passedElement).to.be.an.instanceOf(WrappedInput); }); @@ -197,7 +202,7 @@ describe('choices', () => { `; - instance = new Choices('[data-choice]'); + instance = new Choices('[data-choice]', { allowHTML: true }); expect(instance.passedElement).to.be.an.instanceOf(WrappedSelect); }); @@ -211,7 +216,7 @@ describe('choices', () => { `; - instance = new Choices('[data-choice]'); + instance = new Choices('[data-choice]', { allowHTML: true }); expect(instance.passedElement).to.be.an.instanceOf(WrappedInput); }); @@ -223,7 +228,7 @@ describe('choices', () => { `; - instance = new Choices('[data-choice]'); + instance = new Choices('[data-choice]', { allowHTML: true }); expect(instance.passedElement).to.be.an.instanceOf(WrappedSelect); }); @@ -235,7 +240,7 @@ describe('choices', () => { document.body.innerHTML = `
`; - expect(() => new Choices('[data-choice]')).to.throw( + expect(() => new Choices('[data-choice]', { allowHTML: true })).to.throw( TypeError, 'Expected one of the following types text|select-one|select-multiple', ); @@ -250,6 +255,7 @@ describe('choices', () => { beforeEach(() => { instance = new Choices(passedElement, { + allowHTML: true, callbackOnInit: callbackOnInitSpy, silent: true, }); @@ -330,7 +336,7 @@ describe('choices', () => { passedElement.className = 'js-choices'; document.body.appendChild(passedElement); - instance = new Choices(passedElement); + instance = new Choices(passedElement, { allowHTML: true }); }); describe('not already initialised', () => { @@ -1188,7 +1194,7 @@ describe('choices', () => { describe('select element', () => { it('fetches and sets choices', async () => { document.body.innerHTML = '