From 745308c1e183c92ec2980ee5bcd15c2fa4511cb2 Mon Sep 17 00:00:00 2001 From: Kevin Yosua Date: Wed, 17 May 2023 17:03:47 +0700 Subject: [PATCH] Feature Paste Text to Tags --- src/index.tsx | 35 ++++++++++++++++++++++++++ stories/tags-input.stories.tsx | 45 ++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/src/index.tsx b/src/index.tsx index b535239..5660b5f 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -84,6 +84,16 @@ export const TagsInput = ({ } }; + const onPaste = (event: React.ClipboardEvent) => { + const pasteText = event.clipboardData.getData("text"); + if (pasteText.length < 1) return; + + const pasteTags = splitPaste({ text: pasteText, tags, separators }) + setTags([...tags, ...pasteTags]) + event.preventDefault(); + } + + const onTagRemove = text => { setTags(tags.filter(tag => tag !== text)); onRemoved && onRemoved(text); @@ -110,7 +120,32 @@ export const TagsInput = ({ onBlur={onBlur} disabled={disabled} onKeyUp={onKeyUp} + onPaste={onPaste} /> ); }; + +type splitPasteParamType = { + tags: Array; + text: string; + separators: Array; +} + +function splitPaste({ tags, text, separators }: splitPasteParamType) { + let dirtyTags = separators.reduce((accumulator, separator) => { + const splitText = text.split(separator); + if (splitText.length > accumulator.length) accumulator = splitText; + return accumulator; + }, []); + const cleanTags = dirtyTags.map(tag => tag.trim()); + + const cleanDuplicateTags = cleanTags.reduce((accumulator, tag) => { + if (!tags.includes(tag)) { + accumulator.push(tag) + } + return accumulator; + }, []) + + return cleanDuplicateTags; +} diff --git a/stories/tags-input.stories.tsx b/stories/tags-input.stories.tsx index 4a72a60..700875c 100644 --- a/stories/tags-input.stories.tsx +++ b/stories/tags-input.stories.tsx @@ -58,3 +58,48 @@ export const Page = () => { ); }; + +export const Paste = () => { + const [selected, setSelected] = useState(["papaya"]); + const [disabled, setDisabled] = useState(false); + const [isEditOnRemove, setisEditOnRemove] = useState(false); + + return ( +
+

Add Fruits

+
{JSON.stringify(selected)}
+ +
+ +
Disable: {JSON.stringify(disabled)}
+
+
+ +
Keep Words on Backspace: {JSON.stringify(isEditOnRemove)}
+
+
+ +
+
+ ); +}