Skip to content

Commit e0b47db

Browse files
feat(frontend): add sanitizer for tag input
1 parent 08906d1 commit e0b47db

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
export const tagInputSanitizer = {
2+
customSanitizer: (value) => {
3+
try {
4+
// Entered using progressively enhanced tag input, for example:
5+
// `["foo", "bar"]`
6+
return JSON.parse(value);
7+
} catch {
8+
// Entered using comma separated values, for example:
9+
// `foo, bar`
10+
11+
// Convert string to Array
12+
let tags = value.split(",");
13+
14+
// Trim whitespace
15+
tags = tags.map((tag) => String(tag).trim());
16+
17+
// Remove empty values
18+
tags = tags.filter((tag) => tag !== "");
19+
20+
// Remove duplicate values
21+
tags = [...new Set(tags)];
22+
23+
// Return sanitized array
24+
return tags;
25+
}
26+
},
27+
};

packages/frontend/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,5 @@ export { appIcon } from "./lib/app-icon.js";
55
export { templates } from "./lib/nunjucks.js";
66
export { styles } from "./lib/lightningcss.js";
77
export { scripts } from "./lib/rollup.js";
8+
9+
export { tagInputSanitizer } from "./components/tag-input/sanitizer.js";
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { strict as assert } from "node:assert";
2+
import { describe, it } from "node:test";
3+
import { tagInputSanitizer } from "../../../components/tag-input/sanitizer.js";
4+
5+
describe("frontend/components/tag-input/sanitizer", () => {
6+
it("Excerpts a string", () => {
7+
assert.deepEqual(tagInputSanitizer.customSanitizer("foo, bar, bar,"), [
8+
"foo",
9+
"bar",
10+
]);
11+
assert.deepEqual(tagInputSanitizer.customSanitizer(`["foo","bar"]`), [
12+
"foo",
13+
"bar",
14+
]);
15+
});
16+
});

0 commit comments

Comments
 (0)