search_pill: Prevent adding duplicate search pills.

We shouldn't show duplicate suggestions in the typeahead, but
duplicate pills were still possible by typing a term twice in
the search bar and pressing enter after each one, and this
commit prevents that from putting duplicate pills in the search
bar.
This commit is contained in:
Evy Kassirer
2025-06-01 21:27:39 -07:00
committed by Tim Abbott
parent f0210fd6e8
commit d1023660da
2 changed files with 36 additions and 0 deletions

View File

@@ -178,9 +178,13 @@ export function set_search_bar_contents(
let partial_pill = "";
const invalid_inputs = [];
const search_operator_strings = [];
const added_pills_as_input_strings = new Set(); // to prevent duplicating terms
for (const term of search_terms) {
const input = Filter.unparse([term]);
if (added_pills_as_input_strings.has(input)) {
return;
}
// If the last term looks something like `dm:`, we
// don't want to make it a pill, since it isn't isn't
@@ -215,10 +219,13 @@ export function set_search_bar_contents(
return user;
});
append_user_pill(users, pill_widget, term.operator, term.negated ?? false);
added_pills_as_input_strings.add(input);
} else if (term.operator === "search") {
// This isn't a pill, so we don't add it to `added_pills_as_input_strings`
search_operator_strings.push(input);
} else {
pill_widget.appendValue(input);
added_pills_as_input_strings.add(input);
}
}
pill_widget.clear_text();

View File

@@ -384,3 +384,32 @@ run_test("initiate_search", ({override_rewire}) => {
assert.ok(search_bar_opened);
assert.equal($("#search_query").text(), "");
});
run_test("set_search_bar_contents with duplicate pills", () => {
const duplicate_attachment_terms = [
{
negated: false,
operator: "has",
operand: "attachment",
},
{
negated: false,
operator: "has",
operand: "attachment",
},
];
search_pill.set_search_bar_contents(
duplicate_attachment_terms,
search.search_pill_widget,
false,
noop,
);
const pills = search.search_pill_widget._get_pills_for_testing();
assert.equal(pills.length, 1);
assert.deepEqual(pills[0].item, {
type: "search",
operator: "has",
operand: "attachment",
negated: false,
});
});