Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort slash results so best match is first #296

Merged
merged 1 commit into from
Dec 17, 2024
Merged
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
36 changes: 28 additions & 8 deletions blocks/edit/prose/plugins/slashMenu/slash-menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,34 @@ export default class SlashMenu extends LitElement {
}

getFilteredItems() {
return this.items.filter(
(item) => {
const inputText = item.argument
? this.command.toLowerCase().trim().split(' ')[0]
: this.command.toLowerCase();
return item.title.toLowerCase().includes(inputText);
},
);
const searchText = this.command.toLowerCase().trim();
const inputText = searchText.split(' ')[0];

return this.items
.filter((item) => {
const itemTitle = item.title.toLowerCase();
return item.argument
? itemTitle.includes(inputText)
: itemTitle.includes(searchText);
})
.sort((a, b) => {
const aTitle = a.title.toLowerCase();
const bTitle = b.title.toLowerCase();

// Calculate score:
// 2 points for exact match at start
// 1 point for containing the search text
// 0 otherwise
const getScore = (title) => {
if (title.startsWith(searchText)) return 2;
if (title.includes(searchText)) return 1;
return 0;
};

// First sort by score, then alphabetically if scores are equal
return getScore(bTitle) - getScore(aTitle)
|| aTitle.localeCompare(bTitle);
});
}

render() {
Expand Down
Loading