Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,16 @@ export const TagsInput = ({
}
};

const onPaste = (event: React.ClipboardEvent<HTMLInputElement>) => {
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);
Expand All @@ -110,7 +120,32 @@ export const TagsInput = ({
onBlur={onBlur}
disabled={disabled}
onKeyUp={onKeyUp}
onPaste={onPaste}
/>
</div>
);
};

type splitPasteParamType = {
tags: Array<string>;
text: string;
separators: Array<string>;
}

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;
}
45 changes: 45 additions & 0 deletions stories/tags-input.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,48 @@ export const Page = () => {
</div>
);
};

export const Paste = () => {
const [selected, setSelected] = useState(["papaya"]);
const [disabled, setDisabled] = useState(false);
const [isEditOnRemove, setisEditOnRemove] = useState(false);

return (
<div style={{ marginBottom: "32px" }}>
<h1>Add Fruits</h1>
<pre>{JSON.stringify(selected)}</pre>
<TagsInput
value={selected}
onChange={setSelected}
name="fruits"
placeHolder="press , or ; to add fruits"
disabled={disabled}
isEditOnRemove={isEditOnRemove}
separators={[',', ';']}
/>
<div style={{ marginTop: "2rem" }}>
<button
onClick={() => setDisabled(!disabled)}
style={{ marginRight: "2rem" }}
>
Toggle Disable
</button>
<pre>Disable: {JSON.stringify(disabled)}</pre>
</div>
<div>
<button
onClick={() => setisEditOnRemove(!isEditOnRemove)}
style={{ marginRight: "2rem" }}
>
Toggle Keep Words on Backspace
</button>
<pre>Keep Words on Backspace: {JSON.stringify(isEditOnRemove)}</pre>
</div>
<div>
<button onClick={() => setSelected(["tangerine"])}>
override value
</button>
</div>
</div>
);
}