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

95 lines
2.5 KiB
JavaScript
Raw Normal View History

2018-03-28 10:42:46 +08:00
import libraryLoader from "./library_loader.js";
import noteDetailService from './note_detail.js';
import treeService from './tree.js';
import attributeService from "./attributes.js";
2018-11-08 17:30:35 +08:00
const $component = $('#note-detail-text');
let textEditor = null;
2018-03-28 09:46:38 +08:00
async function show() {
if (!textEditor) {
2018-03-28 10:42:46 +08:00
await libraryLoader.requireLibrary(libraryLoader.CKEDITOR);
2019-03-05 05:36:46 +08:00
// CKEditor since version 12 needs the element to be visible before initialization. At the same time
// we want to avoid flicker - i.e. show editor only once everything is ready. That's why we have separate
// display of $component in both branches.
$component.show();
// textEditor might have been initialized during previous await so checking again
// looks like double initialization can freeze CKEditor pretty badly
if (!textEditor) {
2019-03-05 05:39:44 +08:00
textEditor = await BalloonEditor.create($component[0], {
placeholder: "Type the content of your note here ..."
});
onNoteChange(noteDetailService.noteChanged);
}
}
textEditor.isReadOnly = await isReadOnly();
2018-11-08 17:30:35 +08:00
$component.show();
2019-03-05 05:36:46 +08:00
textEditor.setData(noteDetailService.getActiveNote().content);
}
function getContent() {
let content = textEditor.getData();
// if content is only tags/whitespace (typically <p>&nbsp;</p>), then just make it empty
// this is important when setting new note to code
if (jQuery(content).text().trim() === '' && !content.includes("<img")) {
content = '';
}
return content;
}
async function isReadOnly() {
const attributes = await attributeService.getAttributes();
return attributes.some(attr => attr.type === 'label' && attr.name === 'readOnly');
}
function focus() {
2018-11-08 17:30:35 +08:00
$component.focus();
}
function getEditor() {
return textEditor;
}
function onNoteChange(func) {
textEditor.model.document.on('change:data', func);
}
$component.on("dblclick", "img", e => {
const $img = $(e.target);
const src = $img.prop("src");
const match = src.match(/\/api\/images\/([A-Za-z0-9]+)\//);
if (match) {
const noteId = match[1];
treeService.activateNote(noteId);
}
else {
window.open(src, '_blank');
}
});
export default {
2018-03-28 09:46:38 +08:00
show,
getEditor,
getContent,
focus,
onNoteChange,
cleanup: () => {
if (textEditor) {
textEditor.setData('');
}
},
scrollToTop: () => $component.scrollTop(0)
}