trilium/src/public/javascripts/services/note_autocomplete.js

87 lines
2.3 KiB
JavaScript
Raw Normal View History

import server from "./server.js";
import noteDetailService from "./note_detail.js";
async function autocompleteSource(term, cb) {
const result = await server.get('autocomplete'
+ '?query=' + encodeURIComponent(term)
+ '&currentNoteId=' + noteDetailService.getCurrentNoteId());
if (result.length === 0) {
result.push({
title: "No results",
path: ""
});
}
cb(result);
}
function showRecentNotes($el) {
$el.autocomplete("val", "");
$el.autocomplete("open");
}
function initNoteAutocomplete($el) {
if (!$el.hasClass("aa-input")) {
2018-11-06 04:12:03 +08:00
const $showRecentNotesButton = $("<div>").addClass("input-group-append").append(
$("<span>")
.addClass("input-group-text show-recent-notes-button jam jam-clock")
2018-11-06 04:12:03 +08:00
.prop("title", "Show recent notes"));
$el.after($showRecentNotesButton);
$showRecentNotesButton.click(() => showRecentNotes($el));
$el.autocomplete({
appendTo: document.querySelector('body'),
hint: false,
autoselect: true,
openOnFocus: true,
minLength: 0
}, [
{
source: autocompleteSource,
displayKey: 'title',
templates: {
suggestion: function(suggestion) {
2018-11-08 00:16:33 +08:00
return suggestion.highlighted;
}
}
}
]);
2018-11-08 00:16:33 +08:00
$el.on('autocomplete:selected', function(event, suggestion, dataset) {
$el.prop("data-selected-path", suggestion.path);
});
2018-11-13 06:34:22 +08:00
$el.on('autocomplete:closed', () => {
$el.prop("data-selected-path", "");
});
}
return $el;
}
2018-11-13 06:34:22 +08:00
$.fn.getSelectedPath = function() {
if (!$(this).val().trim()) {
return "";
}
else {
return $(this).prop("data-selected-path");
}
};
ko.bindingHandlers.noteAutocomplete = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
initNoteAutocomplete($(element));
$(element).on('autocomplete:selected', function(event, suggestion, dataset) {
2018-11-13 06:34:22 +08:00
bindingContext.$data.selectedPath = $(element).val().trim() ? suggestion.path : '';
});
}
};
export default {
initNoteAutocomplete,
showRecentNotes
}