svelte-multiselect 4.0.5 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,8 @@
1
1
  <script >import { createEventDispatcher, tick } from 'svelte';
2
- import { fly } from 'svelte/transition';
2
+ import './';
3
3
  import CircleSpinner from './CircleSpinner.svelte';
4
- import { CrossIcon, ExpandIcon, DisabledIcon } from './icons';
4
+ import { CrossIcon, DisabledIcon, ExpandIcon } from './icons';
5
5
  import Wiggle from './Wiggle.svelte';
6
- export let selectedLabels = [];
7
- export let selectedValues = [];
8
6
  export let searchText = ``;
9
7
  export let showOptions = false;
10
8
  export let maxSelect = null; // null means any number of options are selectable
@@ -12,7 +10,9 @@ export let maxSelectMsg = null;
12
10
  export let disabled = false;
13
11
  export let disabledTitle = `This field is disabled`;
14
12
  export let options;
15
- export let selected = options.filter((op) => op?.preselected) ?? [];
13
+ export let selected = [];
14
+ export let selectedLabels = [];
15
+ export let selectedValues = [];
16
16
  export let input = null;
17
17
  export let outerDiv = null;
18
18
  export let placeholder = undefined;
@@ -23,7 +23,7 @@ export let activeOption = null;
23
23
  export let filterFunc = (op, searchText) => {
24
24
  if (!searchText)
25
25
  return true;
26
- return `${op.label}`.toLowerCase().includes(searchText.toLowerCase());
26
+ return `${get_label(op)}`.toLowerCase().includes(searchText.toLowerCase());
27
27
  };
28
28
  export let outerDivClass = ``;
29
29
  export let ulSelectedClass = ``;
@@ -36,85 +36,99 @@ export let removeBtnTitle = `Remove`;
36
36
  export let removeAllTitle = `Remove all`;
37
37
  export let defaultDisabledTitle = `This option is disabled`;
38
38
  export let allowUserOptions = false;
39
+ export let addOptionMsg = `Create this option...`;
39
40
  export let autoScroll = true;
40
41
  export let loading = false;
41
42
  export let required = false;
42
43
  export let autocomplete = `off`;
43
44
  export let invalid = false;
