From 4b0b4f5955ca81c78ccbbee6d67e17e0dd4b46d6 Mon Sep 17 00:00:00 2001 From: Xon <635541+Xon@users.noreply.github.com> Date: Thu, 5 Sep 2024 02:36:59 +0800 Subject: [PATCH] Untangle clearStore and clearChoices - Fix `clearChoices()` would also remove items, and clearing the search flag. - Fix `clearStore()` was wiping options --- CHANGELOG.md | 1 + src/scripts/choices.ts | 29 ++++++++++++++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48c18355..d6ad2f9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ * Fix regression where webpack doesn't permit importing scss/css @tagliala [#1193](https://github.com/Choices-js/Choices/issues/1193) * Fix regression "no choices to choose from"/"no results found" notice did not reliably trigger. [#1185](https://github.com/Choices-js/Choices/issues/1185) [#1191](https://github.com/Choices-js/Choices/issues/1191) * Fix regression of UnhighlightItem event not firing [#1173](https://github.com/Choices-js/Choices/issues/1173) +* Fix `clearChoices()` would remove items, and clear the search flag. ### Chore * Add e2e tests for "no choices" behavior to match v10 diff --git a/src/scripts/choices.ts b/src/scripts/choices.ts index 78be45d4..d09cfd60 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -368,7 +368,7 @@ class Choices { this.containerOuter.unwrap(this.passedElement.element); this._store._listeners = []; // prevents select/input value being wiped - this.clearStore(); + this.clearStore(false); this._stopSearch(); this._templates = Choices.defaults.templates; @@ -782,7 +782,7 @@ class Choices { }); } - this.clearStore(); + this.clearStore(false); choicesFromOptions.forEach((groupOrChoice) => { if ('choices' in groupOrChoice) { @@ -839,12 +839,24 @@ class Choices { } clearChoices(): this { - this.passedElement.element.replaceChildren(''); + this._store.withTxn(() => { + this._store.choices.forEach((choice) => { + if (!choice.selected) { + this._store.dispatch(removeChoice(choice)); + } + }); + }); + + // @todo integrate with Store + this._searcher.reset(); - return this.clearStore(); + return this; } clearStore(): this { + this._stopSearch(); + + this.passedElement.element.replaceChildren(''); this.itemList.element.replaceChildren(''); this.choiceList.element.replaceChildren(''); this._stopSearch(); @@ -1454,11 +1466,10 @@ class Choices { } _stopSearch(): void { - const wasSearching = this._isSearching; - this._currentValue = ''; - this._isSearching = false; - this._clearNotice(); - if (wasSearching) { + if (this._isSearching) { + this._currentValue = ''; + this._isSearching = false; + this._clearNotice(); this._store.dispatch(activateChoices(true)); this.passedElement.triggerEvent(EventType.search, {