Skip to content

Build your personal knowledge base with Trilium Notes

5.9 KB
Raw Blame
import { useEffect, useLayoutEffect, useState } from "preact/hooks";

import Component from "../../../components/component";
import type FNote from "../../../entities/fnote";
import type { PrintReport } from "../../../print";
import content_renderer from "../../../services/content_renderer";
import froca from "../../../services/froca";
import { waitForPendingRenders } from "../../../services/pending_renders";
import { sanitizeNoteContentHtml } from "../../../services/sanitize_content";
import type { ViewModeProps } from "../interface";
import { filterChildNotes, useFilteredNoteIds } from "./utils";

interface NotesWithContent {
    note: FNote;
    contentEl: HTMLElement;
}

export function ListPrintView({ note, noteIds: unfilteredNoteIds, onReady, onProgressChanged }: ViewModeProps<{}>) {
    const noteIds = useFilteredNoteIds(note, unfilteredNoteIds);
    const [ state, setState ] = useState<{
        notesWithContent?: NotesWithContent[],
        data?: PrintReport
    }>({});

    useLayoutEffect(() => {
        const noteIdsSet = new Set<string>();
        // A saved search prints the notes it matched, not what hangs under them: a matching folder
        // would otherwise bring its whole subtree, and a result repeated once it is also a child.
        const printsChildren = note.type !== "search";

        froca.getNotes(noteIds).then(async (notes) => {
            const noteIdsWithChildren = await note.getSubtreeNoteIds(true);
            const ignoredNoteIds: string[] = [];
            const notesWithContent: NotesWithContent[] = [];

            async function processNote(note: FNote, depth: number) {
                if (isNotePrintable(note)) {
                    const content = await content_renderer.getRenderedContent(note, {
                        trim: false,
                        noChildrenList: true,
                        // Printing preserves full embed nesting (see expandNestedEmbeds).
                        expandNestedEmbeds: true,
                        mediaEnvironment: "native",
                        // The copied content has no component tree, so a JSX render note mounts under this root.
                        parentComponent: new Component()
                    });

                    const contentEl = content.$renderedContent[0];
                    // A render note's script finishes after `getRenderedContent()`, and its
                    // output is copied below, so wait for it first.
                    await waitForPendingRenders(contentEl);

                    insertPageTitle(contentEl, note.title);
                    rewriteHeadings(contentEl, depth);
                    noteIdsSet.add(note.noteId);
                    notesWithContent.push({ note, contentEl });
                } else {
                    ignoredNoteIds.push(note.noteId);
                }

                if (onProgressChanged) {
                    onProgressChanged(notesWithContent.length / noteIdsWithChildren.length);
                }

                if (printsChildren && note.hasChildren()) {
                    const filteredChildNotes = await filterChildNotes(note);
                    for (const childNote of filteredChildNotes) {
                        await processNote(childNote, depth + 1);
                    }
                }
            }

            for (const note of notes) {
                await processNote(note, 1);
            }

            // After all notes are processed, rewrite links
            for (const { contentEl } of notesWithContent) {
                rewriteLinks(contentEl, noteIdsSet);
            }

            setState({
                notesWithContent,
                data: {
                    type: "collection",
                    ignoredNoteIds
                }
            });
        });
    }, [noteIds]);

    useEffect(() => {
        if (onReady && state?.data) {
            onReady(state.data);
        }
    }, [ state, onReady ]);

    return (
        <div class="note-list list-print-view">
            <div class="note-list-container use-tn-links">
                <h1>{note.title}</h1>

                {state.notesWithContent?.map(({ note: childNote, contentEl }) => (
                    <section id={`note-${childNote.noteId}`} class="note" dangerouslySetInnerHTML={{ __html: sanitizeNoteContentHtml(contentEl.innerHTML) }} />
                ))}
            </div>
        </div>
    );
}

function isNotePrintable(note: FNote) {
    if (!note.isContentAvailable()) {
        return false;
    }

    if (note.type === "file") {
        return false;
    }

    return true;
}

function insertPageTitle(contentEl: HTMLElement, title: string) {
    const pageTitleEl = document.createElement("h1");
    pageTitleEl.textContent = title;
    contentEl.prepend(pageTitleEl);
}

function rewriteHeadings(contentEl: HTMLElement, depth: number) {
    const headings = contentEl.querySelectorAll("h1, h2, h3, h4, h5, h6");
    for (const headingEl of headings) {
        const currentLevel = parseInt(headingEl.tagName.substring(1), 10);
        const newLevel = Math.min(currentLevel + depth, 6);
        const newHeadingEl = document.createElement(`h${newLevel}`);
        newHeadingEl.innerHTML = headingEl.innerHTML;
        headingEl.replaceWith(newHeadingEl);
    }
}

function rewriteLinks(contentEl: HTMLElement, noteIdsSet: Set<string>) {
    const linkEls = contentEl.querySelectorAll("a");
    for (const linkEl of linkEls) {
        const href = linkEl.getAttribute("href");
        if (href && href.startsWith("#root/")) {
            const noteId = href.split("/").at(-1);

            if (noteId && noteIdsSet.has(noteId)) {
                linkEl.setAttribute("href", `#note-${noteId}`);
            } else {
                // Link to note not in the print view, remove link but keep text
                const spanEl = document.createElement("span");
                spanEl.innerHTML = linkEl.innerHTML;
                linkEl.replaceWith(spanEl);
            }
        }
    }
}