trilium/src/public/javascripts/dialogs/add_link.js

87 lines
2.3 KiB
JavaScript
Raw Normal View History

import linkService from '../services/link.js';
import noteDetailService from '../services/note_detail.js';
import treeUtils from '../services/tree_utils.js';
import noteAutocompleteService from "../services/note_autocomplete.js";
import utils from "../services/utils.js";
const $dialog = $("#add-link-dialog");
const $form = $("#add-link-form");
2019-11-06 06:11:25 +08:00
const $autoComplete = $("#add-link-note-autocomplete");
const $linkTitle = $("#link-title");
2019-11-06 05:40:44 +08:00
const $addLinkTitleFormGroup = $("#add-link-title-form-group");
2017-11-05 05:03:15 +08:00
2019-11-06 05:40:44 +08:00
export async function showDialog() {
utils.closeActiveDialog();
2019-11-06 05:40:44 +08:00
$addLinkTitleFormGroup.toggle(!hasSelection());
2017-12-22 10:54:25 +08:00
2019-11-06 05:40:44 +08:00
glob.activeDialog = $dialog;
$dialog.modal();
$autoComplete.val('').focus();
$linkTitle.val('');
async function setDefaultLinkTitle(noteId) {
const noteTitle = await treeUtils.getNoteTitle(noteId);
$linkTitle.val(noteTitle);
}
2018-11-08 00:16:33 +08:00
noteAutocompleteService.initNoteAutocomplete($autoComplete);
2018-11-08 00:16:33 +08:00
$autoComplete.on('autocomplete:selected', function(event, suggestion, dataset) {
if (!suggestion.path) {
return false;
}
2018-11-08 00:16:33 +08:00
const noteId = treeUtils.getNoteIdFromNotePath(suggestion.path);
2018-11-08 00:16:33 +08:00
if (noteId) {
setDefaultLinkTitle(noteId);
}
});
2018-11-08 00:16:33 +08:00
$autoComplete.on('autocomplete:cursorchanged', function(event, suggestion, dataset) {
const noteId = treeUtils.getNoteIdFromNotePath(suggestion.path);
2018-11-08 00:16:33 +08:00
setDefaultLinkTitle(noteId);
});
2018-11-08 00:16:33 +08:00
noteAutocompleteService.showRecentNotes($autoComplete);
}
$form.submit(() => {
2018-11-08 00:16:33 +08:00
const notePath = $autoComplete.getSelectedPath();
if (notePath) {
2019-11-06 05:40:44 +08:00
const linkTitle = $linkTitle.val();
2017-12-22 10:54:25 +08:00
2019-11-06 05:40:44 +08:00
$dialog.modal('hide');
2017-12-22 10:54:25 +08:00
2019-11-06 05:40:44 +08:00
const linkHref = '#' + notePath;
const editor = noteDetailService.getActiveEditor();
2018-05-26 22:04:40 +08:00
2019-11-06 05:40:44 +08:00
if (hasSelection()) {
editor.execute('link', linkHref);
}
2019-11-06 05:40:44 +08:00
else {
linkService.addLinkToEditor(linkTitle, linkHref);
}
2017-12-22 10:54:25 +08:00
2019-11-06 05:40:44 +08:00
editor.editing.view.focus();
}
2018-11-08 00:16:33 +08:00
else {
console.error("No path to add link.");
}
return false;
});
2018-05-26 22:04:40 +08:00
// returns true if user selected some text, false if there's no selection
function hasSelection() {
const model = noteDetailService.getActiveEditor().model;
2018-05-26 22:04:40 +08:00
const selection = model.document.selection;
return !selection.isCollapsed;
2019-11-06 05:40:44 +08:00
}