;
+
+ /**
+ * Function to run once Choices initialises.
+ *
+ * **Input types affected:** text, select-one, select-multiple
+ *
+ * @note For each callback, this refers to the current instance of This can be useful if you need access to methods `(this.disable())` or the config object `(this.config)`.
+ *
+ * @default null
+ */
+ callbackOnInit: ((this: Choices) => void) | null;
+
+ /**
+ * Function to run on template creation. Through this callback it is possible to provide custom templates for the various components of Choices (see terminology). For Choices to work with custom templates, it is important you maintain the various data attributes defined here [https://github.com/jshjohnson/Choices/blob/67f29c286aa21d88847adfcd6304dc7d068dc01f/assets/scripts/src/choices.js#L1993-L2067].
+ *
+ * **Input types affected:** text, select-one, select-multiple
+ *
+ * @note For each callback, this refers to the current instance of This can be useful if you need access to methods `(this.disable())` or the config object `(this.config)`.
+ *
+ * @example
+ * ```
+ * const example = new Choices(element, {
+ * callbackOnCreateTemplates: function (template) {
+ * var classNames = this.config.classNames;
+ * return {
+ * item: (data) => {
+ * return template(`
+ *
+ * ★ ${data.label}
+ *
+ * `);
+ * },
+ * choice: (data) => {
+ * return template(`
+ * 0 ? 'role="treeitem"' : 'role="option"'}>
+ * ★ ${data.label}
+ *
+ * `);
+ * },
+ * };
+ * }
+ * });
+ * ```
+ *
+ * @default null
+ */
+ callbackOnCreateTemplates: ((template: Types.strToEl) => void) | null;
+}
+
+// @todo rename
+export interface Notice {
+ response: boolean;
+ notice: string;
+}
+
+export interface State {
+ choices: Choice[];
+ groups: Group[];
+ items: Item[];
+ loading: boolean;
+}
diff --git a/src/scripts/lib/utils.js b/src/scripts/lib/utils.js
deleted file mode 100644
index 8cbd576c6..000000000
--- a/src/scripts/lib/utils.js
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * @param {number} min
- * @param {number} max
- * @returns {number}
- */
-export const getRandomNumber = (min, max) =>
- Math.floor(Math.random() * (max - min) + min);
-
-/**
- * @param {number} length
- * @returns {string}
- */
-export const generateChars = length =>
- Array.from({ length }, () => getRandomNumber(0, 36).toString(36)).join('');
-
-/**
- * @param {HTMLInputElement | HTMLSelectElement} element
- * @param {string} prefix
- * @returns {string}
- */
-export const generateId = (element, prefix) => {
- let id =
- element.id ||
- (element.name && `${element.name}-${generateChars(2)}`) ||
- generateChars(4);
- id = id.replace(/(:|\.|\[|\]|,)/g, '');
- id = `${prefix}-${id}`;
-
- return id;
-};
-
-/**
- * @param {any} obj
- * @returns {string}
- */
-export const getType = obj => Object.prototype.toString.call(obj).slice(8, -1);
-
-/**
- * @param {string} type
- * @param {any} obj
- * @returns {boolean}
- */
-export const isType = (type, obj) =>
- obj !== undefined && obj !== null && getType(obj) === type;
-
-/**
- * @param {HTMLElement} element
- * @param {HTMLElement} [wrapper={HTMLDivElement}]
- * @returns {HTMLElement}
- */
-export const wrap = (element, wrapper = document.createElement('div')) => {
- if (element.nextSibling) {
- element.parentNode.insertBefore(wrapper, element.nextSibling);
- } else {
- element.parentNode.appendChild(wrapper);
- }
-
- return wrapper.appendChild(element);
-};
-
-/**
- * @param {Element} startEl
- * @param {string} selector
- * @param {1 | -1} direction
- * @returns {Element | undefined}
- */
-export const getAdjacentEl = (startEl, selector, direction = 1) => {
- if (!(startEl instanceof Element) || typeof selector !== 'string') {
- return undefined;
- }
-
- const prop = `${direction > 0 ? 'next' : 'previous'}ElementSibling`;
-
- let sibling = startEl[prop];
- while (sibling) {
- if (sibling.matches(selector)) {
- return sibling;
- }
- sibling = sibling[prop];
- }
-
- return sibling;
-};
-
-/**
- * @param {Element} element
- * @param {Element} parent
- * @param {-1 | 1} direction
- * @returns {boolean}
- */
-export const isScrolledIntoView = (element, parent, direction = 1) => {
- if (!element) {
- return false;
- }
-
- let isVisible;
-
- if (direction > 0) {
- // In view from bottom
- isVisible =
- parent.scrollTop + parent.offsetHeight >=
- element.offsetTop + element.offsetHeight;
- } else {
- // In view from top
- isVisible = element.offsetTop >= parent.scrollTop;
- }
-
- return isVisible;
-};
-
-/**
- * @param {any} value
- * @returns {any}
- */
-export const sanitise = value => {
- if (typeof value !== 'string') {
- return value;
- }
-
- return value
- .replace(/&/g, '&')
- .replace(/>/g, '&rt;')
- .replace(/ (str: string) => Element}
- */
-export const strToEl = (() => {
- const tmpEl = document.createElement('div');
-
- return str => {
- const cleanedInput = str.trim();
- tmpEl.innerHTML = cleanedInput;
- const firldChild = tmpEl.children[0];
-
- while (tmpEl.firstChild) {
- tmpEl.removeChild(tmpEl.firstChild);
- }
-
- return firldChild;
- };
-})();
-
-/**
- * @param {{ label?: string, value: string }} a
- * @param {{ label?: string, value: string }} b
- * @returns {number}
- */
-export const sortByAlpha = (
- { value, label = value },
- { value: value2, label: label2 = value2 },
-) =>
- label.localeCompare(label2, [], {
- sensitivity: 'base',
- ignorePunctuation: true,
- numeric: true,
- });
-
-/**
- * @param {{ score: number }} a
- * @param {{ score: number }} b
- */
-export const sortByScore = (a, b) => a.score - b.score;
-
-/**
- * @param {HTMLElement} element
- * @param {string} type
- * @param {object} customArgs
- */
-export const dispatchEvent = (element, type, customArgs = null) => {
- const event = new CustomEvent(type, {
- detail: customArgs,
- bubbles: true,
- cancelable: true,
- });
-
- return element.dispatchEvent(event);
-};
-
-/**
- * @param {array} array
- * @param {any} value
- * @param {string} [key="value"]
- * @returns {boolean}
- */
-export const existsInArray = (array, value, key = 'value') =>
- array.some(item => {
- if (typeof value === 'string') {
- return item[key] === value.trim();
- }
-
- return item[key] === value;
- });
-
-/**
- * @param {any} obj
- * @returns {any}
- */
-export const cloneObject = obj => JSON.parse(JSON.stringify(obj));
-
-/**
- * Returns an array of keys present on the first but missing on the second object
- * @param {object} a
- * @param {object} b
- * @returns {string[]}
- */
-export const diff = (a, b) => {
- const aKeys = Object.keys(a).sort();
- const bKeys = Object.keys(b).sort();
-
- return aKeys.filter(i => bKeys.indexOf(i) < 0);
-};
diff --git a/src/scripts/lib/utils.test.js b/src/scripts/lib/utils.test.ts
similarity index 92%
rename from src/scripts/lib/utils.test.js
rename to src/scripts/lib/utils.test.ts
index 2366f5635..3cac1a122 100644
--- a/src/scripts/lib/utils.test.js
+++ b/src/scripts/lib/utils.test.ts
@@ -1,3 +1,4 @@
+/* eslint-disable no-new-wrappers */
import { expect } from 'chai';
import { stub } from 'sinon';
import {
@@ -140,19 +141,19 @@ describe('utils', () => {
it('sorts by label alphabetically', () => {
const values = [
- { label: 'The Strokes' },
- { label: 'Arctic Monkeys' },
- { label: 'Oasis' },
- { label: 'Tame Impala' },
+ { value: '0', label: 'The Strokes' },
+ { value: '0', label: 'Arctic Monkeys' },
+ { value: '0', label: 'Oasis' },
+ { value: '0', label: 'Tame Impala' },
];
const output = values.sort(sortByAlpha);
expect(output).to.eql([
- { label: 'Arctic Monkeys' },
- { label: 'Oasis' },
- { label: 'Tame Impala' },
- { label: 'The Strokes' },
+ { value: '0', label: 'Arctic Monkeys' },
+ { value: '0', label: 'Oasis' },
+ { value: '0', label: 'Tame Impala' },
+ { value: '0', label: 'The Strokes' },
]);
});
});
@@ -185,12 +186,12 @@ describe('utils', () => {
const fakeElement = {
dispatchEvent: stub(),
};
- const eventType = 'testEvent';
+ const eventType = 'addItem';
const customArgs = {
testing: true,
};
- dispatchEvent(fakeElement, eventType, customArgs);
+ dispatchEvent(fakeElement as any, eventType, customArgs);
expect(fakeElement.dispatchEvent.called).to.equal(true);
const event = fakeElement.dispatchEvent.lastCall.args[0];
diff --git a/src/scripts/lib/utils.ts b/src/scripts/lib/utils.ts
new file mode 100644
index 000000000..1508e0985
--- /dev/null
+++ b/src/scripts/lib/utils.ts
@@ -0,0 +1,180 @@
+import { EventMap, Choice } from '../interfaces';
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+export const getRandomNumber = (min: number, max: number): number =>
+ Math.floor(Math.random() * (max - min) + min);
+
+export const generateChars = (length: number): string =>
+ Array.from({ length }, () => getRandomNumber(0, 36).toString(36)).join('');
+
+export const generateId = (
+ element: HTMLInputElement | HTMLSelectElement,
+ prefix: string,
+): string => {
+ let id =
+ element.id ||
+ (element.name && `${element.name}-${generateChars(2)}`) ||
+ generateChars(4);
+ id = id.replace(/(:|\.|\[|\]|,)/g, '');
+ id = `${prefix}-${id}`;
+
+ return id;
+};
+
+export const getType = (obj: any): string =>
+ Object.prototype.toString.call(obj).slice(8, -1);
+
+export const isType = (type: string, obj: any): boolean =>
+ obj !== undefined && obj !== null && getType(obj) === type;
+
+export const wrap = (
+ element: HTMLElement,
+ wrapper: HTMLElement = document.createElement('div'),
+): HTMLElement => {
+ if (element.nextSibling) {
+ element.parentNode &&
+ element.parentNode.insertBefore(wrapper, element.nextSibling);
+ } else {
+ element.parentNode && element.parentNode.appendChild(wrapper);
+ }
+
+ return wrapper.appendChild(element);
+};
+
+export const getAdjacentEl = (
+ startEl: Element,
+ selector: string,
+ direction = 1,
+): Element => {
+ const prop = `${direction > 0 ? 'next' : 'previous'}ElementSibling`;
+
+ let sibling = startEl[prop];
+ while (sibling) {
+ if (sibling.matches(selector)) {
+ return sibling;
+ }
+ sibling = sibling[prop];
+ }
+
+ return sibling;
+};
+
+export const isScrolledIntoView = (
+ element: HTMLElement,
+ parent: HTMLElement,
+ direction = 1,
+): boolean => {
+ if (!element) {
+ return false;
+ }
+
+ let isVisible;
+
+ if (direction > 0) {
+ // In view from bottom
+ isVisible =
+ parent.scrollTop + parent.offsetHeight >=
+ element.offsetTop + element.offsetHeight;
+ } else {
+ // In view from top
+ isVisible = element.offsetTop >= parent.scrollTop;
+ }
+
+ return isVisible;
+};
+
+export const sanitise = (value: T | string): T | string => {
+ if (typeof value !== 'string') {
+ return value;
+ }
+
+ return value
+ .replace(/&/g, '&')
+ .replace(/>/g, '&rt;')
+ .replace(/ Element) => {
+ const tmpEl = document.createElement('div');
+
+ return (str): Element => {
+ const cleanedInput = str.trim();
+ tmpEl.innerHTML = cleanedInput;
+ const firldChild = tmpEl.children[0];
+
+ while (tmpEl.firstChild) {
+ tmpEl.removeChild(tmpEl.firstChild);
+ }
+
+ return firldChild;
+ };
+})();
+
+interface RecordToCompare {
+ value: string;
+ label?: string;
+}
+export const sortByAlpha = (
+ { value, label = value }: RecordToCompare,
+ { value: value2, label: label2 = value2 }: RecordToCompare,
+): number =>
+ label.localeCompare(label2, [], {
+ sensitivity: 'base',
+ ignorePunctuation: true,
+ numeric: true,
+ });
+
+export const sortByScore = (
+ a: Pick,
+ b: Pick,
+): number => {
+ const { score: scoreA = 0 } = a;
+ const { score: scoreB = 0 } = b;
+
+ return scoreA - scoreB;
+};
+
+export const dispatchEvent = (
+ element: HTMLElement,
+ type: keyof EventMap,
+ customArgs: object | null = null,
+): boolean => {
+ const event = new CustomEvent(type, {
+ detail: customArgs,
+ bubbles: true,
+ cancelable: true,
+ });
+
+ return element.dispatchEvent(event);
+};
+
+export const existsInArray = (
+ array: any[],
+ value: string,
+ key = 'value',
+): boolean =>
+ array.some(item => {
+ if (typeof value === 'string') {
+ return item[key] === value.trim();
+ }
+
+ return item[key] === value;
+ });
+
+export const cloneObject = (obj: object): object =>
+ JSON.parse(JSON.stringify(obj));
+
+/**
+ * Returns an array of keys present on the first but missing on the second object
+ */
+export const diff = (
+ a: Record,
+ b: Record,
+): string[] => {
+ const aKeys = Object.keys(a).sort();
+ const bKeys = Object.keys(b).sort();
+
+ return aKeys.filter(i => bKeys.indexOf(i) < 0);
+};
diff --git a/src/scripts/reducers/choices.js b/src/scripts/reducers/choices.js
deleted file mode 100644
index 8f1051689..000000000
--- a/src/scripts/reducers/choices.js
+++ /dev/null
@@ -1,110 +0,0 @@
-export const defaultState = [];
-
-export default function choices(state = defaultState, action) {
- switch (action.type) {
- case 'ADD_CHOICE': {
- /*
- A disabled choice appears in the choice dropdown but cannot be selected
- A selected choice has been added to the passed input's value (added as an item)
- An active choice appears within the choice dropdown
- */
- return [
- ...state,
- {
- id: action.id,
- elementId: action.elementId,
- groupId: action.groupId,
- value: action.value,
- label: action.label || action.value,
- disabled: action.disabled || false,
- selected: false,
- active: true,
- score: 9999,
- customProperties: action.customProperties,
- placeholder: action.placeholder || false,
- keyCode: null,
- },
- ];
- }
-
- case 'ADD_ITEM': {
- // If all choices need to be activated
- if (action.activateOptions) {
- return state.map(obj => {
- const choice = obj;
- choice.active = action.active;
-
- return choice;
- });
- }
-
- // When an item is added and it has an associated choice,
- // we want to disable it so it can't be chosen again
- if (action.choiceId > -1) {
- return state.map(obj => {
- const choice = obj;
- if (choice.id === parseInt(action.choiceId, 10)) {
- choice.selected = true;
- }
-
- return choice;
- });
- }
-
- return state;
- }
-
- case 'REMOVE_ITEM': {
- // When an item is removed and it has an associated choice,
- // we want to re-enable it so it can be chosen again
- if (action.choiceId > -1) {
- return state.map(obj => {
- const choice = obj;
- if (choice.id === parseInt(action.choiceId, 10)) {
- choice.selected = false;
- }
-
- return choice;
- });
- }
-
- return state;
- }
-
- case 'FILTER_CHOICES': {
- return state.map(obj => {
- const choice = obj;
- // Set active state based on whether choice is
- // within filtered results
- choice.active = action.results.some(({ item, score }) => {
- if (item.id === choice.id) {
- choice.score = score;
-
- return true;
- }
-
- return false;
- });
-
- return choice;
- });
- }
-
- case 'ACTIVATE_CHOICES': {
- return state.map(obj => {
- const choice = obj;
- choice.active = action.active;
-
- return choice;
- });
- }
-
- case 'CLEAR_CHOICES': {
- return defaultState;
- }
-
- default: {
- return state;
- }
- }
-}
diff --git a/src/scripts/reducers/choices.test.js b/src/scripts/reducers/choices.test.ts
similarity index 81%
rename from src/scripts/reducers/choices.test.js
rename to src/scripts/reducers/choices.test.ts
index 9563f6c13..a46c1ee1a 100644
--- a/src/scripts/reducers/choices.test.js
+++ b/src/scripts/reducers/choices.test.ts
@@ -1,21 +1,22 @@
import { expect } from 'chai';
import choices, { defaultState } from './choices';
+import { Choice } from '../interfaces';
describe('reducers/choices', () => {
it('should return same state when no action matches', () => {
- expect(choices(defaultState, {})).to.equal(defaultState);
+ expect(choices(defaultState, {} as any)).to.equal(defaultState);
});
describe('when choices do not exist', () => {
describe('ADD_CHOICE', () => {
const value = 'test';
const label = 'test';
- const id = 'test';
- const groupId = 'test';
+ const id = 1;
+ const groupId = 1;
const disabled = false;
- const elementId = 'test';
- const customProperties = 'test';
- const placeholder = 'test';
+ const elementId = 1;
+ const customProperties = { test: true };
+ const placeholder = true;
describe('passing expected values', () => {
it('adds choice', () => {
@@ -32,7 +33,6 @@ describe('reducers/choices', () => {
selected: false,
active: true,
score: 9999,
- keyCode: null,
},
];
@@ -68,14 +68,13 @@ describe('reducers/choices', () => {
selected: false,
active: true,
score: 9999,
- keyCode: null,
},
];
const actualResponse = choices(undefined, {
type: 'ADD_CHOICE',
value,
- label: null,
+ label: undefined,
id,
groupId,
disabled,
@@ -103,14 +102,13 @@ describe('reducers/choices', () => {
selected: false,
active: true,
score: 9999,
- keyCode: null,
},
];
const actualResponse = choices(undefined, {
type: 'ADD_CHOICE',
value,
- label: null,
+ label: undefined,
id,
groupId,
disabled,
@@ -143,7 +141,6 @@ describe('reducers/choices', () => {
score: 9999,
customProperties: null,
placeholder: false,
- keyCode: null,
},
{
id: 2,
@@ -157,7 +154,6 @@ describe('reducers/choices', () => {
score: 9999,
customProperties: null,
placeholder: false,
- keyCode: null,
},
];
});
@@ -178,9 +174,7 @@ describe('reducers/choices', () => {
type: 'FILTER_CHOICES',
results: [
{
- item: {
- id,
- },
+ item: { id } as Choice,
score,
},
],
@@ -227,45 +221,34 @@ describe('reducers/choices', () => {
});
describe('ADD_ITEM', () => {
- it('disables choice if action has choice id', () => {
- const id = 2;
- const clonedState = state.slice(0);
- const expectedResponse = [
- {
- ...state[0],
- },
- {
- ...state[1],
- selected: true,
- },
- ];
-
- const actualResponse = choices(clonedState, {
- type: 'ADD_ITEM',
- choiceId: id,
- });
+ describe('when action has a choice id', () => {
+ it('disables choice corresponding with id', () => {
+ const id = 2;
+ const clonedState = state.slice(0);
+ const expectedResponse = [
+ {
+ ...state[0],
+ },
+ {
+ ...state[1],
+ selected: true,
+ },
+ ];
- expect(actualResponse).to.eql(expectedResponse);
- });
+ const actualResponse = choices(clonedState, {
+ type: 'ADD_ITEM',
+ choiceId: id,
+ });
- it('activates all choices if activateOptions flag passed', () => {
- const clonedState = state.slice(0);
- const actualResponse = choices(clonedState, {
- type: 'ADD_ITEM',
- activateOptions: true,
- active: true,
+ expect(actualResponse).to.eql(expectedResponse);
});
-
- expect(actualResponse[0].active).to.equal(true);
- expect(actualResponse[1].active).to.equal(true);
});
- describe('neither of the above conditions are satisified', () => {
+ describe('when action has no choice id', () => {
it('returns state', () => {
const clonedState = state.slice(0);
const actualResponse = choices(clonedState, {
type: 'ADD_ITEM',
- activateOptions: false,
choiceId: undefined,
});
diff --git a/src/scripts/reducers/choices.ts b/src/scripts/reducers/choices.ts
new file mode 100644
index 000000000..bd73e1921
--- /dev/null
+++ b/src/scripts/reducers/choices.ts
@@ -0,0 +1,127 @@
+import { Choice } from '../interfaces';
+import {
+ AddChoiceAction,
+ FilterChoicesAction,
+ ActivateChoicesAction,
+ ClearChoicesAction,
+} from '../actions/choices';
+import { AddItemAction, RemoveItemAction } from '../actions/items';
+
+export const defaultState = [];
+
+type ActionTypes =
+ | AddChoiceAction
+ | FilterChoicesAction
+ | ActivateChoicesAction
+ | ClearChoicesAction
+ | AddItemAction
+ | RemoveItemAction;
+
+export default function choices(
+ state: Choice[] = defaultState,
+ action: ActionTypes,
+): Choice[] {
+ switch (action.type) {
+ case 'ADD_CHOICE': {
+ const addChoiceAction = action as AddChoiceAction;
+ const choice = {
+ id: addChoiceAction.id,
+ elementId: addChoiceAction.elementId,
+ groupId: addChoiceAction.groupId,
+ value: addChoiceAction.value,
+ label: addChoiceAction.label || addChoiceAction.value,
+ disabled: addChoiceAction.disabled || false,
+ selected: false,
+ active: true,
+ score: 9999,
+ customProperties: addChoiceAction.customProperties,
+ placeholder: addChoiceAction.placeholder || false,
+ };
+
+ /*
+ A disabled choice appears in the choice dropdown but cannot be selected
+ A selected choice has been added to the passed input's value (added as an item)
+ An active choice appears within the choice dropdown
+ */
+ return [...state, choice as Choice];
+ }
+
+ case 'ADD_ITEM': {
+ const addItemAction = action as AddItemAction;
+
+ // When an item is added and it has an associated choice,
+ // we want to disable it so it can't be chosen again
+ if (addItemAction.choiceId > -1) {
+ return state.map(obj => {
+ const choice = obj;
+ if (choice.id === parseInt(`${addItemAction.choiceId}`, 10)) {
+ choice.selected = true;
+ }
+
+ return choice;
+ });
+ }
+
+ return state;
+ }
+
+ case 'REMOVE_ITEM': {
+ const removeItemAction = action as RemoveItemAction;
+
+ // When an item is removed and it has an associated choice,
+ // we want to re-enable it so it can be chosen again
+ if (removeItemAction.choiceId && removeItemAction.choiceId > -1) {
+ return state.map(obj => {
+ const choice = obj;
+ if (choice.id === parseInt(`${removeItemAction.choiceId}`, 10)) {
+ choice.selected = false;
+ }
+
+ return choice;
+ });
+ }
+
+ return state;
+ }
+
+ case 'FILTER_CHOICES': {
+ const filterChoicesAction = action as FilterChoicesAction;
+
+ return state.map(obj => {
+ const choice = obj;
+ // Set active state based on whether choice is
+ // within filtered results
+ choice.active = filterChoicesAction.results.some(({ item, score }) => {
+ if (item.id === choice.id) {
+ choice.score = score;
+
+ return true;
+ }
+
+ return false;
+ });
+
+ return choice;
+ });
+ }
+
+ case 'ACTIVATE_CHOICES': {
+ const activateChoicesAction = action as ActivateChoicesAction;
+
+ return state.map(obj => {
+ const choice = obj;
+ choice.active = activateChoicesAction.active;
+
+ return choice;
+ });
+ }
+
+ case 'CLEAR_CHOICES': {
+ return defaultState;
+ }
+
+ default: {
+ return state;
+ }
+ }
+}
diff --git a/src/scripts/reducers/general.js b/src/scripts/reducers/general.js
deleted file mode 100644
index 2a72cb387..000000000
--- a/src/scripts/reducers/general.js
+++ /dev/null
@@ -1,19 +0,0 @@
-export const defaultState = {
- loading: false,
-};
-
-const general = (state = defaultState, action) => {
- switch (action.type) {
- case 'SET_IS_LOADING': {
- return {
- loading: action.isLoading,
- };
- }
-
- default: {
- return state;
- }
- }
-};
-
-export default general;
diff --git a/src/scripts/reducers/groups.js b/src/scripts/reducers/groups.js
deleted file mode 100644
index d704e926c..000000000
--- a/src/scripts/reducers/groups.js
+++ /dev/null
@@ -1,25 +0,0 @@
-export const defaultState = [];
-
-export default function groups(state = defaultState, action) {
- switch (action.type) {
- case 'ADD_GROUP': {
- return [
- ...state,
- {
- id: action.id,
- value: action.value,
- active: action.active,
- disabled: action.disabled,
- },
- ];
- }
-
- case 'CLEAR_CHOICES': {
- return [];
- }
-
- default: {
- return state;
- }
- }
-}
diff --git a/src/scripts/reducers/groups.test.js b/src/scripts/reducers/groups.test.ts
similarity index 94%
rename from src/scripts/reducers/groups.test.js
rename to src/scripts/reducers/groups.test.ts
index e67ee04a1..95008efb6 100644
--- a/src/scripts/reducers/groups.test.js
+++ b/src/scripts/reducers/groups.test.ts
@@ -3,13 +3,13 @@ import groups, { defaultState } from './groups';
describe('reducers/groups', () => {
it('should return same state when no action matches', () => {
- expect(groups(defaultState, {})).to.equal(defaultState);
+ expect(groups(defaultState, {} as any)).to.equal(defaultState);
});
describe('when groups do not exist', () => {
describe('ADD_GROUP', () => {
it('adds group', () => {
- const id = '1';
+ const id = 1;
const value = 'Group one';
const active = true;
const disabled = false;
diff --git a/src/scripts/reducers/groups.ts b/src/scripts/reducers/groups.ts
new file mode 100644
index 000000000..c845e9127
--- /dev/null
+++ b/src/scripts/reducers/groups.ts
@@ -0,0 +1,36 @@
+import { Group, State } from '../interfaces';
+import { AddGroupAction } from '../actions/groups';
+import { ClearChoicesAction } from '../actions/choices';
+
+export const defaultState = [];
+
+type ActionTypes = AddGroupAction | ClearChoicesAction;
+
+export default function groups(
+ state: Group[] = defaultState,
+ action: ActionTypes,
+): State['groups'] {
+ switch (action.type) {
+ case 'ADD_GROUP': {
+ const addGroupAction = action as AddGroupAction;
+
+ return [
+ ...state,
+ {
+ id: addGroupAction.id,
+ value: addGroupAction.value,
+ active: addGroupAction.active,
+ disabled: addGroupAction.disabled,
+ },
+ ];
+ }
+
+ case 'CLEAR_CHOICES': {
+ return [];
+ }
+
+ default: {
+ return state;
+ }
+ }
+}
diff --git a/src/scripts/reducers/index.test.js b/src/scripts/reducers/index.test.ts
similarity index 75%
rename from src/scripts/reducers/index.test.js
rename to src/scripts/reducers/index.test.ts
index c662cc85f..50e252cf3 100644
--- a/src/scripts/reducers/index.test.js
+++ b/src/scripts/reducers/index.test.ts
@@ -1,9 +1,10 @@
import { createStore } from 'redux';
import { expect } from 'chai';
-import rootReducer from './index';
+import rootReducer from '.';
import groups from './groups';
import choices from './choices';
import items from './items';
+import loading from './loading';
describe('reducers/rootReducer', () => {
const store = createStore(rootReducer);
@@ -11,9 +12,10 @@ describe('reducers/rootReducer', () => {
it('returns expected reducers', () => {
const state = store.getState();
- expect(state.groups).to.equal(groups(undefined, {}));
- expect(state.choices).to.equal(choices(undefined, {}));
- expect(state.items).to.equal(items(undefined, {}));
+ expect(state.groups).to.equal(groups(undefined, {} as any));
+ expect(state.choices).to.equal(choices(undefined, {} as any));
+ expect(state.items).to.equal(items(undefined, {} as any));
+ expect(state.loading).to.equal(loading(undefined, {} as any));
});
describe('CLEAR_ALL', () => {
@@ -33,9 +35,7 @@ describe('reducers/rootReducer', () => {
items: [],
groups: [],
choices: [],
- general: {
- loading: false,
- },
+ loading: false,
});
});
});
diff --git a/src/scripts/reducers/index.js b/src/scripts/reducers/index.ts
similarity index 75%
rename from src/scripts/reducers/index.js
rename to src/scripts/reducers/index.ts
index 31dc7b395..92b10e442 100644
--- a/src/scripts/reducers/index.js
+++ b/src/scripts/reducers/index.ts
@@ -2,24 +2,31 @@ import { combineReducers } from 'redux';
import items from './items';
import groups from './groups';
import choices from './choices';
-import general from './general';
+import loading from './loading';
import { cloneObject } from '../lib/utils';
+export const defaultState = {
+ groups: [],
+ items: [],
+ choices: [],
+ loading: false,
+};
+
const appReducer = combineReducers({
items,
groups,
choices,
- general,
+ loading,
});
-const rootReducer = (passedState, action) => {
+const rootReducer = (passedState, action): object => {
let state = passedState;
// If we are clearing all items, groups and options we reassign
// state and then pass that state to our proper reducer. This isn't
// mutating our actual state
// See: http://stackoverflow.com/a/35641992
if (action.type === 'CLEAR_ALL') {
- state = undefined;
+ state = defaultState;
} else if (action.type === 'RESET_TO') {
return cloneObject(action.state);
}
diff --git a/src/scripts/reducers/items.js b/src/scripts/reducers/items.js
deleted file mode 100644
index 2a520f9d2..000000000
--- a/src/scripts/reducers/items.js
+++ /dev/null
@@ -1,58 +0,0 @@
-export const defaultState = [];
-
-export default function items(state = defaultState, action) {
- switch (action.type) {
- case 'ADD_ITEM': {
- // Add object to items array
- const newState = [
- ...state,
- {
- id: action.id,
- choiceId: action.choiceId,
- groupId: action.groupId,
- value: action.value,
- label: action.label,
- active: true,
- highlighted: false,
- customProperties: action.customProperties,
- placeholder: action.placeholder || false,
- keyCode: null,
- },
- ];
-
- return newState.map(obj => {
- const item = obj;
- item.highlighted = false;
-
- return item;
- });
- }
-
- case 'REMOVE_ITEM': {
- // Set item to inactive
- return state.map(obj => {
- const item = obj;
- if (item.id === action.id) {
- item.active = false;
- }
-
- return item;
- });
- }
-
- case 'HIGHLIGHT_ITEM': {
- return state.map(obj => {
- const item = obj;
- if (item.id === action.id) {
- item.highlighted = action.highlighted;
- }
-
- return item;
- });
- }
-
- default: {
- return state;
- }
- }
-}
diff --git a/src/scripts/reducers/items.test.js b/src/scripts/reducers/items.test.ts
similarity index 95%
rename from src/scripts/reducers/items.test.js
rename to src/scripts/reducers/items.test.ts
index 4041a3b3e..0a7262f32 100644
--- a/src/scripts/reducers/items.test.js
+++ b/src/scripts/reducers/items.test.ts
@@ -1,9 +1,10 @@
import { expect } from 'chai';
import items, { defaultState } from './items';
+import { RemoveItemAction } from '../actions/items';
describe('reducers/items', () => {
it('should return same state when no action matches', () => {
- expect(items(defaultState, {})).to.equal(defaultState);
+ expect(items(defaultState, {} as any)).to.equal(defaultState);
});
describe('when items do not exist', () => {
@@ -16,7 +17,7 @@ describe('reducers/items', () => {
const customProperties = {
property: 'value',
};
- const placeholder = 'This is a placeholder';
+ const placeholder = true;
const keyCode = 10;
describe('passing expected values', () => {
@@ -148,7 +149,7 @@ describe('reducers/items', () => {
const actualResponse = items(clonedState, {
type: 'REMOVE_ITEM',
id,
- });
+ } as RemoveItemAction);
expect(actualResponse).to.eql(expectedResponse);
});
diff --git a/src/scripts/reducers/items.ts b/src/scripts/reducers/items.ts
new file mode 100644
index 000000000..fb8432ace
--- /dev/null
+++ b/src/scripts/reducers/items.ts
@@ -0,0 +1,73 @@
+import { Item, State } from '../interfaces';
+import {
+ AddItemAction,
+ RemoveItemAction,
+ HighlightItemAction,
+} from '../actions/items';
+
+export const defaultState = [];
+
+type ActionTypes = AddItemAction | RemoveItemAction | HighlightItemAction;
+
+export default function items(
+ state: Item[] = defaultState,
+ action: ActionTypes,
+): State['items'] {
+ switch (action.type) {
+ case 'ADD_ITEM': {
+ const addItemAction = action as AddItemAction;
+ // Add object to items array
+ const newState = [
+ ...state,
+ {
+ id: addItemAction.id,
+ choiceId: addItemAction.choiceId,
+ groupId: addItemAction.groupId,
+ value: addItemAction.value,
+ label: addItemAction.label,
+ active: true,
+ highlighted: false,
+ customProperties: addItemAction.customProperties,
+ placeholder: addItemAction.placeholder || false,
+ keyCode: null,
+ },
+ ];
+
+ return newState.map((obj: Item) => {
+ const item = obj;
+ item.highlighted = false;
+
+ return item;
+ });
+ }
+
+ case 'REMOVE_ITEM': {
+ // Set item to inactive
+ return state.map(obj => {
+ const item = obj;
+ if (item.id === action.id) {
+ item.active = false;
+ }
+
+ return item;
+ });
+ }
+
+ case 'HIGHLIGHT_ITEM': {
+ const highlightItemAction = action as HighlightItemAction;
+
+ return state.map(obj => {
+ const item = obj;
+ if (item.id === highlightItemAction.id) {
+ item.highlighted = highlightItemAction.highlighted;
+ }
+
+ return item;
+ });
+ }
+
+ default: {
+ return state;
+ }
+ }
+}
diff --git a/src/scripts/reducers/general.test.js b/src/scripts/reducers/loading.test.ts
similarity index 62%
rename from src/scripts/reducers/general.test.js
rename to src/scripts/reducers/loading.test.ts
index 01203dcc4..cbf9c4bf0 100644
--- a/src/scripts/reducers/general.test.js
+++ b/src/scripts/reducers/loading.test.ts
@@ -1,16 +1,14 @@
import { expect } from 'chai';
-import general, { defaultState } from './general';
+import general, { defaultState } from './loading';
-describe('reducers/general', () => {
+describe('reducers/loading', () => {
it('should return same state when no action matches', () => {
- expect(general(defaultState, {})).to.equal(defaultState);
+ expect(general(defaultState, {} as any)).to.equal(defaultState);
});
describe('SET_IS_LOADING', () => {
it('sets loading state', () => {
- const expectedState = {
- loading: true,
- };
+ const expectedState = true;
const actualState = general(undefined, {
type: 'SET_IS_LOADING',
diff --git a/src/scripts/reducers/loading.ts b/src/scripts/reducers/loading.ts
new file mode 100644
index 000000000..58f6469ac
--- /dev/null
+++ b/src/scripts/reducers/loading.ts
@@ -0,0 +1,23 @@
+import { SetIsLoadingAction } from '../actions/misc';
+import { State } from '../interfaces';
+
+export const defaultState = false;
+
+type ActionTypes = SetIsLoadingAction;
+
+const general = (
+ state = defaultState,
+ action: ActionTypes,
+): State['loading'] => {
+ switch (action.type) {
+ case 'SET_IS_LOADING': {
+ return action.isLoading;
+ }
+
+ default: {
+ return state;
+ }
+ }
+};
+
+export default general;
diff --git a/src/scripts/store/store.test.js b/src/scripts/store/store.test.ts
similarity index 99%
rename from src/scripts/store/store.test.js
rename to src/scripts/store/store.test.ts
index 63ebcc556..44fcaacf4 100644
--- a/src/scripts/store/store.test.js
+++ b/src/scripts/store/store.test.ts
@@ -33,7 +33,7 @@ describe('reducers/store', () => {
describe('subscribe', () => {
it('wraps redux subscribe method', () => {
- const onChange = () => {};
+ const onChange = (): void => {};
expect(subscribeStub.callCount).to.equal(0);
instance.subscribe(onChange);
expect(subscribeStub.callCount).to.equal(1);
diff --git a/src/scripts/store/store.js b/src/scripts/store/store.ts
similarity index 58%
rename from src/scripts/store/store.js
rename to src/scripts/store/store.ts
index 4fb7888ab..cffbf5196 100644
--- a/src/scripts/store/store.js
+++ b/src/scripts/store/store.ts
@@ -1,108 +1,93 @@
-import { createStore } from 'redux';
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { createStore, Store as IStore, AnyAction } from 'redux';
import rootReducer from '../reducers/index';
-
-/**
- * @typedef {import('../../../types/index').Choices.Choice} Choice
- * @typedef {import('../../../types/index').Choices.Group} Group
- * @typedef {import('../../../types/index').Choices.Item} Item
- */
+import { Choice, Group, Item, State } from '../interfaces';
export default class Store {
+ _store: IStore;
+
constructor() {
this._store = createStore(
rootReducer,
- window.__REDUX_DEVTOOLS_EXTENSION__ &&
- window.__REDUX_DEVTOOLS_EXTENSION__(),
+ (window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
+ (window as any).__REDUX_DEVTOOLS_EXTENSION__(),
);
}
/**
* Subscribe store to function call (wrapped Redux method)
- * @param {Function} onChange Function to trigger when state changes
- * @return
*/
- subscribe(onChange) {
+ subscribe(onChange: () => void): void {
this._store.subscribe(onChange);
}
/**
* Dispatch event to store (wrapped Redux method)
- * @param {{ type: string, [x: string]: any }} action Action to trigger
- * @return
*/
- dispatch(action) {
+ dispatch(action: AnyAction): void {
this._store.dispatch(action);
}
/**
* Get store object (wrapping Redux method)
- * @returns {object} State
*/
- get state() {
+ get state(): State {
return this._store.getState();
}
/**
* Get items from store
- * @returns {Item[]} Item objects
*/
- get items() {
+ get items(): Item[] {
return this.state.items;
}
/**
* Get active items from store
- * @returns {Item[]} Item objects
*/
- get activeItems() {
+ get activeItems(): Item[] {
return this.items.filter(item => item.active === true);
}
/**
* Get highlighted items from store
- * @returns {Item[]} Item objects
*/
- get highlightedActiveItems() {
+ get highlightedActiveItems(): Item[] {
return this.items.filter(item => item.active && item.highlighted);
}
/**
* Get choices from store
- * @returns {Choice[]} Option objects
*/
- get choices() {
+ get choices(): Choice[] {
return this.state.choices;
}
/**
* Get active choices from store
- * @returns {Choice[]} Option objects
*/
- get activeChoices() {
+ get activeChoices(): Choice[] {
return this.choices.filter(choice => choice.active === true);
}
/**
* Get selectable choices from store
- * @returns {Choice[]} Option objects
*/
- get selectableChoices() {
+ get selectableChoices(): Choice[] {
return this.choices.filter(choice => choice.disabled !== true);
}
/**
* Get choices that can be searched (excluding placeholders)
- * @returns {Choice[]} Option objects
*/
- get searchableChoices() {
+ get searchableChoices(): Choice[] {
return this.selectableChoices.filter(choice => choice.placeholder !== true);
}
/**
* Get placeholder choice from store
- * @returns {Choice | undefined} Found placeholder
*/
- get placeholderChoice() {
+ get placeholderChoice(): Choice | undefined {
return [...this.choices]
.reverse()
.find(choice => choice.placeholder === true);
@@ -110,17 +95,15 @@ export default class Store {
/**
* Get groups from store
- * @returns {Group[]} Group objects
*/
- get groups() {
+ get groups(): Group[] {
return this.state.groups;
}
/**
* Get active groups from store
- * @returns {Group[]} Group objects
*/
- get activeGroups() {
+ get activeGroups(): Group[] {
const { groups, choices } = this;
return groups.filter(group => {
@@ -135,27 +118,22 @@ export default class Store {
/**
* Get loading state from store
- * @returns {boolean} Loading State
*/
- isLoading() {
- return this.state.general.loading;
+ isLoading(): boolean {
+ return this.state.loading;
}
/**
* Get single choice by it's ID
- * @param {string} id
- * @returns {Choice | undefined} Found choice
*/
- getChoiceById(id) {
+ getChoiceById(id: string): Choice | undefined {
return this.activeChoices.find(choice => choice.id === parseInt(id, 10));
}
/**
* Get group by group id
- * @param {number} id Group ID
- * @returns {Group | undefined} Group data
*/
- getGroupById(id) {
+ getGroupById(id: number): Group | undefined {
return this.groups.find(group => group.id === id);
}
}
diff --git a/src/scripts/templates.test.js b/src/scripts/templates.test.ts
similarity index 99%
rename from src/scripts/templates.test.js
rename to src/scripts/templates.test.ts
index 2db8ed830..363cfa798 100644
--- a/src/scripts/templates.test.js
+++ b/src/scripts/templates.test.ts
@@ -3,11 +3,10 @@ import templates from './templates';
import { strToEl } from './lib/utils';
/**
- *
* @param {HTMLElement} element1
* @param {HTMLElement} element2
*/
-function expectEqualElements(element1, element2) {
+function expectEqualElements(element1, element2): void {
expect(element1.tagName).to.equal(element2.tagName);
expect(element1.attributes.length).to.equal(element2.attributes.length);
expect(Object.keys(element1.dataset)).to.have.members(
@@ -516,11 +515,10 @@ describe('templates', () => {
};
it('returns expected html', () => {
- const value = 'test';
const expectedOutput = strToEl(
``,
);
- const actualOutput = templates.dropdown(classes, value);
+ const actualOutput = templates.dropdown(classes);
expectEqualElements(actualOutput, expectedOutput);
});
diff --git a/src/scripts/templates.js b/src/scripts/templates.ts
similarity index 65%
rename from src/scripts/templates.js
rename to src/scripts/templates.ts
index eb4f2eadb..cb569210e 100644
--- a/src/scripts/templates.js
+++ b/src/scripts/templates.ts
@@ -1,31 +1,19 @@
+import { ClassNames, Item, Choice, Group, PassedElement } from './interfaces';
+
/**
* Helpers to create HTML elements used by Choices
* Can be overridden by providing `callbackOnCreateTemplates` option
- * @typedef {import('../../types/index').Choices.Templates} Templates
- * @typedef {import('../../types/index').Choices.ClassNames} ClassNames
- * @typedef {import('../../types/index').Choices.Options} Options
- * @typedef {import('../../types/index').Choices.Item} Item
- * @typedef {import('../../types/index').Choices.Choice} Choice
- * @typedef {import('../../types/index').Choices.Group} Group
*/
-export const TEMPLATES = /** @type {Templates} */ ({
- /**
- * @param {Partial} classNames
- * @param {"ltr" | "rtl" | "auto"} dir
- * @param {boolean} isSelectElement
- * @param {boolean} isSelectOneElement
- * @param {boolean} searchEnabled
- * @param {"select-one" | "select-multiple" | "text"} passedElementType
- */
+const templates = {
containerOuter(
- { containerOuter },
- dir,
- isSelectElement,
- isSelectOneElement,
- searchEnabled,
- passedElementType,
- ) {
+ { containerOuter }: Pick,
+ dir: HTMLElement['dir'],
+ isSelectElement: boolean,
+ isSelectOneElement: boolean,
+ searchEnabled: boolean,
+ passedElementType: PassedElement['type'],
+ ): HTMLDivElement {
const div = Object.assign(document.createElement('div'), {
className: containerOuter,
});
@@ -53,43 +41,48 @@ export const TEMPLATES = /** @type {Templates} */ ({
return div;
},
- /**
- * @param {Partial} classNames
- */
- containerInner({ containerInner }) {
+ containerInner({
+ containerInner,
+ }: Pick): HTMLDivElement {
return Object.assign(document.createElement('div'), {
className: containerInner,
});
},
- /**
- * @param {Partial} classNames
- * @param {boolean} isSelectOneElement
- */
- itemList({ list, listSingle, listItems }, isSelectOneElement) {
+ itemList(
+ {
+ list,
+ listSingle,
+ listItems,
+ }: Pick,
+ isSelectOneElement: boolean,
+ ): HTMLDivElement {
return Object.assign(document.createElement('div'), {
className: `${list} ${isSelectOneElement ? listSingle : listItems}`,
});
},
- /**
- * @param {Partial} classNames
- * @param {string} value
- */
- placeholder({ placeholder }, value) {
+ placeholder(
+ { placeholder }: Pick,
+ value: string,
+ ): HTMLDivElement {
return Object.assign(document.createElement('div'), {
className: placeholder,
innerHTML: value,
});
},
- /**
- * @param {Partial} classNames
- * @param {Item} item
- * @param {boolean} removeItemButton
- */
item(
- { item, button, highlightedState, itemSelectable, placeholder },
+ {
+ item,
+ button,
+ highlightedState,
+ itemSelectable,
+ placeholder,
+ }: Pick<
+ ClassNames,
+ 'item' | 'button' | 'highlightedState' | 'itemSelectable' | 'placeholder'
+ >,
{
id,
value,
@@ -99,9 +92,9 @@ export const TEMPLATES = /** @type {Templates} */ ({
disabled,
highlighted,
placeholder: isPlaceholder,
- },
- removeItemButton,
- ) {
+ }: Item,
+ removeItemButton: boolean,
+ ): HTMLDivElement {
const div = Object.assign(document.createElement('div'), {
className: item,
innerHTML: label,
@@ -151,11 +144,10 @@ export const TEMPLATES = /** @type {Templates} */ ({
return div;
},
- /**
- * @param {Partial} classNames
- * @param {boolean} isSelectOneElement
- */
- choiceList({ list }, isSelectOneElement) {
+ choiceList(
+ { list }: Pick,
+ isSelectOneElement: boolean,
+ ): HTMLDivElement {
const div = Object.assign(document.createElement('div'), {
className: list,
});
@@ -168,11 +160,14 @@ export const TEMPLATES = /** @type {Templates} */ ({
return div;
},
- /**
- * @param {Partial} classNames
- * @param {Group} group
- */
- choiceGroup({ group, groupHeading, itemDisabled }, { id, value, disabled }) {
+ choiceGroup(
+ {
+ group,
+ groupHeading,
+ itemDisabled,
+ }: Pick,
+ { id, value, disabled }: Group,
+ ): HTMLDivElement {
const div = Object.assign(document.createElement('div'), {
className: `${group} ${disabled ? itemDisabled : ''}`,
});
@@ -199,11 +194,6 @@ export const TEMPLATES = /** @type {Templates} */ ({
return div;
},
- /**
- * @param {Partial} classNames
- * @param {Choice} choice
- * @param {Options['itemSelectText']} selectText
- */
choice(
{
item,
@@ -212,7 +202,15 @@ export const TEMPLATES = /** @type {Templates} */ ({
selectedState,
itemDisabled,
placeholder,
- },
+ }: Pick<
+ ClassNames,
+ | 'item'
+ | 'itemChoice'
+ | 'itemSelectable'
+ | 'selectedState'
+ | 'itemDisabled'
+ | 'placeholder'
+ >,
{
id,
value,
@@ -222,9 +220,9 @@ export const TEMPLATES = /** @type {Templates} */ ({
disabled: isDisabled,
selected: isSelected,
placeholder: isPlaceholder,
- },
- selectText,
- ) {
+ }: Choice,
+ selectText: string,
+ ): HTMLDivElement {
const div = Object.assign(document.createElement('div'), {
id: elementId,
innerHTML: label,
@@ -239,7 +237,7 @@ export const TEMPLATES = /** @type {Templates} */ ({
div.classList.add(placeholder);
}
- div.setAttribute('role', groupId > 0 ? 'treeitem' : 'option');
+ div.setAttribute('role', groupId && groupId > 0 ? 'treeitem' : 'option');
Object.assign(div.dataset, {
choice: '',
@@ -260,11 +258,10 @@ export const TEMPLATES = /** @type {Templates} */ ({
return div;
},
- /**
- * @param {Partial} classNames
- * @param {string} placeholderValue
- */
- input({ input, inputCloned }, placeholderValue) {
+ input(
+ { input, inputCloned }: Pick,
+ placeholderValue: string,
+ ): HTMLInputElement {
const inp = Object.assign(document.createElement('input'), {
type: 'text',
className: `${input} ${inputCloned}`,
@@ -280,10 +277,10 @@ export const TEMPLATES = /** @type {Templates} */ ({
return inp;
},
- /**
- * @param {Partial} classNames
- */
- dropdown({ list, listDropdown }) {
+ dropdown({
+ list,
+ listDropdown,
+ }: Pick): HTMLDivElement {
const div = document.createElement('div');
div.classList.add(list, listDropdown);
@@ -292,13 +289,16 @@ export const TEMPLATES = /** @type {Templates} */ ({
return div;
},
- /**
- *
- * @param {Partial} classNames
- * @param {string} innerHTML
- * @param {"no-choices" | "no-results" | ""} type
- */
- notice({ item, itemChoice, noResults, noChoices }, innerHTML, type = '') {
+ notice(
+ {
+ item,
+ itemChoice,
+ noResults,
+ noChoices,
+ }: Pick,
+ innerHTML: string,
+ type: 'no-choices' | 'no-results' | '' = '',
+ ): HTMLDivElement {
const classes = [item, itemChoice];
if (type === 'no-choices') {
@@ -313,19 +313,23 @@ export const TEMPLATES = /** @type {Templates} */ ({
});
},
- /**
- * @param {Item} option
- */
- option({ label, value, customProperties, active, disabled }) {
+ option({
+ label,
+ value,
+ customProperties,
+ active,
+ disabled,
+ }: Item): HTMLOptionElement {
const opt = new Option(label, value, false, active);
if (customProperties) {
- opt.dataset.customProperties = customProperties;
+ opt.dataset.customProperties = `${customProperties}`;
}
- opt.disabled = disabled;
+
+ opt.disabled = !!disabled;
return opt;
},
-});
+};
-export default TEMPLATES;
+export default templates;
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 000000000..fa1641323
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "baseUrl": "/",
+ "outDir": "./dist/",
+ "allowJs": true,
+ "sourceMap": true,
+ "module": "commonjs",
+ "esModuleInterop": true,
+ "target": "es5",
+ "lib": ["es2017", "dom"],
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noImplicitAny": false,
+ "strictNullChecks": true,
+ "types": ["cypress"]
+ },
+ "include": ["./src/**/*", "./cypress/**/*"]
+}
diff --git a/types/index.d.ts b/types/index.d.ts
deleted file mode 100644
index d3520bdfd..000000000
--- a/types/index.d.ts
+++ /dev/null
@@ -1,1041 +0,0 @@
-// Type definitions for Choices.js
-// Project: https://github.com/jshjohnson/Choices
-// Definitions by:
-// Arthur vasconcelos ,
-// Josh Johnson ,
-// Zack Schuster
-// Konstantin Vyatkin
-// Definitions: https://github.com/jshjohnson/Choices
-
-import { FuseOptions } from 'fuse.js';
-
-// Choices Namespace
-declare namespace Choices {
- namespace Types {
- type strToEl = (
- str: string,
- ) => HTMLElement | HTMLInputElement | HTMLOptionElement;
- type stringFunction = () => string;
- type noticeStringFunction = (value: string) => string;
- type noticeLimitFunction = (maxItemCount: number) => string;
- type filterFunction = (value: string) => boolean;
- type valueCompareFunction = (value1: string, value2: string) => boolean;
- }
-
- interface Choice {
- id?: number;
- customProperties?: Record;
- disabled?: boolean;
- active?: boolean;
- elementId?: string;
- groupId?: number;
- keyCode?: number;
- label: string;
- placeholder?: boolean;
- selected?: boolean;
- value: string;
- }
-
- interface Group {
- id?: number;
- active?: boolean;
- disabled?: boolean;
- value: any;
- }
-
- interface Item extends Choice {
- choiceId?: number;
- keyCode?: number;
- highlighted?: boolean;
- }
-
- /**
- * Events fired by Choices behave the same as standard events. Each event is triggered on the element passed to Choices (accessible via `this.passedElement`. Arguments are accessible within the `event.detail` object.
- */
- interface EventMap {
- /**
- * Triggered each time an item is added (programmatically or by the user).
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * Arguments: id, value, label, groupValue, keyCode
- */
- addItem: CustomEvent<{
- id: number;
- value: string;
- label: string;
- groupValue: string;
- keyCode: number;
- }>;
-
- /**
- * Triggered each time an item is removed (programmatically or by the user).
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * Arguments: id, value, label, groupValue
- */
- removeItem: CustomEvent<{
- id: number;
- value: string;
- label: string;
- groupValue: string;
- }>;
-
- /**
- * Triggered each time an item is highlighted.
- *
- * **Input types affected:** text, select-multiple
- *
- * Arguments: id, value, label, groupValue
- */
- highlightItem: CustomEvent<{
- id: number;
- value: string;
- label: string;
- groupValue: string;
- }>;
-
- /**
- * Triggered each time an item is unhighlighted.
- *
- * **Input types affected:** text, select-multiple
- *
- * Arguments: id, value, label, groupValue
- */
- unhighlightItem: CustomEvent<{
- id: number;
- value: string;
- label: string;
- groupValue: string;
- }>;
-
- /**
- * Triggered each time a choice is selected **by a user**, regardless if it changes the value of the input.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * Arguments: choice: Choice
- */
- choice: CustomEvent<{ choice: Choices.Choice }>;
-
- /**
- * Triggered each time an item is added/removed **by a user**.
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * Arguments: value
- */
- change: CustomEvent<{ value: string }>;
-
- /**
- * Triggered when a user types into an input to search choices.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * Arguments: value, resultCount
- */
- search: CustomEvent<{ value: string; resultCount: number }>;
-
- /**
- * Triggered when the dropdown is shown.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * Arguments: -
- */
- showDropdown: CustomEvent;
-
- /**
- * Triggered when the dropdown is hidden.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * Arguments: -
- */
- hideDropdown: CustomEvent;
-
- /**
- * Triggered when a choice from the dropdown is highlighted.
- *
- * Input types affected: select-one, select-multiple
- * Arguments: el is the choice.passedElement that was affected.
- */
- highlightChoice: CustomEvent<{ el: Choices.passedElement }>;
- }
-
- interface Templates {
- containerOuter: (
- this: Choices,
- classNames: ClassNames,
- direction: HTMLElement['dir'],
- isSelectElement: boolean,
- isSelectOneElement: boolean,
- searchEnabled: boolean,
- passedElementType: passedElement['type'],
- ) => HTMLElement;
- containerInner: (this: Choices, classNames: ClassNames) => HTMLElement;
- itemList: (
- this: Choices,
- classNames: ClassNames,
- isSelectOneElement: boolean,
- ) => HTMLElement;
- placeholder: (
- this: Choices,
- classNames: ClassNames,
- value: string,
- ) => HTMLElement;
- item: (
- this: Choices,
- classNames: ClassNames,
- data: Choice,
- removeItemButton: boolean,
- ) => HTMLElement;
- choiceList: (
- this: Choices,
- classNames: ClassNames,
- isSelectOneElement: boolean,
- ) => HTMLElement;
- choiceGroup: (
- this: Choices,
- classNames: ClassNames,
- data: Choice,
- ) => HTMLElement;
- choice: (
- this: Choices,
- classNames: ClassNames,
- data: Choice,
- selectText: string,
- ) => HTMLElement;
- input: (
- this: Choices,
- classNames: ClassNames,
- placeholderValue: string,
- ) => HTMLInputElement;
- dropdown: (this: Choices, classNames: ClassNames) => HTMLElement;
- notice: (
- this: Choices,
- classNames: ClassNames,
- label: string,
- type: '' | 'no-results' | 'no-choices',
- ) => HTMLElement;
- option: (data: Choice) => HTMLOptionElement;
- }
-
- /** Classes added to HTML generated by Choices. By default classnames follow the BEM notation. */
- interface ClassNames {
- /** @default 'choices' */
- containerOuter: string;
- /** @default 'choices__inner' */
- containerInner: string;
- /** @default 'choices__input' */
- input: string;
- /** @default 'choices__input--cloned' */
- inputCloned: string;
- /** @default 'choices__list' */
- list: string;
- /** @default 'choices__list--multiple' */
- listItems: string;
- /** @default 'choices__list--single' */
- listSingle: string;
- /** @default 'choices__list--dropdown' */
- listDropdown: string;
- /** @default 'choices__item' */
- item: string;
- /** @default 'choices__item--selectable' */
- itemSelectable: string;
- /** @default 'choices__item--disabled' */
- itemDisabled: string;
- /** @default 'choices__item--choice' */
- itemChoice: string;
- /** @default 'choices__placeholder' */
- placeholder: string;
- /** @default 'choices__group' */
- group: string;
- /** @default 'choices__heading' */
- groupHeading: string;
- /** @default 'choices__button' */
- button: string;
- /** @default 'is-active' */
- activeState: string;
- /** @default 'is-focused' */
- focusState: string;
- /** @default 'is-open' */
- openState: string;
- /** @default 'is-disabled' */
- disabledState: string;
- /** @default 'is-highlighted' */
- highlightedState: string;
- /** @default 'is-selected' */
- selectedState: string;
- /** @default 'is-flipped' */
- flippedState: string;
- /** @default 'is-loading' */
- loadingState: string;
- /** @default 'has-no-results' */
- noResults: string;
- /** @default 'has-no-choices' */
- noChoices: string;
- }
-
- interface passedElement {
- classNames: Choices.ClassNames;
- element: (HTMLInputElement | HTMLSelectElement) & {
- // Extends HTMLElement addEventListener with Choices events
- addEventListener(
- type: K,
- listener: (
- this: HTMLInputElement | HTMLSelectElement,
- ev: Choices.EventMap[K],
- ) => void,
- options?: boolean | AddEventListenerOptions,
- ): void;
- };
- type: 'text' | 'select-one' | 'select-multiple';
- isDisabled: boolean;
- parentInstance: Choices;
- }
-
- /**
- * Choices options interface
- *
- * **Terminology**
- *
- * - **Choice:** A choice is a value a user can select. A choice would be equivalent to the `` element within a select input.
- * - **Group:** A group is a collection of choices. A group should be seen as equivalent to a `` element within a select input.
- * - **Item:** An item is an inputted value **_(text input)_** or a selected choice **_(select element)_**. In the context of a select element, an item is equivelent to a selected option element: `` whereas in the context of a text input an item is equivelant to ``
- */
- interface Options {
- /**
- * Optionally suppress console errors and warnings.
- *
- * **Input types affected:** text, select-single, select-multiple
- *
- * @default false
- */
- silent: boolean;
-
- /**
- * Add pre-selected items (see terminology) to text input.
- *
- * **Input types affected:** text
- *
- * @example
- * ```
- * ['value 1', 'value 2', 'value 3']
- * ```
- *
- * @example
- * ```
- * [{
- * value: 'Value 1',
- * label: 'Label 1',
- * id: 1
- * },
- * {
- * value: 'Value 2',
- * label: 'Label 2',
- * id: 2,
- * customProperties: {
- * random: 'I am a custom property'
- * }
- * }]
- * ```
- *
- * @default []
- */
- items: string[] | Choice[];
-
- /**
- * Add choices (see terminology) to select input.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @example
- * ```
- * [{
- * value: 'Option 1',
- * label: 'Option 1',
- * selected: true,
- * disabled: false,
- * },
- * {
- * value: 'Option 2',
- * label: 'Option 2',
- * selected: false,
- * disabled: true,
- * customProperties: {
- * description: 'Custom description about Option 2',
- * random: 'Another random custom property'
- * },
- * }]
- * ```
- *
- * @default []
- */
- choices: Choice[];
-
- /**
- * The amount of choices to be rendered within the dropdown list `("-1" indicates no limit)`. This is useful if you have a lot of choices where it is easier for a user to use the search area to find a choice.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default -1
- */
- renderChoiceLimit: number;
-
- /**
- * The amount of items a user can input/select `("-1" indicates no limit)`.
- *
- * **Input types affected:** text, select-multiple
- *
- * @default -1
- */
- maxItemCount: number;
-
- /**
- * Whether a user can add items.
- *
- * **Input types affected:** text
- *
- * @default true
- */
- addItems: boolean;
-
- /**
- * A filter that will need to pass for a user to successfully add an item.
- *
- * **Input types affected:** text
- *
- * @default null
- */
- addItemFilter: string | RegExp | Choices.Types.filterFunction | null;
-
- /**
- * The text that is shown when a user has inputted a new item but has not pressed the enter key. To access the current input value, pass a function with a `value` argument (see the **default config** [https://github.com/jshjohnson/Choices#setup] for an example), otherwise pass a string.
- *
- * **Input types affected:** text
- *
- * @default
- * ```
- * (value) => `Press Enter to add "${value}"`;
- * ```
- */
- addItemText: string | Choices.Types.noticeStringFunction;
-
- /**
- * Whether a user can remove items.
- *
- * **Input types affected:** text, select-multiple
- *
- * @default true
- */
- removeItems: boolean;
-
- /**
- * Whether each item should have a remove button.
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * @default false
- */
- removeItemButton: boolean;
-
- /**
- * Whether a user can edit items. An item's value can be edited by pressing the backspace.
- *
- * **Input types affected:** text
- *
- * @default false
- */
- editItems: boolean;
-
- /**
- * Whether each inputted/chosen item should be unique.
- *
- * **Input types affected:** text, select-multiple
- *
- * @default true
- */
- duplicateItemsAllowed: boolean;
-
- /**
- * What divides each value. The default delimiter separates each value with a comma: `"Value 1, Value 2, Value 3"`.
- *
- * **Input types affected:** text
- *
- * @default ','
- */
- delimiter: string;
-
- /**
- * Whether a user can paste into the input.
- *
- * **Input types affected:** text, select-multiple
- *
- * @default true
- */
- paste: boolean;
-
- /**
- * Whether a search area should be shown.
- *
- * @note Multiple select boxes will always show search areas.
- *
- * **Input types affected:** select-one
- *
- * @default true
- */
- searchEnabled: boolean;
-
- /**
- * Whether choices should be filtered by input or not. If `false`, the search event will still emit, but choices will not be filtered.
- *
- * **Input types affected:** select-one
- *
- * @default true
- */
- searchChoices: boolean;
-
- /**
- * The minimum length a search value should be before choices are searched.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default 1
- */
- searchFloor: number;
-
- /**
- * The maximum amount of search results to show.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default 4
- */
- searchResultLimit: number;
-
- /**
- * Specify which fields should be used when a user is searching. If you have added custom properties to your choices, you can add these values thus: `['label', 'value', 'customProperties.example']`.
- *
- * Input types affected:select-one, select-multiple
- *
- * @default ['label', 'value']
- */
- searchFields: string[];
-
- /**
- * Whether the dropdown should appear above `(top)` or below `(bottom)` the input. By default, if there is not enough space within the window the dropdown will appear above the input, otherwise below it.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default 'auto'
- */
- position: 'auto' | 'top';
-
- /**
- * Whether the scroll position should reset after adding an item.
- *
- * **Input types affected:** select-multiple
- *
- * @default true
- */
- resetScrollPosition: boolean;
-
- /**
- * Whether choices and groups should be sorted. If false, choices/groups will appear in the order they were given.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default true
- */
- shouldSort: boolean;
-
- /**
- * Whether items should be sorted. If false, items will appear in the order they were selected.
- *
- * **Input types affected:** text, select-multiple
- *
- * @default false
- */
- shouldSortItems: boolean;
-
- /**
- * The function that will sort choices and items before they are displayed (unless a user is searching). By default choices and items are sorted by alphabetical order.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @example
- * ```
- * // Sorting via length of label from largest to smallest
- * const example = new Choices(element, {
- * sorter: function(a, b) {
- * return b.label.length - a.label.length;
- * },
- * };
- * ```
- *
- * @default sortByAlpha
- */
- sorter: (current: Choice, next: Choice) => number;
-
- /**
- * Whether the input should show a placeholder. Used in conjunction with `placeholderValue`. If `placeholder` is set to true and no value is passed to `placeholderValue`, the passed input's placeholder attribute will be used as the placeholder value.
- *
- * **Input types affected:** text, select-multiple
- *
- * @note For single select boxes, the recommended way of adding a placeholder is as follows:
- * ```
- *
- * ```
- *
- * @default true
- */
- placeholder: boolean;
-
- /**
- * The value of the inputs placeholder.
- *
- * **Input types affected:** text, select-multiple
- *
- * @default null
- */
- placeholderValue: string | null;
-
- /**
- * The value of the search inputs placeholder.
- *
- * **Input types affected:** select-one
- *
- * @default null
- */
- searchPlaceholderValue: string | null;
-
- /**
- * Prepend a value to each item added/selected.
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * @default null
- */
- prependValue: string | null;
-
- /**
- * Append a value to each item added/selected.
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * @default null
- */
- appendValue: string | null;
-
- /**
- * Whether selected choices should be removed from the list. By default choices are removed when they are selected in multiple select box. To always render choices pass `always`.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default 'auto';
- */
- renderSelectedChoices: 'auto' | 'always';
-
- /**
- * The text that is shown whilst choices are being populated via AJAX.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default 'Loading...'
- */
- loadingText: string;
-
- /**
- * The text that is shown when a user's search has returned no results. Optionally pass a function returning a string.
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default 'No results found'
- */
- noResultsText: string | Choices.Types.stringFunction;
-
- /**
- * The text that is shown when a user has selected all possible choices. Optionally pass a function returning a string.
- *
- * **Input types affected:** select-multiple
- *
- * @default 'No choices to choose from'
- */
- noChoicesText: string | Choices.Types.stringFunction;
-
- /**
- * The text that is shown when a user hovers over a selectable choice.
- *
- * **Input types affected:** select-multiple, select-one
- *
- * @default 'Press to select'
- */
- itemSelectText: string;
-
- /**
- * The text that is shown when a user has focus on the input but has already reached the **max item count** [https://github.com/jshjohnson/Choices#maxitemcount]. To access the max item count, pass a function with a `maxItemCount` argument (see the **default config** [https://github.com/jshjohnson/Choices#setup] for an example), otherwise pass a string.
- *
- * **Input types affected:** text
- *
- * @default
- * ```
- * (maxItemCount) => `Only ${maxItemCount} values can be added.`;
- * ```
- */
- maxItemText: string | Choices.Types.noticeLimitFunction;
-
- /**
- * If no duplicates are allowed, and the value already exists in the array.
- *
- * @default 'Only unique values can be added'
- */
- uniqueItemText: string | Choices.Types.noticeStringFunction;
-
- /**
- * The text that is shown when addItemFilter is passed and it returns false
- *
- * **Input types affected:** text
- *
- * @default 'Only values matching specific conditions can be added'
- */
- customAddItemText: string | Choices.Types.noticeStringFunction;
-
- /**
- * Compare choice and value in appropriate way (e.g. deep equality for objects). To compare choice and value, pass a function with a `valueComparer` argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example).
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @default
- * ```
- * (choice, item) => choice === item;
- * ```
- */
- valueComparer: Choices.Types.valueCompareFunction;
-
- /**
- * Classes added to HTML generated by Choices. By default classnames follow the BEM notation.
- *
- * **Input types affected:** text, select-one, select-multiple
- */
- classNames: Choices.ClassNames;
-
- /**
- * Choices uses the great Fuse library for searching. You can find more options here: https://github.com/krisk/Fuse#options
- */
- fuseOptions: FuseOptions;
-
- /**
- * Function to run once Choices initialises.
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * @note For each callback, this refers to the current instance of Choices. This can be useful if you need access to methods `(this.disable())` or the config object `(this.config)`.
- *
- * @default null
- */
- callbackOnInit: ((this: Choices) => void) | null;
-
- /**
- * Function to run on template creation. Through this callback it is possible to provide custom templates for the various components of Choices (see terminology). For Choices to work with custom templates, it is important you maintain the various data attributes defined here [https://github.com/jshjohnson/Choices/blob/67f29c286aa21d88847adfcd6304dc7d068dc01f/assets/scripts/src/choices.js#L1993-L2067].
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * @note For each callback, this refers to the current instance of Choices. This can be useful if you need access to methods `(this.disable())` or the config object `(this.config)`.
- *
- * @example
- * ```
- * const example = new Choices(element, {
- * callbackOnCreateTemplates: function (template) {
- * var classNames = this.config.classNames;
- * return {
- * item: (data) => {
- * return template(`
- *
- * ★ ${data.label}
- *
- * `);
- * },
- * choice: (data) => {
- * return template(`
- * 0 ? 'role="treeitem"' : 'role="option"'}>
- * ★ ${data.label}
- *
- * `);
- * },
- * };
- * }
- * });
- * ```
- *
- * @default null
- */
- callbackOnCreateTemplates:
- | ((template: Choices.Types.strToEl) => Partial)
- | null;
- }
-
- interface KeyDownAction {
- event: KeyboardEvent;
- activeItems: Item[];
- hasFocusedInput: boolean;
- hasActiveDropdown: boolean;
- hasItems: boolean;
- }
-}
-
-// Exporting default class
-export default class Choices {
- static readonly defaults: {
- readonly options: Partial;
- readonly templates: Choices.Templates;
- };
- readonly config: Choices.Options;
-
- // State Tracking
- initialised: boolean;
-
- // Element
- readonly passedElement: Choices.passedElement;
-
- placeholder: boolean;
-
- constructor(
- selectorOrElement: string | HTMLInputElement | HTMLSelectElement,
- userConfig?: Partial,
- );
-
- /**
- * Creates a new instance of Choices, adds event listeners, creates templates and renders a Choices element to the DOM.
- *
- * @note This is called implicitly when a new instance of Choices is created. This would be used after a Choices instance had already been destroyed `(using destroy())`.
- *
- * **Input types affected:** text, select-multiple, select-one
- */
- init(): void;
-
- /**
- * Kills the instance of Choices, removes all event listeners and returns passed input to its initial state.
- *
- * **Input types affected:** text, select-multiple, select-one
- */
- destroy(): void;
-
- /** Select item (a selected item can be deleted) */
- highlightItem(item: Element, runEvent?: boolean): this;
-
- /** Deselect item */
- unhighlightItem(item: Element): this;
-
- /**
- * Highlight each chosen item (selected items can be removed).
- *
- * **Input types affected:** text, select-multiple
- */
- highlightAll(): this;
-
- /**
- * Un-highlight each chosen item.
- *
- * **Input types affected:** text, select-multiple
- */
- unhighlightAll(): this;
-
- /**
- * Remove each item by a given value.
- *
- * **Input types affected:** text, select-multiple
- */
- removeActiveItemsByValue(value: string): this;
-
- /**
- * Remove each selectable item.
- *
- * **Input types affected:** text, select-multiple
- */
- removeActiveItems(excludedId: number): this;
-
- /**
- * Remove each item the user has selected.
- *
- * **Input types affected:** text, select-multiple
- */
- removeHighlightedItems(runEvent?: boolean): this;
-
- /**
- * Show option list dropdown (only affects select inputs).
- *
- * **Input types affected:** select-one, select-multiple
- */
- showDropdown(focusInput?: boolean): this;
-
- /**
- * Hide option list dropdown (only affects select inputs).
- *
- * **Input types affected:** text, select-multiple
- */
- hideDropdown(blurInput?: boolean): this;
-
- /**
- * Get value(s) of input (i.e. inputted items (text) or selected choices (select)). Optionally pass an argument of `true` to only return values rather than value objects.
- *
- * **Input types affected:** text, select-one, select-multiple
- *
- * @example
- * ```
- * const example = new Choices(element);
- * const values = example.getValue(true); // returns ['value 1', 'value 2'];
- * const valueArray = example.getValue(); // returns [{ active: true, choiceId: 1, highlighted: false, id: 1, label: 'Label 1', value: 'Value 1'}, { active: true, choiceId: 2, highlighted: false, id: 2, label: 'Label 2', value: 'Value 2'}];
- * ```
- */
- getValue(valueOnly?: boolean): string | string[];
-
- /** Direct populate choices
- *
- * @param {string[] | Choices.Item[]} items
- */
- setValue(items: string[] | Choices.Item[]): this;
-
- /**
- * Set value of input based on existing Choice. `value` can be either a single string or an array of strings
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @example
- * ```
- * const example = new Choices(element, {
- * choices: [
- * {value: 'One', label: 'Label One'},
- * {value: 'Two', label: 'Label Two', disabled: true},
- * {value: 'Three', label: 'Label Three'},
- * ],
- * });
- *
- * example.setChoiceByValue('Two'); // Choice with value of 'Two' has now been selected.
- * ```
- */
- setChoiceByValue(value: string | string[]): this;
-
- /**
- * Set choices of select input via an array of objects (or function that returns array of object or promise of it),
- * a value field name and a label field name.
- * This behaves the same as passing items via the choices option but can be called after initialising Choices.
- * This can also be used to add groups of choices (see example 2); Optionally pass a true `replaceChoices` value to remove any existing choices.
- * Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc).
- *
- * **Input types affected:** select-one, select-multiple
- *
- * @param {string} [value = 'value'] - name of `value` field
- * @param {string} [label = 'label'] - name of 'label' field
- * @param {boolean} [replaceChoices = false] - whether to replace of add choices
- *
- * @example
- * ```js
- * const example = new Choices(element);
- *
- * example.setChoices([
- * {value: 'One', label: 'Label One', disabled: true},
- * {value: 'Two', label: 'Label Two', selected: true},
- * {value: 'Three', label: 'Label Three'},
- * ], 'value', 'label', false);
- * ```
- *
- * @example
- * ```js
- * const example = new Choices(element);
- *
- * example.setChoices(async () => {
- * try {
- * const items = await fetch('/items');
- * return items.json()
- * } catch(err) {
- * console.error(err)
- * }
- * });
- * ```
- *
- * @example
- * ```js
- * const example = new Choices(element);
- *
- * example.setChoices([{
- * label: 'Group one',
- * id: 1,
- * disabled: false,
- * choices: [
- * {value: 'Child One', label: 'Child One', selected: true},
- * {value: 'Child Two', label: 'Child Two', disabled: true},
- * {value: 'Child Three', label: 'Child Three'},
- * ]
- * },
- * {
- * label: 'Group two',
- * id: 2,
- * disabled: false,
- * choices: [
- * {value: 'Child Four', label: 'Child Four', disabled: true},
- * {value: 'Child Five', label: 'Child Five'},
- * {value: 'Child Six', label: 'Child Six', customProperties: {
- * description: 'Custom description about child six',
- * random: 'Another random custom property'
- * }},
- * ]
- * }], 'value', 'label', false);
- * ```
- */
- setChoices<
- T extends object[] | ((instance: Choices) => object[] | Promise