Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactoring ...
zadam78ea0b4ba9fc
diff --git a/src/services/note_cache.js b/src/services/note_cache.jsindex 4f4700d192..e52619f3de 100644--- a/src/services/note_cache.js+++ b/src/services/note_cache.js@@ -136,22 +136,26 @@ class Note {return this.flatTextCache;}- this.flatTextCache = this.title.toLowerCase();+ this.flatTextCache = '';for (const branch of this.parentBranches) {if (branch.prefix) {- this.flatTextCache += ' ' + branch.prefix;+ this.flatTextCache += branch.prefix + ' - ';}}+ this.flatTextCache += this.title;+for (const attr of this.attributes) {// it's best to use space as separator since spaces are filtered from the search string by the tokenization into words- this.flatTextCache += ' ' + attr.name.toLowerCase();+ this.flatTextCache += (attr.type === 'label' ? '#' : '@') + attr.name;if (attr.value) {- this.flatTextCache += ' ' + attr.value.toLowerCase();+ this.flatTextCache += '=' + attr.value;}}++ this.flatTextCache = this.flatTextCache.toLowerCase();}return this.flatTextCache;@@ -205,11 +209,11 @@ class Note {}/** @return {Note[]} */- get subtreeNotes() {+ get subtreeNotesIncludingTemplated() {const arr = [[this]];for (const childNote of this.children) {- arr.push(childNote.subtreeNotes);+ arr.push(childNote.subtreeNotesIncludingTemplated);}for (const targetRelation of this.targetRelations) {@@ -217,7 +221,7 @@ class Note {const note = targetRelation.note;if (note) {- arr.push(note.subtreeNotes);+ arr.push(note.subtreeNotesIncludingTemplated);}}}@@ -225,6 +229,17 @@ class Note {return arr.flat();}+ /** @return {Note[]} */+ get subtreeNotes() {+ const arr = [[this]];++ for (const childNote of this.children) {+ arr.push(childNote.subtreeNotes);+ }++ return arr.flat();+ }+/** @return {Note[]} - returns only notes which are templated, does not include their subtrees* in effect returns notes which are influenced by note's non-inheritable attributes */get templatedNotes() {@@ -378,9 +393,9 @@ class AndOp {this.subExpressions = subExpressions;}- execute(noteSet) {+ execute(noteSet, searchContext) {for (const subExpression of this.subExpressions) {- noteSet = subExpression.execute(noteSet);+ noteSet = subExpression.execute(noteSet, searchContext);}return noteSet;@@ -392,11 +407,11 @@ class OrOp {this.subExpressions = subExpressions;}- execute(noteSet) {+ execute(noteSet, searchContext) {const resultNoteSet = new NoteSet();for (const subExpression of this.subExpressions) {- resultNoteSet.mergeIn(subExpression.execute(noteSet));+ resultNoteSet.mergeIn(subExpression.execute(noteSet, searchContext));}return resultNoteSet;@@ -404,25 +419,25 @@ class OrOp {}class NoteSet {- constructor(arr = []) {- this.arr = arr;+ constructor(notes = []) {+ this.notes = notes;}add(note) {- this.arr.push(note);+ this.notes.push(note);}addAll(notes) {- this.arr.push(...notes);+ this.notes.push(...notes);}hasNoteId(noteId) {// TODO: optimize- return !!this.arr.find(note => note.noteId === noteId);+ return !!this.notes.find(note => note.noteId === noteId);}mergeIn(anotherNoteSet) {- this.arr = this.arr.concat(anotherNoteSet.arr);+ this.notes = this.notes.concat(anotherNoteSet.arr);}}@@ -441,7 +456,7 @@ class ExistsOp {if (noteSet.hasNoteId(note.noteId)) {if (attr.isInheritable) {- resultNoteSet.addAll(note.subtreeNotes);+ resultNoteSet.addAll(note.subtreeNotesIncludingTemplated);}else if (note.isTemplate) {resultNoteSet.addAll(note.templatedNotes);@@ -470,7 +485,7 @@ class EqualsOp {if (noteSet.hasNoteId(note.noteId) && attr.value === this.attributeValue) {if (attr.isInheritable) {- resultNoteSet.addAll(note.subtreeNotes);+ resultNoteSet.addAll(note.subtreeNotesIncludingTemplated);}else if (note.isTemplate) {resultNoteSet.addAll(note.templatedNotes);@@ -483,96 +498,124 @@ class EqualsOp {}}-async function findNotesWithExpression(expression) {- const allNoteSet = new NoteSet(Object.values(notes));+class NoteContentFulltextOp {+ constructor(tokens) {+ this.tokens = tokens;+ }- expression.execute(allNoteSet);-}+ async execute(noteSet) {+ const resultNoteSet = new NoteSet();+ const wheres = this.tokens.map(token => "note_contents.content LIKE " + utils.prepareSqlForLike('%', token, '%'));-async function findNotesWithFulltext(query, searchInContent) {- if (!query.trim().length) {- return [];+ const noteIds = await sql.getColumn(`+ SELECT notes.noteId+ FROM notes+ JOIN note_contents ON notes.noteId = note_contents.noteId+ WHERE isDeleted = 0 AND isProtected = 0 AND ${wheres.join(' AND ')}`);++ const results = [];++ for (const noteId of noteIds) {+ if (noteSet.hasNoteId(noteId) && noteId in notes) {+ resultNoteSet.add(notes[noteId]);+ }+ }++ return results;}+}- const tokens = query- .trim() // necessary because even with .split() trailing spaces are tokens which causes havoc- .toLowerCase()- .split(/[ -]/)- .filter(token => token !== '/'); // '/' is used as separator+class NoteCacheFulltextOp {+ constructor(tokens) {+ this.tokens = tokens;+ }- const cacheResults = findInNoteCache(tokens);+ execute(noteSet, searchContext) {+ const resultNoteSet = new NoteSet();- const contentResults = searchInContent ? await findInNoteContent(tokens) : [];+ const candidateNotes = this.getCandidateNotes(noteSet);- let results = cacheResults.concat(contentResults);+ for (const note of candidateNotes) {+ // autocomplete should be able to find notes by their noteIds as well (only leafs)+ if (this.tokens.length === 1 && note.noteId === this.tokens[0]) {+ this.searchDownThePath(note, [], [], resultNoteSet, searchContext);+ continue;+ }- if (hoistedNoteService.getHoistedNoteId() !== 'root') {- results = results.filter(res => res.pathArray.includes(hoistedNoteService.getHoistedNoteId()));- }+ // for leaf note it doesn't matter if "archived" label is inheritable or not+ if (note.isArchived) {+ continue;+ }- // sort results by depth of the note. This is based on the assumption that more important results- // are closer to the note root.- results.sort((a, b) => {- if (a.pathArray.length === b.pathArray.length) {- return a.title < b.title ? -1 : 1;- }+ const foundAttrTokens = [];- return a.pathArray.length < b.pathArray.length ? -1 : 1;- });+ for (const attribute of note.ownedAttributes) {+ for (const token of this.tokens) {+ if (attribute.name.toLowerCase().includes(token)+ || attribute.value.toLowerCase().includes(token)) {+ foundAttrTokens.push(token);+ }+ }+ }- const apiResults = results.slice(0, 200).map(res => {- const notePath = res.pathArray.join('/');+ for (const parentNote of note.parents) {+ const title = getNoteTitle(note.noteId, parentNote.noteId).toLowerCase();+ const foundTokens = foundAttrTokens.slice();- return {- noteId: res.noteId,- branchId: res.branchId,- path: notePath,- pathTitle: res.titleArray.join(' / '),- noteTitle: getNoteTitleFromPath(notePath)- };- });+ for (const token of this.tokens) {+ if (title.includes(token)) {+ foundTokens.push(token);+ }+ }- highlightResults(apiResults, tokens);+ if (foundTokens.length > 0) {+ const remainingTokens = tokens.filter(token => !foundTokens.includes(token));- return apiResults;-}+ this.searchDownThePath(parentNote, remainingTokens, [note.noteId], resultNoteSet, searchContext);+ }+ }+ }-/**- * Returns noteIds which have at least one matching tokens- *- * @param tokens- * @return {String[]}- */-function getCandidateNotes(tokens) {- const candidateNotes = [];+ return resultNoteSet;+ }- for (const note of Object.values(notes)) {- for (const token of tokens) {- if (note.flatText.includes(token)) {- candidateNotes.push(note);- break;+ /**+ * Returns noteIds which have at least one matching tokens+ *+ * @param {NoteSet} noteSet+ * @return {String[]}+ */+ getCandidateNotes(noteSet) {+ const candidateNotes = [];++ for (const note of noteSet.notes) {+ for (const token of this.tokens) {+ if (note.flatText.includes(token)) {+ candidateNotes.push(note);+ break;+ }}}++ return candidateNotes;}- return candidateNotes;-}+ searchDownThePath(note, tokens, path, resultNoteSet, searchContext) {+ if (tokens.length === 0) {+ const retPath = getSomePath(note, path);-function findInNoteCache(tokens) {- let results = [];+ if (retPath) {+ const noteId = retPath[retPath.length - 1];+ searchContext.noteIdToNotePath[noteId] = retPath;- const candidateNotes = getCandidateNotes(tokens);+ resultNoteSet.add(notes[noteId]);+ }- for (const note of candidateNotes) {- // autocomplete should be able to find notes by their noteIds as well (only leafs)- if (tokens.length === 1 && note.noteId === tokens[0]) {- search(note, [], [], results);- continue;+ return;}- // for leaf note it doesn't matter if "archived" label is inheritable or not- if (note.isArchived) {- continue;+ if (!note.parents.length === 0 || note.noteId === 'root') {+ return;}const foundAttrTokens = [];@@ -599,99 +642,77 @@ function findInNoteCache(tokens) {if (foundTokens.length > 0) {const remainingTokens = tokens.filter(token => !foundTokens.includes(token));- search(parentNote, remainingTokens, [note.noteId], results);+ this.searchDownThePath(parentNote, remainingTokens, path.concat([note.noteId]), resultNoteSet, searchContext);+ }+ else {+ this.searchDownThePath(parentNote, tokens, path.concat([note.noteId]), resultNoteSet, searchContext);}}}-- return results;}-async function findInNoteContent(tokens) {- const wheres = tokens.map(token => "note_contents.content LIKE " + utils.prepareSqlForLike('%', token, '%'));-- const noteIds = await sql.getColumn(`- SELECT notes.noteId- FROM notes- JOIN note_contents ON notes.noteId = note_contents.noteId- WHERE isDeleted = 0 AND isProtected = 0 AND ${wheres.join(' AND ')}`);+async function findNotesWithExpression(expression) {- const results = [];+ const hoistedNote = notes[hoistedNoteService.getHoistedNoteId()];+ const allNotes = (hoistedNote && hoistedNote.noteId !== 'root')+ ? hoistedNote.subtreeNotes+ : Object.values(notes);- for (const noteId of noteIds) {- const note = notes[noteId];+ const allNoteSet = new NoteSet(allNotes);- if (!note) {- continue;- }+ const searchContext = {+ noteIdToNotePath: {}+ };- const notePath = getSomePath(note);- const parentNoteId = notePath.length > 1 ? notePath[notePath.length - 2] : null;+ expression.execute(allNoteSet, searchContext);+}- results.push({- noteId: noteId,- branchId: getBranch(noteId, parentNoteId),- pathArray: notePath,- titleArray: getNoteTitleArrayForPath(notePath)- });+async function findNotesWithFulltext(query, searchInContent) {+ if (!query.trim().length) {+ return [];}- return results;-}+ const tokens = query+ .trim() // necessary because even with .split() trailing spaces are tokens which causes havoc+ .toLowerCase()+ .split(/[ -]/)+ .filter(token => token !== '/'); // '/' is used as separator-function search(note, tokens, path, results) {- if (tokens.length === 0) {- const retPath = getSomePath(note, path);+ const cacheResults = findInNoteCache(tokens);- if (retPath) {- const thisNoteId = retPath[retPath.length - 1];- const thisParentNoteId = retPath.length > 1 ? retPath[retPath.length - 2] : null;-- results.push({- noteId: thisNoteId,- branchId: getBranch(thisNoteId, thisParentNoteId),- pathArray: retPath,- titleArray: getNoteTitleArrayForPath(retPath)- });- }+ const contentResults = searchInContent ? await findInNoteContent(tokens) : [];- return;- }+ let results = cacheResults.concat(contentResults);- if (!note.parents.length === 0 || note.noteId === 'root') {- return;+ if (hoistedNoteService.getHoistedNoteId() !== 'root') {+ results = results.filter(res => res.pathArray.includes(hoistedNoteService.getHoistedNoteId()));}- const foundAttrTokens = [];-- for (const attribute of note.ownedAttributes) {- for (const token of tokens) {- if (attribute.name.toLowerCase().includes(token)- || attribute.value.toLowerCase().includes(token)) {- foundAttrTokens.push(token);- }+ // sort results by depth of the note. This is based on the assumption that more important results+ // are closer to the note root.+ results.sort((a, b) => {+ if (a.pathArray.length === b.pathArray.length) {+ return a.title < b.title ? -1 : 1;}- }- for (const parentNote of note.parents) {- const title = getNoteTitle(note.noteId, parentNote.noteId).toLowerCase();- const foundTokens = foundAttrTokens.slice();+ return a.pathArray.length < b.pathArray.length ? -1 : 1;+ });- for (const token of tokens) {- if (title.includes(token)) {- foundTokens.push(token);- }- }+ const apiResults = results.slice(0, 200).map(res => {+ const notePath = res.pathArray.join('/');++ return {+ noteId: res.noteId,+ branchId: res.branchId,+ path: notePath,+ pathTitle: res.titleArray.join(' / '),+ noteTitle: getNoteTitleFromPath(notePath)+ };+ });- if (foundTokens.length > 0) {- const remainingTokens = tokens.filter(token => !foundTokens.includes(token));+ highlightResults(apiResults, tokens);- search(parentNote, remainingTokens, path.concat([note.noteId]), results);- }- else {- search(parentNote, tokens, path.concat([note.noteId]), results);- }- }+ return apiResults;}function highlightResults(results, allTokens) {