From 6207fbc31705c176ac00b970503c172a61e237c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BFCai?= Date: Thu, 31 Oct 2024 20:17:16 +0800 Subject: [PATCH] fix(tag-input): prevent backspace event in readonly mode and add test --- src/tag-input/__tests__/vitest-tag-input.test.jsx | 15 ++++++++++++++- src/tag-input/useTagList.tsx | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/tag-input/__tests__/vitest-tag-input.test.jsx b/src/tag-input/__tests__/vitest-tag-input.test.jsx index fdadcb8a6..6c8850237 100644 --- a/src/tag-input/__tests__/vitest-tag-input.test.jsx +++ b/src/tag-input/__tests__/vitest-tag-input.test.jsx @@ -210,7 +210,7 @@ describe('TagInput Component', () => { expect(wrapper.attributes('placeholder')).toBe('This is TagInput placeholder'); }); - it('props.readonly works fine', () => { + it('props.readonly works fine', async () => { // readonly default value is false const wrapper1 = mount({ render() { @@ -225,6 +225,7 @@ describe('TagInput Component', () => { }, }).find('.t-input'); expect(wrapper2.classes('t-is-readonly')).toBeTruthy(); + // readonly = false const wrapper3 = mount({ render() { @@ -232,6 +233,18 @@ describe('TagInput Component', () => { }, }).find('.t-input'); expect(wrapper3.classes('t-is-readonly')).toBeFalsy(); + // readonly = false and able backspace + const onRemoveFnOn = vi.fn(); + const wrapper4 = getTagInputValueMount(TagInput, { readonly: false }, { remove: onRemoveFnOn }); + wrapper4.find('input').trigger('keydown.backspace'); + await wrapper4.vm.$nextTick(); + expect(onRemoveFnOn).toHaveBeenCalled(); + // readonly = true and prevent backspace + const onRemoveFnUn = vi.fn(); + const wrapper5 = getTagInputValueMount(TagInput, { readonly: true }, { remove: onRemoveFnUn }); + wrapper5.find('input').trigger('keydown.backspace'); + await wrapper5.vm.$nextTick(); + expect(onRemoveFnUn).not.toHaveBeenCalled(); }); it('props.readonly: readonly TagInput does not need clearIcon', async () => { diff --git a/src/tag-input/useTagList.tsx b/src/tag-input/useTagList.tsx index f35cb941a..af4133f48 100644 --- a/src/tag-input/useTagList.tsx +++ b/src/tag-input/useTagList.tsx @@ -70,7 +70,7 @@ export default function useTagList(props: TdTagInputProps, context: SetupContext // 按下回退键,删除标签 const onInputBackspaceKeyDown = (value: InputValue, p: { e: KeyboardEvent }) => { const { e } = p; - if (!tagValue.value || !tagValue.value.length) return; + if (!tagValue.value || !tagValue.value.length || readonly.value) return; // 回车键删除,输入框值为空时,才允许 Backspace 删除标签 const isDelete = /(Backspace|NumpadDelete)/.test(e.code) || /(Backspace|NumpadDelete)/.test(e.key); if (!value && isDelete) {