44
- if (maxSelect !== null && maxSelect < 0) {
45
+ export let sortSelected = false;
46
+ if (maxSelect !== null && maxSelect < 1) {
45
47
  console.error(`maxSelect must be null or positive integer, got ${maxSelect}`);
46
48
  }
47
49
  if (!(options?.length > 0))
48
- console.error(`MultiSelect missing options`);
50
+ console.error(`MultiSelect is missing options`);
49
51
  if (!Array.isArray(selected))
50
52
  console.error(`selected prop must be an array`);
51
53
  const dispatch = createEventDispatcher();
52
- function isObject(item) {
53
- return typeof item === `object` && !Array.isArray(item) && item !== null;
54
- }
55
- // process proto options to full ones with mandatory labels
56
- $: _options = options.map((rawOp) => {
57
- if (isObject(rawOp)) {
58
- const option = { ...rawOp };
59
- if (option.value === undefined)
60
- option.value = option.label;
61
- return option;
62
- }
63
- else {
64
- if (![`string`, `number`].includes(typeof rawOp)) {
65
- console.warn(`MultiSelect options must be objects, strings or numbers, got ${typeof rawOp}`);
66
- }
67
- // even if we logged error above, try to proceed hoping user knows what they're doing
68
- return { label: rawOp, value: rawOp };
69
- }
70
- });
71
- $: labels = _options.map((op) => op.label);
72
- $: if (new Set(labels).size !== options.length) {
73
- console.warn(`Option labels should be unique. Duplicates found: ${labels.filter((label, idx) => labels.indexOf(label) !== idx)}`);
74
- }
75
- let wiggle = false;
76
- $: selectedLabels = selected.map((op) => op.label);
77
- $: selectedValues = selected.map((op) => op.value);
54
+ let activeMsg = false; // controls active state of <li>{addOptionMsg}</li>
55
+ const get_label = (op) => (op instanceof Object ? op.label : op);
56
+ // fallback on label if option is object and value is undefined
57
+ const get_value = (op) => (op instanceof Object ? op.value ?? op.label : op);
58
+ let wiggle = false; // controls wiggle animation when user tries to exceed maxSelect
59
+ $: selectedLabels = selected.map(get_label);
60
+ $: selectedValues = selected.map(get_value);
78
61
  // formValue binds to input.form-control to prevent form submission if required
79
62
  // prop is true and no options are selected
80
63
  $: formValue = selectedValues.join(`,`);
81
64
  $: if (formValue)
82
65
  invalid = false; // reset error status whenever component state changes
83
66
  // options matching the current search text
84
- $: matchingOptions = _options.filter((op) => filterFunc(op, searchText) && !selectedLabels.includes(op.label));
85
- $: matchingEnabledOptions = matchingOptions.filter((op) => !op.disabled);
67
+ $: matchingOptions = options.filter((op) => filterFunc(op, searchText) &&
68
+ !(op instanceof Object && op.disabled) &&
69
+ !selectedLabels.includes(get_label(op)) // remove already selected options from dropdown list
70
+ );
71
+ // add an option to selected list
86
72
  function add(label) {
87
73
  if (maxSelect && maxSelect > 1 && selected.length >= maxSelect)
88
74
  wiggle = true;
89
- if (!selectedLabels.includes(label) &&
90
- // for maxselect = 1 we always replace current option with new selection
91
- (maxSelect === null || maxSelect === 1 || selected.length < maxSelect)) {
75
+ // to prevent duplicate selection, we could add `&& !selectedLabels.includes(label)`
76
+ if (maxSelect === null || maxSelect === 1 || selected.length < maxSelect) {
77
+ // first check if we find option in the options list
78
+ let option = options.find((op) => get_label(op) === label);
79
+ if (!option && // this has the side-effect of not allowing to user to add the same
80
+ // custom option twice in append mode
81
+ [true, `append`].includes(allowUserOptions) &&
82
+ searchText.length > 0) {
83
+ // user entered text but no options match, so if allowUserOptions=true | 'append', we create new option
84
+ option = { label: searchText, value: searchText };
85
+ if (allowUserOptions === `append`)
86
+ options = [...options, option];
87
+ }
92
88
  searchText = ``; // reset search string on selection
93
- const option = _options.find((op) => op.label === label);
94
89
  if (!option) {
95
90
  console.error(`MultiSelect: option with label ${label} not found`);
96
91
  return;
97
92
  }
98
93
  if (maxSelect === 1) {
94
+ // for maxselect = 1 we always replace current option with new one
99
95
  selected = [option];
100
96
  }
101
97
  else {
102
- selected = [option, ...selected];
98
+ selected = [...selected, option];
99
+ if (sortSelected === true) {
100
+ selected = selected.sort((op1, op2) => {
101
+ const [label1, label2] = [get_label(op1), get_label(op2)];
102
+ // coerce to string if labels are numbers
103
+ return `${label1}`.localeCompare(`${label2}`);
104
+ });
105
+ }
106
+ else if (typeof sortSelected === `function`) {
107
+ selected = selected.sort(sortSelected);
108
+ }
103
109
  }
104
110
  if (selected.length === maxSelect)
105
111
  setOptionsVisible(false);
112
+ else
113
+ input?.focus();
106
114
  dispatch(`add`, { option });
107
115
  dispatch(`change`, { option, type: `add` });
108
116
  }
109
117
  }
118
+ // remove an option from selected list
110
119
  function remove(label) {
111
120
  if (selected.length === 0)
112
121
  return;
113
- const option = _options.find((option) => option.label === label);
122
+ selected.splice(selectedLabels.lastIndexOf(label), 1);
123
+ selected = selected; // Svelte rerender after in-place splice
124
+ const option = options.find((option) => get_label(option) === label) ??
125
+ // if option with label could not be found but allowUserOptions is truthy,
126
+ // assume it was created by user and create correspondidng option object
127
+ // on the fly for use as event payload
128
+ (allowUserOptions && { label, value: label });
114
129
  if (!option) {
115
130
  return console.error(`MultiSelect: option with label ${label} not found`);
116
131
  }
117
- selected = selected.filter((option) => label !== option.label);
118
132
  dispatch(`remove`, { option });
119
133
  dispatch(`change`, { option, type: `remove` });
120
134
  }
@@ -141,16 +155,15 @@ async function handleKeydown(event) {
141
155
  }
142
156
  // on enter key: toggle active option and reset search text
143
157
  else if (event.key === `Enter`) {
158
+ event.preventDefault(); // prevent enter key from triggering form submission
144
159
  if (activeOption) {
145
- const { label } = activeOption;
160
+ const label = get_label(activeOption);
146
161
  selectedLabels.includes(label) ? remove(label) : add(label);
147
162
  searchText = ``;
148
163
  }
149
- else if ([true, `append`].includes(allowUserOptions)) {
150
- selected = [...selected, { label: searchText, value: searchText }];
151
- if (allowUserOptions === `append`)
152
- options = [...options, { label: searchText, value: searchText }];
153
- searchText = ``;
164
+ else if (allowUserOptions && searchText.length > 0) {
165
+ // user entered text but no options match, so if allowUserOptions is truthy, we create new option
166
+ add(searchText);
154
167
  }
155
168
  // no active option and no search text means the options dropdown is closed
156
169
  // in which case enter means open it
@@ -159,24 +172,34 @@ async function handleKeydown(event) {
159
172
  }
160
173
  // on up/down arrow keys: update active option
161
174
  else if ([`ArrowDown`, `ArrowUp`].includes(event.key)) {
162
- if (activeOption === null) {
163
- // if no option is active yet, make first one active
164
- activeOption = matchingEnabledOptions[0];
175
+ // if no option is active yet, but there are matching options, make first one active
176
+ if (activeOption === null && matchingOptions.length > 0) {
177
+ activeOption = matchingOptions[0];
178
+ return;
179
+ }
180
+ else if (allowUserOptions && searchText.length > 0) {
181
+ // if allowUserOptions is truthy and user entered text but no options match, we make
182
+ // <li>{addUserMsg}</li> active on keydown (or toggle it if already active)
183
+ activeMsg = !activeMsg;
184
+ return;
185
+ }
186
+ else if (activeOption === null) {
187
+ // if no option is active and no options are matching, do nothing
165
188
  return;
166
189
  }
167
190
  const increment = event.key === `ArrowUp` ? -1 : 1;
168
- const newActiveIdx = matchingEnabledOptions.indexOf(activeOption) + increment;
191
+ const newActiveIdx = matchingOptions.indexOf(activeOption) + increment;
169
192
  if (newActiveIdx < 0) {
170
193
  // wrap around top
171
- activeOption = matchingEnabledOptions[matchingEnabledOptions.length - 1];
194
+ activeOption = matchingOptions[matchingOptions.length - 1];
172
195
  }
173
- else if (newActiveIdx === matchingEnabledOptions.length) {
196
+ else if (newActiveIdx === matchingOptions.length) {
174
197
  // wrap around bottom
175
- activeOption = matchingEnabledOptions[0];
198
+ activeOption = matchingOptions[0];
176
199
  }
177
200
  else {
178
201
  // default case: select next/previous in item list
179
- activeOption = matchingEnabledOptions[newActiveIdx];
202
+ activeOption = matchingOptions[newActiveIdx];
180
203
  }
181
204
  if (autoScroll) {
182
205
  await tick();
@@ -185,20 +208,18 @@ async function handleKeydown(event) {
185
208
  }
186
209
  }
187
210
  // on backspace key: remove last selected option
188
- else if (event.key === `Backspace`) {
189
- const label = selectedLabels.pop();
190
- if (label && !searchText)
191
- remove(label);
211
+ else if (event.key === `Backspace` && selectedLabels.length > 0 && !searchText) {
212
+ remove(selectedLabels.at(-1));
192
213
  }
193
214
  }
194
- const removeAll = () => {
215
+ function remove_all() {
195
216
  dispatch(`removeAll`, { options: selected });
196
217
  dispatch(`change`, { options: selected, type: `removeAll` });
197
218
  selected = [];
198
219
  searchText = ``;
199
- };
220
+ }
200
221
  $: isSelected = (label) => selectedLabels.includes(label);
201
- const handleEnterAndSpaceKeys = (handler) => (event) => {
222
+ const if_enter_or_space = (handler) => (event) => {
202
223
  if ([`Enter`, `Space`].includes(event.code)) {
203
224
  event.preventDefault();
204
225
  handler();
@@ -214,8 +235,6 @@ const handleEnterAndSpaceKeys = (handler) => (event) => {
214
235
  }}
215
236
  />
216
237
 
217
- <!-- z-index: 2 when showOptions is true ensures the ul.selected of one <MultiSelect />
218
- display above those of another following shortly after it -->
219
238
  <div
220
239
  bind:this={outerDiv}
221
240
  class:disabled
@@ -243,14 +262,14 @@ display above those of another following shortly after it -->
243
262
  {#each selected as option, idx}
244
263
  <li class={liSelectedClass} aria-selected="true">
245
264
  <slot name="selected" {option} {idx}>
246
- {option.label}
265
+ {get_label(option)}
247
266
  </slot>
248
267
  {#if !disabled}
249
268
  <button
250
- on:mouseup|stopPropagation={() => remove(option.label)}
251
- on:keydown={handleEnterAndSpaceKeys(() => remove(option.label))}
269
+ on:mouseup|stopPropagation={() => remove(get_label(option))}
270
+ on:keydown={if_enter_or_space(() => remove(get_label(option)))}
252
271
  type="button"
253
- title="{removeBtnTitle} {option.label}"
272
+ title="{removeBtnTitle} {get_label(option)}"
254
273
  >
255
274
  <CrossIcon width="15px" />
256
275
  </button>
@@ -297,56 +316,68 @@ display above those of another following shortly after it -->
297
316
  type="button"
298
317
  class="remove-all"
299
318
  title={removeAllTitle}
300
- on:mouseup|stopPropagation={removeAll}
301
- on:keydown={handleEnterAndSpaceKeys(removeAll)}
319
+ on:mouseup|stopPropagation={remove_all}
320
+ on:keydown={if_enter_or_space(remove_all)}
302
321
  >
303
322
  <CrossIcon width="15px" />
304
323
  </button>
305
324
  {/if}
306
325
  {/if}
307
326
 
308
- {#key showOptions}
309
- <ul
310
- class:hidden={!showOptions}
311
- class="options {ulOptionsClass}"
312
- transition:fly|local={{ duration: 300, y: 40 }}
313
- >
314
- {#each matchingOptions as option, idx}
315
- {@const { label, disabled, title = null, selectedTitle } = option}
316
- {@const { disabledTitle = defaultDisabledTitle } = option}
317
- {@const active = activeOption?.label === label}
327
+ <ul class:hidden={!showOptions} class="options {ulOptionsClass}">
328
+ {#each matchingOptions as option, idx}
329
+ {@const {
330
+ label,
331
+ disabled = null,
332
+ title = null,
333
+ selectedTitle = null,
334
+ disabledTitle = defaultDisabledTitle,
335
+ } = option instanceof Object ? option : { label: option }}
336
+ {@const active = activeOption && get_label(activeOption) === label}
337
+ <li
338
+ on:mousedown|stopPropagation
339
+ on:mouseup|stopPropagation={() => {
340
+ if (!disabled) isSelected(label) ? remove(label) : add(label)
341
+ }}
342
+ title={disabled ? disabledTitle : (isSelected(label) && selectedTitle) || title}
343
+ class:selected={isSelected(label)}
344
+ class:active
345
+ class:disabled
346
+ class="{liOptionClass} {active ? liActiveOptionClass : ``}"
347
+ on:mouseover={() => {
348
+ if (!disabled) activeOption = option
349
+ }}
350
+ on:focus={() => {
351
+ if (!disabled) activeOption = option
352
+ }}
353
+ on:mouseout={() => (activeOption = null)}
354
+ on:blur={() => (activeOption = null)}
355
+ aria-selected="false"
356
+ >
357
+ <slot name="option" {option} {idx}>
358
+ {get_label(option)}
359
+ </slot>
360
+ </li>
361
+ {:else}
362
+ {#if allowUserOptions && searchText}
318
363
  <li
319
- on:mouseup|preventDefault|stopPropagation
320
- on:mousedown|preventDefault|stopPropagation={() => {
321
- if (disabled) return
322
- isSelected(label) ? remove(label) : add(label)
323
- }}
324
- title={disabled ? disabledTitle : (isSelected(label) && selectedTitle) || title}
325
- class:selected={isSelected(label)}
326
- class:active
327
- class:disabled
328
- class="{liOptionClass} {active ? liActiveOptionClass : ``}"
329
- on:mouseover={() => {
330
- if (disabled) return
331
- activeOption = option
332
- }}
333
- on:focus={() => {
334
- if (disabled) return
335
- activeOption = option
336
- }}
337
- on:mouseout={() => (activeOption = null)}
338
- on:blur={() => (activeOption = null)}
364
+ on:mousedown|stopPropagation
365
+ on:mouseup|stopPropagation={() => add(searchText)}
366
+ title={addOptionMsg}
367
+ class:active={activeMsg}
368
+ on:mouseover={() => (activeMsg = true)}
369
+ on:focus={() => (activeMsg = true)}
370
+ on:mouseout={() => (activeMsg = false)}
371
+ on:blur={() => (activeMsg = false)}
339
372
  aria-selected="false"
340
373
  >
341
- <slot name="option" {option} {idx}>
342
- {option.label}
343
- </slot>
374
+ {addOptionMsg}
344
375
  </li>
345
376
  {:else}
346
377
  <span>{noOptionsMsg}</span>
347
- {/each}
348
- </ul>
349
- {/key}
378
+ {/if}
379
+ {/each}
380
+ </ul>
350
381
  </div>
351
382
 
352
383
  <style>
@@ -366,6 +397,8 @@ display above those of another following shortly after it -->
366
397
  min-height: var(--sms-min-height, 19pt);
367
398
  }
368
399
  :where(div.multiselect.open) {
400
+ /* increase z-index when open to ensure the dropdown of one <MultiSelect />
401
+ displays above that of another slightly below it on the page */
369
402
  z-index: var(--sms-open-z-index, 4);
370
403
  }
371
404
  :where(div.multiselect:focus-within) {
@@ -455,9 +488,14 @@ display above those of another following shortly after it -->
455
488
  max-height: var(--sms-options-max-height, 50vh);
456
489
  overscroll-behavior: var(--sms-options-overscroll, none);
457
490
  box-shadow: var(--sms-options-shadow, 0 0 14pt -8pt black);
491
+ transition: all 0.2s;
492
+ opacity: 1;
493
+ transform: translateY(0);
458
494
  }
459
495
  :where(div.multiselect > ul.options.hidden) {
460
496
  visibility: hidden;
497
+ opacity: 0;
498
+ transform: translateY(50px);
461
499
  }
462
500
  :where(div.multiselect > ul.options > li) {
463
501
  padding: 3pt 2ex;
@@ -1,17 +1,17 @@
1
1
  import { SvelteComponentTyped } from "svelte";
2
- import type { Option, Primitive, ProtoOption } from './';
2
+ import { CustomEvents, Option } from './';
3
3
  declare const __propDef: {
4
4
  props: {
5
- selectedLabels?: Primitive[] | undefined;
6
- selectedValues?: Primitive[] | undefined;
7
5
  searchText?: string | undefined;
8
6
  showOptions?: boolean | undefined;
9
7
  maxSelect?: number | null | undefined;
10
8
  maxSelectMsg?: ((current: number, max: number) => string) | null | undefined;
11
9
  disabled?: boolean | undefined;
12
10
  disabledTitle?: string | undefined;
13
- options: ProtoOption[];
11
+ options: Option[];
14
12
  selected?: Option[] | undefined;
13
+ selectedLabels?: (string | number)[] | undefined;
14
+ selectedValues?: unknown[] | undefined;
15
15
  input?: HTMLInputElement | null | undefined;
16
16
  outerDiv?: HTMLDivElement | null | undefined;
17
17
  placeholder?: string | undefined;
@@ -31,16 +31,13 @@ declare const __propDef: {
31
31
  removeAllTitle?: string | undefined;
32
32
  defaultDisabledTitle?: string | undefined;
33
33
  allowUserOptions?: boolean | "append" | undefined;
34
+ addOptionMsg?: string | undefined;
34
35
  autoScroll?: boolean | undefined;
35
36
  loading?: boolean | undefined;
36
37
  required?: boolean | undefined;
37
38
  autocomplete?: string | undefined;
38
39
  invalid?: boolean | undefined;
39
- };
40
- events: {
41
- mouseup: MouseEvent;
42
- } & {
43
- [evt: string]: CustomEvent<any>;
40
+ sortSelected?: boolean | ((op1: Option, op2: Option) => number) | undefined;
44
41
  };
45
42
  slots: {
46
43
  selected: {
@@ -54,6 +51,8 @@ declare const __propDef: {
54
51
  idx: any;
55
52
  };
56
53
  };
54
+ getters: {};
55
+ events: CustomEvents;
57
56
  };
58
57
  export declare type MultiSelectProps = typeof __propDef.props;
59
58
  export declare type MultiSelectEvents = typeof __propDef.events;
package/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  export { default } from './MultiSelect.svelte';
2
- export declare type Primitive = string | number;
3
- export declare type Option = {
4
- label: Primitive;
5
- value: Primitive;
2
+ export declare type Option = string | number | ObjectOption;
3
+ export declare type ObjectOption = {
4
+ label: string | number;
5
+ value?: unknown;
6
6
  title?: string;
7
7
  disabled?: boolean;
8
8
  preselected?: boolean;
@@ -10,9 +10,6 @@ export declare type Option = {
10
10
  selectedTitle?: string;
11
11
  [key: string]: unknown;
12
12
  };
13
- export declare type ProtoOption = Primitive | (Omit<Option, `value`> & {
14
- value?: Primitive;
15
- });
16
13
  export declare type DispatchEvents = {
17
14
  add: {
18
15
  option: Option;
@@ -31,3 +28,6 @@ export declare type DispatchEvents = {
31
28
  focus: undefined;
32
29
  blur: undefined;
33
30
  };
31
+ export declare type CustomEvents = {
32
+ [key in keyof DispatchEvents]: CustomEvent<DispatchEvents[key]>;
33
+ };
package/package.json CHANGED
@@ -5,37 +5,39 @@
5
5
  "homepage": "https://svelte-multiselect.netlify.app",
6
6
  "repository": "https://github.com/janosh/svelte-multiselect",
7
7
  "license": "MIT",
8
- "version": "4.0.5",
8
+ "version": "5.0.1",
9
9
  "type": "module",
10
10
  "svelte": "index.js",
11
+ "main": "index.js",
11
12
  "bugs": "https://github.com/janosh/svelte-multiselect/issues",
12
13
  "devDependencies": {
13
14
  "@sveltejs/adapter-static": "^1.0.0-next.29",
14
- "@sveltejs/kit": "^1.0.0-next.302",
15
- "@sveltejs/vite-plugin-svelte": "^1.0.0-next.40",
16
- "@typescript-eslint/eslint-plugin": "^5.16.0",
17
- "@typescript-eslint/parser": "^5.16.0",
18
- "@vitest/ui": "^0.7.9",
19
- "eslint": "^8.11.0",
15
+ "@sveltejs/kit": "^1.0.0-next.308",
16
+ "@sveltejs/vite-plugin-svelte": "^1.0.0-next.41",
17
+ "@typescript-eslint/eslint-plugin": "^5.18.0",
18
+ "@typescript-eslint/parser": "^5.18.0",
19
+ "@vitest/ui": "^0.9.0",
20
+ "c8": "^7.11.0",
21
+ "eslint": "^8.12.0",
20
22
  "eslint-plugin-svelte3": "^3.4.1",
21
23
  "hastscript": "^7.0.2",
22
24
  "jsdom": "^19.0.0",
23
25
  "mdsvex": "^0.10.5",
24
- "playwright": "^1.20.0",
25
- "prettier": "^2.6.0",
26
+ "playwright": "^1.20.2",
27
+ "prettier": "^2.6.2",
26
28
  "prettier-plugin-svelte": "^2.6.0",
27
29
  "rehype-autolink-headings": "^6.1.1",
28
30
  "rehype-slug": "^5.0.1",
29
- "svelte": "^3.46.4",
31
+ "svelte": "^3.46.6",
30
32
  "svelte-check": "^2.4.6",
31
33
  "svelte-github-corner": "^0.1.0",
32
- "svelte-preprocess": "^4.10.4",
34
+ "svelte-preprocess": "^4.10.5",
33
35
  "svelte-toc": "^0.2.9",
34
36
  "svelte2tsx": "^0.5.6",
35
37
  "tslib": "^2.3.1",
36
- "typescript": "^4.6.2",
37
- "vite": "^2.8.6",
38
- "vitest": "^0.7.9"
38
+ "typescript": "^4.6.3",
39
+ "vite": "^2.9.1",
40
+ "vitest": "^0.9.0"
39
41
  },
40
42
  "keywords": [
41
43
  "svelte",
package/readme.md CHANGED
@@ -35,15 +35,6 @@
35
35
 
36
36
  ## Recent breaking changes
37
37
 
38
- - v3.0.0 changed the `event.detail` payload for `'add'`, `'remove'` and `'change'` events from `token` to `option`, e.g.
39
-
40
- ```js
41
- on:add={(e) => console.log(e.detail.token.label)} // v2
42
- on:add={(e) => console.log(e.detail.option.label)} // v3
43
- ```
44
-
45
- It also added a separate event type `removeAll` for when the user removes all currently selected options at once which previously fired a normal `remove`. The props `ulTokensClass` and `liTokenClass` were renamed to `ulSelectedClass` and `liSelectedClass`. Similarly, the CSS variable `--sms-token-bg` changed to `--sms-selected-bg`.
46
-
47
38
  - v4.0.0 renamed the slots for customizing how selected options and dropdown list items are rendered:
48
39
 
49
40
  - old: `<slot name="renderOptions" />`, new: `<slot name="option" />`
@@ -53,6 +44,8 @@
53
44
 
54
45
  - v4.0.3 CSS variables starting with `--sms-input-<attr>` were renamed to just `--sms-<attr>`. E.g. `--sms-input-min-height` is now `--sms-min-height`.
55
46
 
47
+ - v5.0.0 Support both simple and object options. Previously string or number options were converted to objects internally and returned by `bind:selected`. Now, if you pass in `string[]`, that's what you'll get from `bind:selected`.
48
+
56
49
  ## Installation
57
50
 
58
51
  ```sh
@@ -84,33 +77,35 @@ Full list of props/bindable variables for this component:
84
77
  <div class="table">
85
78
 
86
79
  <!-- prettier-ignore -->
87
- | name | default | description |
88
- | :--------------------- | :-------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
89
- | `options` | required prop | Array of strings/numbers or `Option` objects that will be listed in the dropdown. See `src/lib/index.ts` for admissible fields. The `label` is the only mandatory one. It must also be unique. |
90
- | `showOptions` | `false` | Bindable boolean that controls whether the options dropdown is visible. |
91
- | `searchText` | `` | Text the user-entered to filter down on the list of options. Binds both ways, i.e. can also be used to set the input text. |
92
- | `activeOption` | `null` | Currently active option, i.e. the one the user currently hovers or navigated to with arrow keys. |
93
- | `maxSelect` | `null` | Positive integer to limit the number of options users can pick. `null` means no limit. |
94
- | `selected` | `[]` | Array of currently/pre-selected options when binding/passing as props respectively. |
95
- | `selectedLabels` | `[]` | Labels of currently selected options. |
96
- | `selectedValues` | `[]` | Values of currently selected options. |
97
- | `noOptionsMsg` | `'No matching options'` | What message to show if no options match the user-entered search string. |
98
- | `disabled` | `false` | Disable the component. It will still be rendered but users won't be able to interact with it. |
99
- | `disabledTitle` | `This field is disabled` | Tooltip text to display on hover when the component is in `disabled` state. |
100
- | `placeholder` | `undefined` | String shown in the text input when no option is selected. |
101
- | `input` | `null` | Handle to the `<input>` DOM node. Only available after component mounts (`null` before then). |
102
- | `outerDiv` | `null` | Handle to outer `<div class="multiselect">` that wraps the whole component. Only available after component mounts (`null` before then). |
103
- | `id` | `undefined` | Applied to the `<input>` element for associating HTML form `<label>`s with this component for accessibility. Also, clicking a `<label>` with same `for` attribute as `id` will focus this component. |
104
- | `name` | `id` | Applied to the `<input>` element. If not provided, will be set to the value of `id`. Sets the key of this field in a submitted form data object. Not useful at the moment since the value is stored in Svelte state, not on the `<input>`. |
105
- | `required` | `false` | Whether forms can be submitted without selecting any options. Aborts submission, is scrolled into view and shows help "Please fill out" message when true and user tries to submit with no options selected. |
106
- | `autoScroll` | `true` | `false` disables keeping the active dropdown items in view when going up/down the list of options with arrow keys. |
107
- | `allowUserOptions` | `false` | Whether users are allowed to enter values not in the dropdown list. `true` means add user-defined options to the selected list only, `'append'` means add to both options and selected. |
108
- | `loading` | `false` | Whether the component should display a spinner to indicate it's in loading state. Use `<slot name='spinner'>` to specify a custom spinner. |
109
- | `removeBtnTitle` | `'Remove'` | Title text to display when user hovers over button (cross icon) to remove selected option. |
110
- | `removeAllTitle` | `'Remove all'` | Title text to display when user hovers over remove-all button. |
111
- | `defaultDisabledTitle` | `'This option is disabled'` | Title text to display when user hovers over a disabled option. Each option can override this through its `disabledTitle` attribute. |
112
- | `autocomplete` | `'off'` | Applied to the `<input>`. Specifies if browser is permitted to auto-fill this form field. See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete) for other admissible values. |
113
- | `invalid` | `false` | If `required=true` and user tries to submit but `selected = []` is empty, `invalid` is automatically set to `true` and CSS class `invalid` applied to the top-level `div.multiselect`. `invalid` class is removed again as soon as the user selects an option. `invalid` can also be controlled externally by binding to it `<MultiSelect bind:invalid />` and setting it to `true` based on outside events or custom validation. |
80
+ | name | default | description |
81
+ | :--------------------- | :---------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
82
+ | `options` | required prop | Array of strings/numbers or `Option` objects to be listed in the dropdown. The only required key on objects is `label` which must also be unique. An object's `value` defaults to `label` if `undefined`. You can add arbitrary additional keys to your option objects. MultiSelect A few keys like `preselected` and `title` have special meaning though. See `src/lib/index.ts` for all special keys and their purpose. |
83
+ | `showOptions` | `false` | Bindable boolean that controls whether the options dropdown is visible. |
84
+ | `searchText` | `` | Text the user-entered to filter down on the list of options. Binds both ways, i.e. can also be used to set the input text. |
85
+ | `activeOption` | `null` | Currently active option, i.e. the one the user currently hovers or navigated to with arrow keys. |
86
+ | `maxSelect` | `null` | Positive integer to limit the number of options users can pick. `null` means no limit. |
87
+ | `selected` | `[]` | Array of currently/pre-selected options when binding/passing as props respectively. |
88
+ | `selectedLabels` | `[]` | Labels of currently selected options. Exposed just for convenience, equivalent to `selected.map(op => op.label)` when options are objects. If options are simple strings, `selected === selectedLabels`. Supports binding but is read-only, i.e. since this value is reactive to `selected`, you cannot control `selected` by changing `bind:selectedLabels`. |
89
+ | `selectedValues` | `[]` | Values of currently selected options. Exposed just for convenience, equivalent to `selected.map(op => op.value)` when options are objects. If options are simple strings, `selected === selectedValues`. Supports binding but is read-only, i.e. since this value is reactive to `selected`, you cannot control `selected` by changing `bind:selectedValues`. |
90
+ | `sortSelected` | `boolean \| ((op1, op2) => number)` | Default behavior is to render selected items in the order they were chosen. `sortSelected={true}` uses default JS array sorting. A compare function enables custom logic for sorting selected options. See the [`/sort-selected`](https://svelte-multiselect.netlify.app/sort-selected) example. |
91
+ | `noOptionsMsg` | `'No matching options'` | What message to show if no options match the user-entered search string. |
92
+ | `disabled` | `false` | Disable the component. It will still be rendered but users won't be able to interact with it. |
93
+ | `disabledTitle` | `This field is disabled` | Tooltip text to display on hover when the component is in `disabled` state. |
94
+ | `placeholder` | `undefined` | String shown in the text input when no option is selected. |
95
+ | `input` | `null` | Handle to the `<input>` DOM node. Only available after component mounts (`null` before then). |
96
+ | `outerDiv` | `null` | Handle to outer `<div class="multiselect">` that wraps the whole component. Only available after component mounts (`null` before then). |
97
+ | `id` | `undefined` | Applied to the `<input>` element for associating HTML form `<label>`s with this component for accessibility. Also, clicking a `<label>` with same `for` attribute as `id` will focus this component. |
98
+ | `name` | `id` | Applied to the `<input>` element. If not provided, will be set to the value of `id`. Sets the key of this field in a submitted form data object. Not useful at the moment since the value is stored in Svelte state, not on the `<input>`. |
99
+ | `required` | `false` | Whether forms can be submitted without selecting any options. Aborts submission, is scrolled into view and shows help "Please fill out" message when true and user tries to submit with no options selected. |
100
+ | `autoScroll` | `true` | `false` disables keeping the active dropdown items in view when going up/down the list of options with arrow keys. |
101
+ | `allowUserOptions` | `false` | Whether users are allowed to enter values not in the dropdown list. `true` means add user-defined options to the selected list only, `'append'` means add to both options and selected. |
102
+ | `addOptionMsg` | `'Create this option...'` | Message shown to users after entering text when no options match their query and `allowUserOptions` is truthy. |
103
+ | `loading` | `false` | Whether the component should display a spinner to indicate it's in loading state. Use `<slot name='spinner'>` to specify a custom spinner. |
104
+ | `removeBtnTitle` | `'Remove'` | Title text to display when user hovers over button (cross icon) to remove selected option. |
105
+ | `removeAllTitle` | `'Remove all'` | Title text to display when user hovers over remove-all button. |
106
+ | `defaultDisabledTitle` | `'This option is disabled'` | Title text to display when user hovers over a disabled option. Each option can override this through its `disabledTitle` attribute. |
107
+ | `autocomplete` | `'off'` | Applied to the `<input>`. Specifies if browser is permitted to auto-fill this form field. See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete) for other admissible values. |
108
+ | `invalid` | `false` | If `required=true` and user tries to submit but `selected = []` is empty, `invalid` is automatically set to `true` and CSS class `invalid` applied to the top-level `div.multiselect`. `invalid` class is removed again as soon as the user selects an option. `invalid` can also be controlled externally by binding to it `<MultiSelect bind:invalid />` and setting it to `true` based on outside events or custom validation. |
114
109
 
115
110
  </div>
116
111
 
@@ -135,8 +130,8 @@ Full list of props/bindable variables for this component:
135
130
 
136
131
  `MultiSelect.svelte` has 3 named slots:
137
132
 
138
- - `slot="option"`: Customize rendering of dropdown options. Receives as props the `option` object and the zero-indexed position (`idx`) it has in the dropdown.
139
- - `slot="selected"`: Customize rendering selected tags. Receives as props the `option` object and the zero-indexed position (`idx`) it has in the list of selected items.
133
+ - `slot="option"`: Customize rendering of dropdown options. Receives as props an `option` and the zero-indexed position (`idx`) it has in the dropdown.
134
+ - `slot="selected"`: Customize rendering of selected items. Receives as props an `option` and the zero-indexed position (`idx`) it has in the list of selected items.
140
135
  - `slot="spinner"`: Custom spinner component to display when in `loading` state. Receives no props.
141
136
  - `slot="disabled-icon"`: Custom icon to display inside the input when in `disabled` state. Receives no props. Use an empty `<span slot="disabled-icon" />` or `div` to remove the default disabled icon.
142
137
 
@@ -164,25 +159,27 @@ Example:
164
159
 
165
160
  `MultiSelect.svelte` dispatches the following events:
166
161
 
167
- | name | detail | description |
168
- | ----------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
169
- | `add` | `{ option: Option }` | Triggers when a new option is selected. |
170
- | `remove` | `{ option: Option }` | Triggers when one selected option provided as `event.detail.option` is removed. |
171
- | `removeAll` | `options: Option[]` | Triggers when all selected options are removed. The payload `event.detail.options` gives the options that were previously selected. |
172
- | `change` | `type: 'add' \| 'remove' \| 'removeAll'` | Triggers when a option is either added or removed, or all options are removed at once. Payload will be a single or an aarray of `Option` objects, respectively. |
173
- | `blur` | none | Triggers when the input field looses focus. |
162
+ | name | detail | description |
163
+ | ----------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
164
+ | `add` | `{ option: Option }` | Triggers when a new option is selected. |
165
+ | `remove` | `{ option: Option }` | Triggers when one selected option provided as `event.detail.option` is removed. |
166
+ | `removeAll` | `options: Option[]` | Triggers when all selected options are removed. The payload `event.detail.options` gives the options that were previously selected. |
167
+ | `change` | `type: 'add' \| 'remove' \| 'removeAll'` | Triggers when a option is either added or removed, or all options are removed at once. Payload will be a single or an array of `Option`s, respectively. |
168
+ | `blur` | none | Triggers when the input field looses focus. |
169
+
170
+ Depending on the data passed to the component the `options(s)` payload will either be objects or simple strings/numbers.
174
171
 
175
172
  ### Examples
176
173
 
177
174
  <!-- prettier-ignore -->
178
- - `on:add={(event) => console.log(event.detail.option.label)}`
179
- - `on:remove={(event) => console.log(event.detail.option.label)}`.
180
- - ``on:change={(event) => console.log(`${event.detail.type}: '${event.detail.option.label}'`)}``
181
- - `on:blur={yourFunctionHere}`
175
+ - `on:add={(event) => console.log(event.detail.option)}`
176
+ - `on:remove={(event) => console.log(event.detail.option)}`.
177
+ - ``on:change={(event) => console.log(`${event.detail.type}: '${event.detail.option}'`)}``
178
+ - `on:blur={myFunction}`
182
179
 
183
180
  ```svelte
184
181
  <MultiSelect
185
- on:change={(e) => alert(`You ${e.detail.type}ed '${e.detail.option.label}'`)}
182
+ on:change={(e) => alert(`You ${e.detail.type}ed '${e.detail.option}'`)}
186
183
  />
187
184
  ```
188
185
 
@@ -281,7 +278,7 @@ The second method allows you to pass in custom classes to the important DOM elem
281
278
  - `liOptionClass`
282
279
  - `liActiveOptionClass`
283
280
 
284
- This simplified version of the DOM structure of this component shows where these classes are inserted:
281
+ This simplified version of the DOM structure of the component shows where these classes are inserted:
285
282
 
286
283
  ```svelte
287
284
  <div class="multiselect {outerDivClass}">