Fix backspace bug

This commit is contained in:
shamoon committed 2026-11-21 10:39:47 -08:00
1 parent f6b8055150
commit b1bb4bdf84
3 files changed
+50

No files matched your search

@@ -17,6 +17,7 @@
[searchFn]="searchFn"
addTagText="Add tag"
i18n-addTagText
[keyDownFn]="onKeyDown"
(add)="onAdd($event)"
(change)="onChange(value)">
@@ -278,4 +278,42 @@ describe('TagsComponent', () => {
component.tags = [lone]
expect(component.getParentChain(5)).toEqual([])
})
describe('hierarchy', () => {
const root: Tag = { id: 1, name: 'root' }
const mid: Tag = { id: 2, name: 'mid', parent: 1 }
const leaf: Tag = { id: 3, name: 'leaf', parent: 2 }
const other: Tag = { id: 4, name: 'other' }
beforeEach(() => {
component.tags = [root, mid, leaf, other]
component.value = [3, 2, 1, 4]
})
it('should treat ancestors of another selected tag as implied', () => {
expect([1, 2, 3, 4].map((id) => component.isImplied(id))).toEqual([
true,
true,
false,
false,
])
component.preserveHierarchy = false
expect(component.isImplied(1)).toBe(false)
})
it('should remove the last visible tag on backspace, not a hidden ancestor', () => {
const backspace = new KeyboardEvent('keydown', { key: 'Backspace' })
expect(component.onKeyDown(backspace)).toBe(false)
expect(component.value).toEqual([3, 2, 1])
expect(component.onKeyDown(backspace)).toBe(false)
expect(component.value).toEqual([2, 1])
// nothing hidden: leave it to ng-select
component.value = [4]
expect(component.onKeyDown(backspace)).toBe(true)
expect(
component.onKeyDown(new KeyboardEvent('keydown', { key: 'a' }))
).toBe(true)
})
})
})
@@ -153,6 +153,17 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
return !collapseImpliedAncestors(this.value, this.tagsById).includes(id)
}
/**
* Remove the last visible tag (in case its actually a hidden ancestor)
*/
readonly onKeyDown = (event: KeyboardEvent): boolean => {
if (event.key !== 'Backspace' || this.select?.searchTerm) return true
const visible = this.value?.filter((id) => !this.isImplied(id)) ?? []
if (visible.length === (this.value?.length ?? 0)) return true
this.removeTag(visible.at(-1))
return false
}
getTag(id: number) {
if (this.tags) {
return this.tags.find((tag) => tag.id == id)