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 "./NoteList.css";
import { HighlightedTokenInfo, WebSocketMessage } from "@triliumnext/commons";
import { Component, VNode } from "preact";
import { lazy, Suspense } from "preact/compat";
import { useEffect, useRef, useState } from "preact/hooks";
import FNote from "../../entities/fnote";
import type { PrintReport } from "../../print";
import { subscribeToMessages, unsubscribeToMessage as unsubscribeFromMessage } from "../../services/ws";
import {
useGetContextDataFrom, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelInt,
useNoteProperty, useParentClass, useTriliumEvent
} from "../react/hooks";
import { ViewModeMedia, ViewModeProps, resolveViewType, ViewTypeOptions } from "./interface";
import ViewModeStorage, { type ViewModeStorageType } from "./view_mode_storage";
interface NoteListProps {
note: FNote | null | undefined;
notePath: string | null | undefined;
highlightedTokens?: (string | HighlightedTokenInfo)[] | null;
/** if set to `true` then only collection-type views are displayed such as geo-map and the calendar. The original book types grid and list will be ignored. */
displayOnlyCollections?: boolean;
isEnabled: boolean;
/**
* When false, the note's content is still being loaded and the legacy list/grid views hold off
* their visibility check: without content the widget sits inside the viewport, so observing it
* now would latch it visible on effectively every note. Defaults to true.
*/
contentReady?: boolean;
ntxId: string | null | undefined;
media: ViewModeMedia;
viewType: ViewTypeOptions | undefined;
onReady?: (data: PrintReport) => void;
onProgressChanged?(progress: number): void;
showTextRepresentation?: boolean;
onOpenNote?: (noteId: string) => void;
/** Shows the collection read-only even when its note can be edited. */
isReadOnly?: boolean;
}
type LazyLoadedComponent = ((props: ViewModeProps<any>) => VNode<any> | undefined);
const ViewComponents: Record<ViewTypeOptions, { normal: LazyLoadedComponent, print?: LazyLoadedComponent }> = {
list: {
normal: lazy(() => import("./legacy/ListOrGridView.js").then(i => i.ListView)),
print: lazy(() => import("./legacy/ListPrintView.js").then(i => i.ListPrintView))
},
searchPreview: {
normal: lazy(() => import("./search/SearchResultsList.js").then(i => i.default)),
print: lazy(() => import("./legacy/ListPrintView.js").then(i => i.ListPrintView))
},
grid: {
normal: lazy(() => import("./legacy/ListOrGridView.js").then(i => i.GridView)),
},
geoMap: {
normal: lazy(() => import("./geomap/index.js")),
},
calendar: {
normal: lazy(() => import("./calendar/index.js"))
},
table: {
normal: lazy(() => import("./table/index.js")),
print: lazy(() => import("./table/TablePrintView.js"))
},
board: {
normal: lazy(() => import("./board/index.js"))
},
presentation: {
normal: lazy(() => import("./presentation/index.js"))
},
dashboard: {
normal: lazy(() => import("./dashboard/index.js"))
}
};
export default function NoteList(props: Pick<NoteListProps, "displayOnlyCollections" | "media" | "onReady" | "onProgressChanged">) {
const { note, noteContext, notePath, ntxId, viewScope } = useNoteContext();
const viewType = useNoteViewType(note);
const noteType = useNoteProperty(note, "type");
const contentLoad = useGetContextDataFrom(noteContext, "contentLoad");
const [ enabled, setEnabled ] = useState(noteContext?.hasNoteList());
useEffect(() => {
setEnabled(noteContext?.hasNoteList());
}, [ note, noteContext, viewType, viewScope?.viewMode, noteType ]);
return <CustomNoteList viewType={viewType} note={note} isEnabled={!!enabled} notePath={notePath} ntxId={ntxId}
contentReady={contentLoad?.state !== "loading"} {...props} />;
}
export function SearchNoteList(props: Omit<NoteListProps, "isEnabled" | "viewType">) {
return <EmbeddedNoteList {...props} showTextRepresentation />;
}
/**
* Mounts a collection — a book or an (already-executed) saved search — as a live, prop-driven note
* list, picking the view type from the note's `viewType` label. Unlike {@link NoteList} it reads no
* note context, so it can be embedded outside the note detail (e.g. dashboard tiles, included notes).
*/
export function EmbeddedNoteList(props: Omit<NoteListProps, "isEnabled" | "viewType">) {
const viewType = useNoteViewType(props.note);
return <CustomNoteList {...props} isEnabled={true} viewType={viewType} />;
}
export function CustomNoteList({ note, viewType, isEnabled: shouldEnable, contentReady = true, notePath, highlightedTokens, displayOnlyCollections, ntxId, onReady, onProgressChanged, media, ...restProps }: NoteListProps) {
const widgetRef = useRef<HTMLDivElement>(null);
const noteIds = useNoteIds(shouldEnable ? note : null, viewType, ntxId);
const isFullHeight = (viewType && viewType !== "list" && viewType !== "grid" && viewType !== "searchPreview");
const [ isIntersecting, setIsIntersecting ] = useState(false);
const shouldRender = shouldRenderNoteList(note, viewType, isIntersecting, media);
const isEnabled = (note && shouldEnable && !!viewType && shouldRender);
useParentClass(widgetRef, "list-full-height", !!(isFullHeight && isEnabled));
useEffect(() => {
if (isFullHeight || displayOnlyCollections || note?.type === "book") {
// Double role: no need to check if the note list is visible if the view is full-height or book, but also prevent legacy views if `displayOnlyCollections` is true.
return;
}
if (!contentReady) {
// Drop any previous latch and wait for the load to finish before observing — a note
// switch reports "loading" again, so this also resets the latch across note switches.
setIsIntersecting(false);
return;
}
const observer = new IntersectionObserver(
(entries) => {
// The first callback fires immediately after observe() and reports false while the
// widget is hidden (background tab) or below the viewport, so only latch-and-stop
// once the widget actually becomes visible (#7901).
if (entries[0].isIntersecting) {
setIsIntersecting(true);
observer.disconnect();
}
},
{
rootMargin: "50px",
threshold: 0.1
}
);
// there seems to be a race condition on Firefox which triggers the observer only before the widget is visible
// (intersection is false). https://github.com/zadam/trilium/issues/4165
const observeTimeout = setTimeout(() => widgetRef.current && observer.observe(widgetRef.current), 10);
return () => {
clearTimeout(observeTimeout);
observer.disconnect();
};
}, [ widgetRef, isFullHeight, displayOnlyCollections, note, contentReady ]);
// Preload the configuration.
let props: ViewModeProps<any> | undefined | null = null;
const viewModeConfig = useViewModeConfig(note, viewType);
if (note && notePath && viewModeConfig) {
props = {
note, noteIds, notePath, ntxId,
highlightedTokens,
media,
viewConfig: viewModeConfig.config,
saveConfig: viewModeConfig.storeFn,
onReady: onReady ?? (() => {}),
onProgressChanged: onProgressChanged ?? (() => {}),
...restProps
};
}
const ComponentToRender = viewType && props && isEnabled && (
props.media === "print"
? ViewComponents[viewType].print ?? ViewComponents[viewType].normal
: ViewComponents[viewType].normal
);
return (
<div ref={widgetRef} className={`note-list-widget component ${isFullHeight && isEnabled ? "full-height" : ""}`}>
{ComponentToRender && props && (
<div className="note-list-widget-content">
<Suspense fallback="">
<ComponentToRender {...props} />
</Suspense>
</div>
)}
</div>
);
}
export function useNoteViewType(note?: FNote | null): ViewTypeOptions | undefined {
const [ viewType ] = useNoteLabel(note, "viewType");
return resolveViewType(note, viewType);
}
/**
* Whether a view is drawn yet. A full-height view, or a book's, is drawn at once; a list waits until
* it scrolls into view. A print page has nothing on screen to scroll into, so it draws its results
* for the paper.
*/
export function shouldRenderNoteList(
note: FNote | null | undefined,
viewType: ViewTypeOptions | undefined,
isIntersecting: boolean,
media: ViewModeMedia
) {
const isFullHeight = viewType && viewType !== "list" && viewType !== "grid" && viewType !== "searchPreview";
return !!(isFullHeight || isIntersecting || note?.type === "book" || media === "print");
}
export function useNoteIds(note: FNote | null | undefined, viewType: ViewTypeOptions | undefined, ntxId: string | null | undefined) {
const [ noteIds, setNoteIds ] = useState<string[]>([]);
const [ includeArchived ] = useNoteLabelBoolean(note, "includeArchived");
const directChildrenOnly = (viewType === "list" || viewType === "searchPreview" || viewType === "grid" || viewType === "table" || viewType === "dashboard" || note?.type === "search");
const [ labelMaxDepth ] = useNoteLabelInt(note, "maxNestingDepth");
const maxDepth = (viewType === "calendar" || viewType === "geoMap" || viewType === "board")
? labelMaxDepth : undefined;
// getNoteIds can do a server round-trip (archive filtering), so concurrent refreshes may resolve
// out of order. Track the latest issued refresh so a stale one can't clobber a newer result.
const refreshSeqRef = useRef(0);
async function refreshNoteIds() {
const seq = ++refreshSeqRef.current;
const result = note ? await getNoteIds(note) : [];
if (seq !== refreshSeqRef.current) {
// A newer refresh was issued while we were awaiting; let it win.
return;
}
// getNoteIds may hand back froca's live children array, which is mutated in place when notes
// are cloned/removed. Setting that same reference would be a no-op for React (Object.is), so
// downstream effects never re-run. Copy it, and skip the update only when nothing changed.
setNoteIds(prev => sameNoteIds(prev, result) ? prev : [ ...result ]);
}
async function getNoteIds(note: FNote) {
if (directChildrenOnly) {
return await note.getChildNoteIdsWithArchiveFiltering(includeArchived);
}
return await note.getSubtreeNoteIds(includeArchived, maxDepth);
}
// Refresh on note switch.
useEffect(() => {
refreshNoteIds();
}, [ note, includeArchived, directChildrenOnly, maxDepth ]);
// Refresh on alterations to the note subtree.
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
if (note && (
loadResults.getNoteReorderings().includes(note.noteId)
|| loadResults.getBranchRows().some(branch =>
branch.parentNoteId === note.noteId
|| noteIds.includes(branch.parentNoteId ?? ""))
|| loadResults.getAttributeRows().some(attr => attr.name === "archived" && attr.noteId && noteIds.includes(attr.noteId))
)) {
refreshNoteIds();
}
});
// Refresh on search.
useTriliumEvent("searchRefreshed", ({ ntxId: eventNtxId }) => {
if (eventNtxId !== ntxId) return;
refreshNoteIds();
});
// Refresh on import.
useEffect(() => {
function onImport(message: WebSocketMessage) {
if (!("taskType" in message) || message.taskType !== "importNotes" || message.type !== "taskSucceeded") return;
const { parentNoteId, importedNoteId } = message.result;
if (!parentNoteId || !importedNoteId) return;
// Walked again from the collection, so that `maxDepth` counts from there.
if (parentNoteId === note?.noteId || noteIds.includes(parentNoteId)) {
void refreshNoteIds();
}
}
subscribeToMessages(onImport);
return () => unsubscribeFromMessage(onImport);
}, [ note, noteIds, includeArchived, directChildrenOnly, maxDepth ]);
return noteIds;
}
/** Order-sensitive equality for note-id lists, used to skip no-op `noteIds` updates. */
export function sameNoteIds(a: string[], b: string[]) {
return a.length === b.length && a.every((id, index) => id === b[index]);
}
export function useViewModeConfig<T extends object>(note: FNote | null | undefined, viewType: ViewModeStorageType | undefined) {
const [ viewConfig, setViewConfig ] = useState<{
config: T | undefined;
storeFn: (data: T) => void;
note: FNote;
viewType: ViewModeStorageType;
}>();
const storageRef = useRef<{ storage: ViewModeStorage<T>, storeFn: (data: T) => void, note: FNote, viewType: ViewModeStorageType } | undefined>(undefined);
useEffect(() => {
if (!note || !viewType) return;
setViewConfig(undefined);
const viewStorage = new ViewModeStorage<T>(note, viewType);
const storeFn = (config: T) => {
setViewConfig({ note, viewType, config, storeFn });
viewStorage.store(config);
};
const current = { storage: viewStorage, storeFn, note, viewType };
storageRef.current = current;
viewStorage.restore().then(config => {
// A restore that resolves after the note or view type changed would replace the newer
// config.
if (storageRef.current !== current) return;
setViewConfig({ note, viewType, config, storeFn });
});
}, [ note, viewType ]);
// Reload the config when the underlying attachment changes externally
// (e.g. the same view opened in another split, or synced from another instance).
// Echoes of our own saves are filtered out by the storage, so views are never handed
// a fresh config object for content they already have.
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
const current = storageRef.current;
if (!current || current.note !== note) return;
if (!loadResults.getAttachmentRows().some(att => att.ownerId === current.note.noteId && att.title === current.storage.attachmentName)) {
return;
}
current.storage.restoreIfChanged().then(config => {
if (config === undefined || storageRef.current !== current) return;
setViewConfig({ note: current.note, viewType: current.viewType, config, storeFn: current.storeFn });
});
});
// Only expose the config of the current note and view type, so a view never receives the config
// or `storeFn` of the one it replaced before the effect above resets them.
if (viewConfig?.note !== note || viewConfig?.viewType !== viewType) return undefined;
return viewConfig;
}