import BasicWidget from "./basic_widget.js";
import server from "../services/server.js";
import linkService from "../services/link.js";
import dateNotesService from "../services/date_notes.js";
import treeCache from "../services/tree_cache.js";
import utils from "../services/utils.js";
import appContext from "../services/app_context.js";
const TPL = `
`;
const MAX_DISPLAYED_NOTES = 15;
export default class QuickSearchWidget extends BasicWidget {
doRender() {
this.$widget = $(TPL);
this.overflowing();
this.$searchString = this.$widget.find('.search-string');
this.$dropdownMenu = this.$widget.find('.dropdown-menu');
this.$dropdownToggle = this.$widget.find('.search-button');
this.$dropdownToggle.dropdown();
this.$widget.find('.input-group-append').on('shown.bs.dropdown', () => this.search());
utils.bindElShortcut(this.$searchString, 'return', () => {
this.$dropdownToggle.dropdown('show');
this.$searchString.focus();
});
utils.bindElShortcut(this.$searchString, 'down', () => {
this.$dropdownMenu.find('.dropdown-item:first').focus();
});
utils.bindElShortcut(this.$searchString, 'esc', () => {
this.$dropdownToggle.dropdown('hide');
});
return this.$widget;
}
async search() {
const searchString = this.$searchString.val().trim();
if (!searchString) {
this.$dropdownToggle.dropdown("hide");
return;
}
this.$dropdownMenu.empty();
this.$dropdownMenu.append(' Searching ... ');
const resultNoteIds = await server.get('quick-search/' + encodeURIComponent(searchString));
const displayedNoteIds = resultNoteIds.slice(0, Math.min(MAX_DISPLAYED_NOTES, resultNoteIds.length));
this.$dropdownMenu.empty();
if (displayedNoteIds.length === 0) {
this.$dropdownMenu.append('No results found ');
}
for (const note of await treeCache.getNotes(displayedNoteIds)) {
const $link = await linkService.createNoteLink(note.noteId, {showNotePath: true});
$link.addClass('dropdown-item');
$link.attr("tabIndex", "0");
$link.on('click', () => this.$dropdownToggle.dropdown("hide"));
utils.bindElShortcut($link, 'return', () => {
$link.find('a').trigger({
type: 'click',
which: 1 // left click
});
});
this.$dropdownMenu.append($link);
}
if (resultNoteIds.length > MAX_DISPLAYED_NOTES) {
this.$dropdownMenu.append(`... and ${resultNoteIds.length - MAX_DISPLAYED_NOTES} more results. `);
}
const $showInFullButton = $('')
.append($('Show in full search '));
this.$dropdownMenu.append($showInFullButton);
utils.bindElShortcut($showInFullButton, 'return', async () => {
const searchNote = await dateNotesService.createSearchNote({searchString: this.$searchString.val()});
await appContext.tabManager.getActiveTabContext().setNote(searchNote.noteId);
});
utils.bindElShortcut(this.$dropdownMenu.find('.dropdown-item:first'), 'up', () => this.$searchString.focus());
this.$dropdownToggle.dropdown('update');
}
quickSearchEvent() {
this.$searchString.focus();
}
}