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
import { getNoteIcon, HighlightedTokenInfo, isMarkdownMime, type NoteType } from "@triliumnext/commons";
import cssClassManager from "../services/css_class_manager.js";
import type { Froca } from "../services/froca-interface.js";
import noteAttributeCache from "../services/note_attribute_cache.js";
import protectedSessionHolder from "../services/protected_session_holder.js";
import server from "../services/server.js";
import utils from "../services/utils.js";
import type FAttachment from "./fattachment.js";
import type { AttributeType, default as FAttribute } from "./fattribute.js";
const LABEL = "label";
const RELATION = "relation";
export interface NotePathRecord {
isArchived: boolean;
isInHoistedSubTree: boolean;
isSearch?: boolean;
notePath: string[];
isHidden: boolean;
}
export interface FNoteRow {
noteId: string;
title: string;
isProtected: boolean;
type: NoteType;
mime: string;
blobId: string;
/** Sent only as `false`, for a virtual note whose provider cannot save content. */
isContentWritable?: boolean;
}
export interface NoteMetaData {
dateCreated: string;
utcDateCreated: string;
dateModified: string;
utcDateModified: string;
}
/**
* Note is the main node and concept in Trilium.
*/
export default class FNote {
private froca: Froca;
noteId!: string;
title!: string;
isProtected!: boolean;
type!: NoteType;
mime!: string;
// the main use case to keep this is to detect content change which should trigger refresh
blobId!: string;
/** `false` for a note that no editing mode can unlock, such as a page of the in-app help. */
isContentWritable!: boolean;
attributes: string[];
targetRelations: string[];
parents: string[];
children: string[];
parentToBranch: Record<string, string>;
childToBranch: Record<string, string>;
attachments: FAttachment[] | null;
// Managed by Froca.
searchResultsLoaded?: boolean;
highlightedTokens?: string[];
/** Structured, diacritic/regex-aware counterpart of {@link highlightedTokens}; prefer this
* when present. */
highlightedTokenInfos?: HighlightedTokenInfo[];
constructor(froca: Froca, row: FNoteRow) {
this.froca = froca;
this.attributes = [];
this.targetRelations = [];
this.parents = [];
this.children = [];
this.parentToBranch = {};
this.childToBranch = {};
this.attachments = null; // lazy loaded
this.update(row);
}
update(row: FNoteRow) {
this.noteId = row.noteId;
this.isProtected = !!row.isProtected;
this.type = row.type;
// The server can send a row without a mime or title: becca materialises "skeleton" notes
// for entities that arrive out of order during sync, and JSON serialisation drops their
// undefined mime/title. Defaulting keeps the mime predicates (isTriliumScript(), ...) and
// title consumers (escapeHtml() in the tree) from throwing until the real row syncs in.
this.title = row.title ?? "";
this.mime = row.mime ?? "";
this.blobId = row.blobId;
this.isContentWritable = row.isContentWritable ?? true;
}
addParent(parentNoteId: string, branchId: string, sort = true) {
if (parentNoteId === "none") {
return;
}
if (!this.parents.includes(parentNoteId)) {
this.parents.push(parentNoteId);
}
this.parentToBranch[parentNoteId] = branchId;
if (sort) {
this.sortParents();
}
}
addChild(childNoteId: string, branchId: string, sort = true) {
if (!(childNoteId in this.childToBranch)) {
this.children.push(childNoteId);
}
this.childToBranch[childNoteId] = branchId;
if (sort) {
this.sortChildren();
}
}
sortChildren() {
const branchIdPos: Record<string, number> = {};
for (const branchId of Object.values(this.childToBranch)) {
const notePosition = this.froca.getBranch(branchId)?.notePosition;
if (notePosition !== undefined) {
branchIdPos[branchId] = notePosition;
}
}
this.children.sort((a, b) => branchIdPos[this.childToBranch[a]] - branchIdPos[this.childToBranch[b]]);
}
isJson() {
return this.mime === "application/json";
}
async getContent() {
const blob = await this.getBlob();
return blob?.content;
}
async getJsonContent() {
const content = await this.getContent();
if (typeof content !== "string") {
console.log(`Unknown note content for '${this.noteId}'.`);
return null;
}
try {
return JSON.parse(content);
} catch (e: any) {
console.log(`Cannot parse content of note '${this.noteId}': `, e.message);
return null;
}
}
getParentBranchIds() {
return Object.values(this.parentToBranch);
}
getBranchIds() {
return this.getParentBranchIds();
}
getParentBranches() {
const branchIds = Object.values(this.parentToBranch);
return this.froca.getBranches(branchIds);
}
getBranches() {
return this.getParentBranches();
}
hasChildren() {
return this.children.length > 0;
}
getChildBranches() {
// don't use Object.values() to guarantee order
const branchIds = this.children.map((childNoteId) => this.childToBranch[childNoteId]);
return this.froca.getBranches(branchIds);
}
getParentNoteIds() {
return this.parents;
}
getParentNotes() {
return this.froca.getNotesFromCache(this.parents);
}
/**
* The parent notes that make this note a clone: the share root, the bookmarks and saved
* searches also hold the note as a child, but the tree does not count them.
*/
getRealParentNotes() {
return this.getParentNotes().filter((parent) =>
parent.noteId !== "_share" && parent.noteId !== "_lbBookmarks" && parent.type !== "search");
}
// will sort the parents so that non-search & non-archived are first and archived at the end
// this is done so that non-search & non-archived paths are always explored as first when looking for a note path
sortParents() {
this.parents.sort((aNoteId, bNoteId) => {
const aBranchId = this.parentToBranch[aNoteId];
if (aBranchId && aBranchId.startsWith("virt-")) {
return 1;
}
const aNote = this.froca.getNoteFromCache(aNoteId);
if (!aNote || aNote.isArchived || aNote.isHiddenCompletely()) {
return 1;
}
return aNoteId < bNoteId ? -1 : 1;
});
}
get isArchived() {
return this.hasAttribute("label", "archived");
}
get isMetadataReadOnly() {
return utils.isLaunchBarConfig(this.noteId)
|| this.noteId.startsWith("_help_")
|| this.noteId.startsWith("_options");
}
getChildNoteIds() {
return this.children;
}
async getChildNoteIdsWithArchiveFiltering(includeArchived = false) {
const isHiddenNote = this.noteId.startsWith("_");
const isSearchNote = this.type === "search";
if (!includeArchived && !isHiddenNote && !isSearchNote) {
const query = `note.parents.noteId="${this.noteId}" #!archived`;
const unorderedIds = new Set(await this.froca.searchNoteIds(query, this.noteId));
const results: string[] = [];
for (const id of this.children) {
if (unorderedIds.has(id)) {
results.push(id);
}
}
return results;
}
return this.children;
}
async getSubtreeNoteIds(includeArchived = false, maxDepth = -1) {
const noteIds: (string | string[])[] = [];
for (const child of await this.getChildNotes()) {
if (child.isArchived && !includeArchived) continue;
noteIds.push(child.noteId);
if (maxDepth !== 0) {
noteIds.push(await child.getSubtreeNoteIds(includeArchived, maxDepth - 1));
}
}
return noteIds.flat();
}
async getSubtreeNotes() {
const noteIds = await this.getSubtreeNoteIds();
return (await this.froca.getNotes(noteIds));
}
async getChildNotes() {
return await this.froca.getNotes(this.children);
}
async getAttachments() {
if (!this.attachments) {
this.attachments = await this.froca.getAttachmentsForNote(this.noteId);
}
return this.attachments;
}
async getAttachmentsByRole(role: string) {
return (await this.getAttachments()).filter((attachment) => attachment.role === role);
}
async getAttachmentById(attachmentId: string) {
const attachments = await this.getAttachments();
return attachments.find((att) => att.attachmentId === attachmentId);
}
isEligibleForConversionToAttachment() {
if (this.type !== "image" || !this.isContentAvailable() || this.hasChildren() || this.getParentBranches().length !== 1) {
return false;
}
const targetRelations = this.getTargetRelations().filter((relation) => relation.name === "imageLink");
if (targetRelations.length > 1) {
return false;
}
const parentNote = this.getParentNotes()[0]; // at this point note can have only one parent
const referencingNote = targetRelations[0]?.getNote();
if (referencingNote && referencingNote !== parentNote) {
return false;
} else if (parentNote.type !== "text" || !parentNote.isContentAvailable()) {
return false;
}
return true;
}
getOwnedAttributes(type?: AttributeType, name?: string) {
const attrs = this.attributes.map((attributeId) => this.froca.attributes[attributeId]).filter(Boolean); // filter out nulls;
return this.__filterAttrs(attrs, type, name);
}
getAttributes(type?: AttributeType, name?: string) {
return this.__filterAttrs(this.__getCachedAttributes([]), type, name);
}
/**
* @private
*/
__getCachedAttributes(path: string[]): FAttribute[] {
// notes/clones cannot form tree cycles, it is possible to create attribute inheritance cycle via templates
// when template instance is a parent of template itself
if (path.includes(this.noteId)) {
console.log("Forming a path");
return [];
}
if (!(this.noteId in noteAttributeCache.attributes)) {
const newPath = [...path, this.noteId];
const attrArrs = [this.getOwnedAttributes()];
// inheritable attrs on root are typically not intended to be applied to hidden subtree #3537
if (this.noteId !== "root" && this.noteId !== "_hidden") {
for (const parentNote of this.getParentNotes()) {
// these virtual parent-child relationships are also loaded into froca
if (parentNote.type !== "search") {
attrArrs.push(parentNote.__getInheritableAttributes(newPath));
}
}
}
for (const templateAttr of attrArrs.flat().filter((attr) => attr.type === "relation" && ["template", "inherit"].includes(attr.name))) {
const templateNote = this.froca.notes[templateAttr.value];
if (templateNote && templateNote.noteId !== this.noteId) {
attrArrs.push(
templateNote
.__getCachedAttributes(newPath)
// template attr is used as a marker for templates, but it's not meant to be inherited
.filter((attr) => !(attr.type === "label" && (attr.name === "template" || attr.name === "workspaceTemplate")))
);
}
}
noteAttributeCache.attributes[this.noteId] = [];
const addedAttributeIds = new Set();
for (const attr of attrArrs.flat()) {
if (!addedAttributeIds.has(attr.attributeId)) {
addedAttributeIds.add(attr.attributeId);
noteAttributeCache.attributes[this.noteId].push(attr);
}
}
}
return noteAttributeCache.attributes[this.noteId];
}
isRoot() {
return this.noteId === "root";
}
getAllNotePaths(): string[][] {
if (this.noteId === "root") {
return [["root"]];
}
const parentNotes = this.getParentNotes().filter((note) => note.type !== "search");
const notePaths =
parentNotes.length === 1
? parentNotes[0].getAllNotePaths() // optimization for the most common case
: parentNotes.flatMap((parentNote) => parentNote.getAllNotePaths());
for (const notePath of notePaths) {
notePath.push(this.noteId);
}
return notePaths;
}
getSortedNotePathRecords(hoistedNoteId = "root", activeNotePath: string | null = null): NotePathRecord[] {
const isHoistedRoot = hoistedNoteId === "root";
// Every ancestor in a path comes out of `froca.notes`, but the last segment is this note,
// which a view can still hold after `froca_updater` drops it from the cache.
const getPathNote = (noteId: string) =>
noteId === this.noteId ? this : this.froca.notes[noteId];
const notePaths: NotePathRecord[] = this.getAllNotePaths().map((path) => ({
notePath: path,
isInHoistedSubTree: isHoistedRoot || path.includes(hoistedNoteId),
isArchived: path.some((noteId) => getPathNote(noteId).isArchived),
isSearch: path.some((noteId) => getPathNote(noteId).type === "search"),
isHidden: path.includes("_hidden")
}));
// Calculate the length of the prefix match between two arrays
const prefixMatchLength = (path: string[], target: string[]) => {
const diffIndex = path.findIndex((seg, i) => seg !== target[i]);
return diffIndex === -1 ? Math.min(path.length, target.length) : diffIndex;
};
notePaths.sort((a, b) => {
if (a.isInHoistedSubTree !== b.isInHoistedSubTree) {
return a.isInHoistedSubTree ? -1 : 1;
} else if (a.isArchived !== b.isArchived) {
return a.isArchived ? 1 : -1;
} else if (a.isHidden !== b.isHidden) {
return a.isHidden ? 1 : -1;
/* v8 ignore start -- unreachable: getAllNotePaths() filters out search-typed parents at every level, so no path can contain a search note (isSearch is always false) */
} else if (a.isSearch !== b.isSearch) {
return a.isSearch ? 1 : -1;
}
/* v8 ignore stop */
if (activeNotePath) {
// Among otherwise equal paths, the one sharing the longest prefix with the active
// note wins, so opening a clone keeps the user where they came from. The checks
// above outrank it: an active `_hidden` note must not promote a bookmark clone.
const activeSegments = activeNotePath.split("/");
const aOverlap = prefixMatchLength(a.notePath, activeSegments);
const bOverlap = prefixMatchLength(b.notePath, activeSegments);
if (bOverlap !== aOverlap) {
return bOverlap - aOverlap;
}
}
return a.notePath.length - b.notePath.length;
});
return notePaths;
}
getBestNotePath(hoistedNoteId = "root", activeNotePath: string | null = null) {
return this.getSortedNotePathRecords(hoistedNoteId, activeNotePath)[0]?.notePath;
}
getBestNotePathString(hoistedNoteId = "root") {
const notePath = this.getBestNotePath(hoistedNoteId);
return notePath?.join("/");
}
isHiddenCompletely() {
if (this.noteId === "_hidden") {
return true;
} else if (this.noteId === "root") {
return false;
}
for (const parentNote of this.getParentNotes()) {
if (parentNote.noteId === "root") {
return false;
} else if (parentNote.noteId === "_hidden" || parentNote.type === "search") {
continue;
}
if (!parentNote.isHiddenCompletely()) {
return false;
}
}
return true;
}
/**
* @private
*/
__filterAttrs(attributes: FAttribute[], type?: AttributeType, name?: string): FAttribute[] {
this.__validateTypeName(type, name);
if (!type && !name) {
return attributes;
} else if (type && name) {
return attributes.filter((attr) => attr.name === name && attr.type === type);
} else if (type) {
return attributes.filter((attr) => attr.type === type);
}
// type is falsy and the both-falsy case already returned above, so name is necessarily set here
return attributes.filter((attr) => attr.name === name);
}
__getInheritableAttributes(path: string[]) {
const attrs = this.__getCachedAttributes(path);
return attrs.filter((attr) => attr.isInheritable);
}
__validateTypeName(type?: string, name?: string) {
if (type && type !== "label" && type !== "relation") {
throw new Error(`Unrecognized attribute type '${type}'. Only 'label' and 'relation' are possible values.`);
}
if (name) {
const firstLetter = name.charAt(0);
if (firstLetter === "#" || firstLetter === "~") {
throw new Error(`Detect '#' or '~' in the attribute's name. In the API, attribute names should be set without these characters.`);
}
}
}
getOwnedLabels(name?: string) {
return this.getOwnedAttributes(LABEL, name);
}
getLabels(name: string) {
return this.getAttributes(LABEL, name);
}
getIcon() {
const iconClassLabels = this.getLabels("iconClass");
const workspaceIconClass = this.getWorkspaceIconClass();
const icon = getNoteIcon({
noteId: this.noteId,
type: this.type,
mime: this.mime,
iconClass: iconClassLabels.length > 0 ? iconClassLabels[0].value : undefined,
workspaceIconClass,
isFolder: this.isFolder.bind(this),
getLabelValue: this.getLabelValue.bind(this)
});
return `tn-icon ${icon}`;
}
getColorClass() {
const color = this.getLabelValue("color");
return cssClassManager.createClassForColor(color);
}
isFolder() {
if (this.isLabelTruthy("subtreeHidden")) return false;
if (this.type === "search") return true;
return this.getFilteredChildBranches().length > 0;
}
getFilteredChildBranches() {
const childBranches = this.getChildBranches();
if (!childBranches) {
console.error(`No children for '${this.noteId}'. This shouldn't happen.`);
return [];
}
// we're not checking hideArchivedNotes since that would mean we need to lazy load the child notes
// which would seriously slow down everything.
// we check this flag only once user chooses to expand the parent. This has the negative consequence that
// note may appear as a folder but not contain any children when all of them are archived
return childBranches;
}
getOwnedRelations(name: string) {
return this.getOwnedAttributes(RELATION, name);
}
getRelations(name?: string) {
return this.getAttributes(RELATION, name);
}
hasAttribute(type: AttributeType, name: string) {
const attributes = this.getAttributes();
return attributes.some((attr) => attr.name === name && attr.type === type);
}
hasOwnedAttribute(type: AttributeType, name: string) {
return !!this.getOwnedAttribute(type, name);
}
getOwnedAttribute(type: AttributeType, name: string) {
const attributes = this.getOwnedAttributes();
return attributes.find((attr) => attr.name === name && attr.type === type);
}
getAttribute(type: AttributeType, name: string) {
const attributes = this.getAttributes();
return attributes.find((attr) => attr.name === name && attr.type === type);
}
getOwnedAttributeValue(type: AttributeType, name: string) {
const attr = this.getOwnedAttribute(type, name);
return attr ? attr.value : null;
}
getAttributeValue(type: AttributeType, name: string) {
const attr = this.getAttribute(type, name);
return attr ? attr.value : null;
}
hasOwnedLabel(name: string) {
return this.hasOwnedAttribute(LABEL, name);
}
hasLabel(name: string) {
return this.hasAttribute(LABEL, name);
}
hasLabelOrDisabled(name: string) {
return this.hasLabel(name) || this.hasLabel(`disabled:${name}`);
}
isLabelTruthy(name: string) {
const label = this.getLabel(name);
if (!label) {
return false;
}
return label && label.value !== "false";
}
hasOwnedRelation(name: string) {
return this.hasOwnedAttribute(RELATION, name);
}
hasRelation(name: string) {
return this.hasAttribute(RELATION, name);
}
getOwnedLabel(name: string) {
return this.getOwnedAttribute(LABEL, name);
}
getLabel(name: string) {
return this.getAttribute(LABEL, name);
}
getOwnedRelation(name: string) {
return this.getOwnedAttribute(RELATION, name);
}
getRelation(name: string) {
return this.getAttribute(RELATION, name);
}
getOwnedLabelValue(name: string) {
return this.getOwnedAttributeValue(LABEL, name);
}
getLabelValue(name: string) {
return this.getAttributeValue(LABEL, name);
}
getLabelOrRelation(nameWithPrefix: string) {
if (nameWithPrefix.startsWith("#")) {
return this.getLabelValue(nameWithPrefix.substring(1));
} else if (nameWithPrefix.startsWith("~")) {
return this.getRelationValue(nameWithPrefix.substring(1));
}
return this.getLabelValue(nameWithPrefix);
}
getOwnedRelationValue(name: string) {
return this.getOwnedAttributeValue(RELATION, name);
}
getRelationValue(name: string) {
return this.getAttributeValue(RELATION, name);
}
async getRelationTarget(name: string) {
const targets = await this.getRelationTargets(name);
return targets.length > 0 ? targets[0] : null;
}
async getRelationTargets(name: string) {
const relations = this.getRelations(name);
const targets: (FNote | null)[] = [];
for (const relation of relations) {
targets.push(await this.froca.getNote(relation.value));
}
return targets;
}
getNotesToInheritAttributesFrom() {
const relations = [...this.getRelations("template"), ...this.getRelations("inherit")];
return relations.map((rel) => this.froca.notes[rel.value]);
}
/**
* The value a note created under this one would be given for the attribute without asking for
* it, or `null` where it would be given none: a `child:`-prefixed attribute copied onto every
* new child, an inheritable attribute handed down the tree, or one lent by a template the child
* is given. Checked in that order, which is the order `getAttributes()` lists them in on the
* child itself.
*
* Mirrors `copyChildAttributes()` in trilium-core, which is where the copying happens. Two
* uses: previewing a note that does not exist yet (see GhostPin in the geo map), and telling a
* default apart from a value the user chose — what a note would be given anyway is not worth
* writing onto it, and writing it defeats the setting that would have given it.
*
* `childType` is the type the caller is about to create. A `~child:template` of another type is
* skipped by core when the type was chosen explicitly (#3015) and lends such a child nothing;
* left out, the template is taken to apply. The title is not answered for: `#titleTemplate` is
* evaluated by the server against values the client does not hold.
*/
getAttributeValueForNewChild(type: AttributeType, name: string, childType?: NoteType) {
const copied = this.getAttributeValue(type, `child:${name}`);
if (copied !== null) {
return copied;
}
const inherited = this.getAttributes(type, name).find((attr) => attr.isInheritable);
if (inherited) {
return inherited.value;
}
for (const template of this.__getTemplatesForNewChild(childType)) {
const value = template.getAttributeValue(type, name);
if (value !== null) {
return value;
}
}
return null;
}
/**
* @param name - label name
* @returns the label value a note created under this one would be given, or null
*/
getLabelValueForNewChild(name: string, childType?: NoteType) {
return this.getAttributeValueForNewChild(LABEL, name, childType);
}
/**
* The templates a note created under this one would be given: the target of a `~child:template`
* copied onto it, and the targets of the inheritable `~template` / `~inherit` it inherits.
*
* @private
*/
__getTemplatesForNewChild(childType?: NoteType) {
const templates: FNote[] = [];
for (const attr of this.getAttributes(RELATION)) {
const isCopied = attr.name === "child:template";
const isHandedDown = attr.isInheritable && ["template", "inherit"].includes(attr.name);
if (!isCopied && !isHandedDown) {
continue;
}
const template = this.froca.notes[attr.value];
if (!template || (isCopied && childType && template.type !== childType)) {
continue;
}
templates.push(template);
}
return templates;
}
getPromotedDefinitionAttributes() {
if (this.isLabelTruthy("hidePromotedAttributes")) {
return [];
}
const promotedAttrs = this.getAttributeDefinitions()
.filter((attr) => {
const def = attr.getDefinition();
return def && def.isPromoted;
});
// attrs are not resorted if position changes after the initial load
promotedAttrs.sort((a, b) => {
if (a.noteId === b.noteId) {
return a.position < b.position ? -1 : 1;
}
// inherited promoted attributes should stay grouped: https://github.com/zadam/trilium/issues/3761
return a.noteId < b.noteId ? -1 : 1;
});
return promotedAttrs;
}
getAttributeDefinitions() {
const definitions: FAttribute[] = [];
const seenNames = new Set<string>();
for (const attr of this.getAttributes()) {
if (!attr.isDefinition() || seenNames.has(attr.name)) {
continue;
}
seenNames.add(attr.name);
definitions.push(attr);
}
return definitions;
}
hasAncestor(ancestorNoteId: string, followTemplates = false, visitedNoteIds: Set<string> | null = null) {
if (this.noteId === ancestorNoteId) {
return true;
}
if (!visitedNoteIds) {
visitedNoteIds = new Set();
} else if (visitedNoteIds.has(this.noteId)) {
// to avoid infinite cycle when template is descendent of the instance
return false;
}
visitedNoteIds.add(this.noteId);
if (followTemplates) {
for (const templateNote of this.getNotesToInheritAttributesFrom()) {
if (templateNote.hasAncestor(ancestorNoteId, followTemplates, visitedNoteIds)) {
return true;
}
}
}
for (const parentNote of this.getParentNotes()) {
if (parentNote.hasAncestor(ancestorNoteId, followTemplates, visitedNoteIds)) {
return true;
}
}
return false;
}
isInHiddenSubtree() {
return this.noteId === "_hidden" || this.hasAncestor("_hidden");
}
invalidateAttributeCache() {}
getTargetRelations() {
return this.targetRelations.map((attributeId) => this.froca.attributes[attributeId]);
}
async getTargetRelationSourceNotes() {
const targetRelations = this.getTargetRelations();
return await this.froca.getNotes(targetRelations.map((tr) => tr.noteId));
}
async getNoteComplement() {
return this.getBlob();
}
getBlob() {
return this.froca.getBlob("notes", this.noteId);
}
toString() {
return `Note(noteId=${this.noteId}, title=${this.title})`;
}
get dto(): Omit<FNote, "froca"> {
const dto = Object.assign({}, this) as any;
delete dto.froca;
return dto;
}
getCssClass() {
const labels = this.getLabels("cssClass");
return labels.map((l) => l.value).join(" ");
}
getWorkspaceIconClass() {
const labels = this.getLabels("workspaceIconClass");
return labels.length > 0 ? labels[0].value : "";
}
getWorkspaceTabBackgroundColor() {
const labels = this.getLabels("workspaceTabBackgroundColor");
return labels.length > 0 ? labels[0].value : "";
}
isJavaScript() {
return (
(this.type === "code" || this.type === "file" || this.type === "launcher") &&
(this.mime.startsWith("application/javascript") || this.mime === "application/x-javascript" || this.mime === "text/javascript")
);
}
isJsx() {
return (this.type === "code" && this.mime === "text/jsx");
}
isHtml() {
return (this.type === "code" || this.type === "file" || this.type === "render") && this.mime === "text/html";
}
getScriptEnv() {
if (this.isHtml() || (this.isJavaScript() && this.mime.endsWith("env=frontend")) || this.isJsx()) {
return "frontend";
}
if (this.type === "render") {
return "frontend";
}
if (this.isJavaScript() && this.mime.endsWith("env=backend")) {
return "backend";
}
return null;
}
async executeScript() {
if (!(this.isJavaScript() || this.isJsx())) {
throw new Error(`Note ${this.noteId} is of type ${this.type} and mime ${this.mime} and thus cannot be executed`);
}
const env = this.getScriptEnv();
if (env === "frontend") {
const { default: bundleService } = await import("../services/bundle.js");
return await bundleService.getAndExecuteBundle(this.noteId);
} else if (env === "backend") {
const { runBackendScript } = await import("../services/backend_scripting.js");
await runBackendScript(this.noteId);
} else {
throw new Error(`Unrecognized env type ${env} for note ${this.noteId}`);
}
}
isShared() {
for (const parentNoteId of this.parents) {
if (parentNoteId === "root" || parentNoteId === "none") {
continue;
}
const parentNote = this.froca.notes[parentNoteId];
if (!parentNote || parentNote.type === "search") {
continue;
}
if (parentNote.noteId === "_share" || parentNote.isShared()) {
return true;
}
}
return false;
}
isContentAvailable() {
return !this.isProtected || protectedSessionHolder.isProtectedSessionAvailable();
}
isLaunchBarConfig() {
return this.type === "launcher" || utils.isLaunchBarConfig(this.noteId);
}
isOptions() {
return this.noteId.startsWith("_options");
}
isTriliumSqlite() {
return this.mime === "text/x-sqlite;schema=trilium";
}
isMarkdown() {
return this.type === "code" && isMarkdownMime(this.mime);
}
isIconPack() {
// Icon-pack manifests exist both as JSON `code` notes (created manually per the docs) and as
// `file` notes (produced by the icon-pack builder and shipped in distributable zips). Disabled
// packs (#disabled:iconPack, e.g. from a safe import) still preview so the user can inspect them.
return (this.type === "code" || this.type === "file") && this.mime === "application/json" && this.hasLabelOrDisabled("iconPack");
}
isTriliumScript() {
return this.mime.startsWith("application/javascript");
}
isSvg() {
return this.mime === "image/svg+xml";
}
async getMetadata() {
return await server.get<NoteMetaData>(`notes/${this.noteId}/metadata`);
}
}