PDF.js sidebar experiments for new layout (#8212)

This commit is contained in:
Elian Doran 2026-01-01 22:49:15 +02:00 committed by GitHub
commit 63b6abdb9d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
27 changed files with 1461 additions and 30 deletions

View File

@ -473,6 +473,11 @@ type EventMappings = {
noteContextRemoved: {
ntxIds: string[];
};
contextDataChanged: {
noteContext: NoteContext;
key: string;
value: unknown;
};
exportSvg: { ntxId: string | null | undefined; };
exportPng: { ntxId: string | null | undefined; };
geoMapCreateChildNote: {

View File

@ -12,6 +12,7 @@ import server from "../services/server.js";
import treeService from "../services/tree.js";
import utils from "../services/utils.js";
import { ReactWrappedWidget } from "../widgets/basic_widget.js";
import type { HeadingContext } from "../widgets/sidebar/TableOfContents.js";
import appContext, { type EventData, type EventListener } from "./app_context.js";
import Component from "./component.js";
@ -22,6 +23,26 @@ export interface SetNoteOpts {
export type GetTextEditorCallback = (editor: CKTextEditor) => void;
export interface NoteContextDataMap {
toc: HeadingContext;
pdfPages: {
totalPages: number;
currentPage: number;
scrollToPage(page: number): void;
requestThumbnail(page: number): void;
};
pdfAttachments: {
attachments: Array<{ filename: string; size: number }>;
downloadAttachment(filename: string): void;
};
pdfLayers: {
layers: Array<{ id: string; name: string; visible: boolean }>;
toggleLayer(layerId: string, visible: boolean): void;
};
}
type ContextDataKey = keyof NoteContextDataMap;
class NoteContext extends Component implements EventListener<"entitiesReloaded"> {
ntxId: string | null;
hoistedNoteId: string;
@ -32,6 +53,13 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
parentNoteId?: string | null;
viewScope?: ViewScope;
/**
* Metadata storage for UI components (e.g., table of contents, PDF page list, code outline).
* This allows type widgets to publish data that sidebar/toolbar components can consume.
* Data is automatically cleared when navigating to a different note.
*/
private contextData: Map<string, unknown> = new Map();
constructor(ntxId: string | null = null, hoistedNoteId: string = "root", mainNtxId: string | null = null) {
super();
@ -91,6 +119,22 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
this.viewScope = opts.viewScope;
({ noteId: this.noteId, parentNoteId: this.parentNoteId } = treeService.getNoteIdAndParentIdFromUrl(resolvedNotePath));
// Clear context data when switching notes and notify subscribers
const oldKeys = Array.from(this.contextData.keys());
this.contextData.clear();
if (oldKeys.length > 0) {
// Notify subscribers asynchronously to avoid blocking navigation
window.setTimeout(() => {
for (const key of oldKeys) {
this.triggerEvent("contextDataChanged", {
noteContext: this,
key,
value: undefined
});
}
}, 0);
}
this.saveToRecentNotes(resolvedNotePath);
protectedSessionHolder.touchProtectedSessionIfNecessary(this.note);
@ -443,6 +487,52 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
return title;
}
/**
* Set metadata for this note context (e.g., table of contents, PDF pages, code outline).
* This data can be consumed by sidebar/toolbar components.
*
* @param key - Unique identifier for the data type (e.g., "toc", "pdfPages", "codeOutline")
* @param value - The data to store (will be cleared when switching notes)
*/
setContextData<K extends ContextDataKey>(key: K, value: NoteContextDataMap[K]): void {
this.contextData.set(key, value);
// Trigger event so subscribers can react
this.triggerEvent("contextDataChanged", {
noteContext: this,
key,
value
});
}
/**
* Get metadata for this note context.
*
* @param key - The data key to retrieve
* @returns The stored data, or undefined if not found
*/
getContextData<K extends ContextDataKey>(key: K): NoteContextDataMap[K] | undefined {
return this.contextData.get(key) as NoteContextDataMap[K] | undefined;
}
/**
* Check if context data exists for a given key.
*/
hasContextData(key: ContextDataKey): boolean {
return this.contextData.has(key);
}
/**
* Clear specific context data.
*/
clearContextData(key: ContextDataKey): void {
this.contextData.delete(key);
this.triggerEvent("contextDataChanged", {
noteContext: this,
key,
value: undefined
});
}
}
export function openInCurrentNoteContext(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDownEvent | React.PointerEvent<HTMLCanvasElement> | null, notePath: string, viewScope?: ViewScope) {

View File

@ -187,13 +187,15 @@ export function formatSize(size: number | null | undefined) {
return "";
}
size = Math.max(Math.round(size / 1024), 1);
if (size < 1024) {
return `${size} KiB`;
if (size === 0) {
return "0 B";
}
return `${Math.round(size / 102.4) / 10} MiB`;
const k = 1024;
const sizes = ["B", "KiB", "MiB", "GiB"];
const i = Math.floor(Math.log(size) / Math.log(k));
return `${Math.round((size / Math.pow(k, i)) * 100) / 100} ${sizes[i]}`;
}
function toObject<T, R>(array: T[], fn: (arg0: T) => [key: string, value: R]) {

View File

@ -2238,5 +2238,15 @@
"empty_button": "Hide the panel",
"toggle": "Toggle right panel",
"custom_widget_go_to_source": "Go to source code"
},
"pdf": {
"attachments_one": "{{count}} attachment",
"attachments_other": "{{count}} attachments",
"layers_one": "{{count}} layer",
"layers_other": "{{count}} layers",
"pages_one": "{{count}} page",
"pages_other": "{{count}} pages",
"pages_alt": "Page {{pageNumber}}",
"pages_loading": "Loading..."
}
}

View File

@ -1,3 +1,15 @@
interface Window {
/**
* By default, pdf.js will try to store information about the opened PDFs such as zoom and scroll position in local storage.
* The Trilium alternative is to use attachments stored at note level.
* This variable represents the direct content used by the pdf.js viewer in its local storage key, but in plain JS object format.
* The variable must be set early at startup, before pdf.js fully initializes.
*/
TRILIUM_VIEW_HISTORY_STORE?: object;
/**
* If set to true, hides the pdf.js viewer default sidebar containing the outline, page navigation, etc.
* This needs to be set early in the main method.
*/
TRILIUM_HIDE_SIDEBAR?: boolean;
}

View File

@ -4,7 +4,8 @@
*/
import { NoteType } from "@triliumnext/commons";
import { VNode, type JSX } from "preact";
import { type JSX, VNode } from "preact";
import { TypeWidgetProps } from "./type_widgets/type_widget";
/**
@ -13,7 +14,7 @@ import { TypeWidgetProps } from "./type_widgets/type_widget";
*/
export type ExtendedNoteType = Exclude<NoteType, "launcher" | "text" | "code"> | "empty" | "readOnlyCode" | "readOnlyText" | "editableText" | "editableCode" | "attachmentDetail" | "attachmentList" | "protectedSession" | "aiChat";
export type TypeWidget = ((props: TypeWidgetProps) => VNode | JSX.Element);
export type TypeWidget = ((props: TypeWidgetProps) => VNode | JSX.Element | undefined);
type NoteTypeView = () => (Promise<{ default: TypeWidget } | TypeWidget> | TypeWidget);
interface NoteTypeMapping {

View File

@ -8,7 +8,7 @@ import { MutableRef, useCallback, useContext, useDebugValue, useEffect, useLayou
import appContext, { EventData, EventNames } from "../../components/app_context";
import Component from "../../components/component";
import NoteContext from "../../components/note_context";
import NoteContext, { NoteContextDataMap } from "../../components/note_context";
import FBlob from "../../entities/fblob";
import FNote from "../../entities/fnote";
import attributes from "../../services/attributes";
@ -1207,3 +1207,92 @@ export function useContentElement(noteContext: NoteContext | null | undefined) {
return contentElement;
}
/**
* Set context data on the current note context.
* This allows type widgets to publish data (e.g., table of contents, PDF pages)
* that can be consumed by sidebar/toolbar components.
*
* Data is automatically cleared when navigating to a different note.
*
* @param key - Unique identifier for the data type (e.g., "toc", "pdfPages")
* @param value - The data to publish
*
* @example
* // In a PDF viewer widget:
* const { noteContext } = useActiveNoteContext();
* useSetContextData(noteContext, "pdfPages", pages);
*/
export function useSetContextData<K extends keyof NoteContextDataMap>(
noteContext: NoteContext | null | undefined,
key: K,
value: NoteContextDataMap[K] | undefined
) {
useEffect(() => {
if (!noteContext) return;
if (value !== undefined) {
noteContext.setContextData(key, value);
} else {
noteContext.clearContextData(key);
}
return () => {
noteContext.clearContextData(key);
};
}, [noteContext, key, value]);
}
/**
* Get context data from the active note context.
* This is typically used in sidebar/toolbar components that need to display
* data published by type widgets.
*
* The component will automatically re-render when the data changes.
*
* @param key - The data key to retrieve (e.g., "toc", "pdfPages")
* @returns The current data, or undefined if not available
*
* @example
* // In a Table of Contents sidebar widget:
* function TableOfContents() {
* const headings = useGetContextData<Heading[]>("toc");
* if (!headings) return <div>No headings available</div>;
* return <ul>{headings.map(h => <li>{h.text}</li>)}</ul>;
* }
*/
export function useGetContextData<K extends keyof NoteContextDataMap>(key: K): NoteContextDataMap[K] | undefined {
const { noteContext } = useActiveNoteContext();
return useGetContextDataFrom(noteContext, key);
}
/**
* Get context data from a specific note context (not necessarily the active one).
*
* @param noteContext - The specific note context to get data from
* @param key - The data key to retrieve
* @returns The current data, or undefined if not available
*/
export function useGetContextDataFrom<K extends keyof NoteContextDataMap>(
noteContext: NoteContext | null | undefined,
key: K
): NoteContextDataMap[K] | undefined {
const [data, setData] = useState<NoteContextDataMap[K] | undefined>(() =>
noteContext?.getContextData(key)
);
// Update initial value when noteContext changes
useEffect(() => {
setData(noteContext?.getContextData(key));
}, [noteContext, key]);
// Subscribe to changes via Trilium event system
useTriliumEvent("contextDataChanged", ({ noteContext: eventNoteContext, key: changedKey, value }) => {
if (eventNoteContext === noteContext && changedKey === key) {
setData(value as NoteContextDataMap[K]);
}
});
return data;
}

View File

@ -15,6 +15,9 @@ import { useActiveNoteContext, useLegacyWidget, useNoteProperty, useTriliumEvent
import Icon from "../react/Icon";
import LegacyRightPanelWidget from "../right_panel_widget";
import HighlightsList from "./HighlightsList";
import PdfAttachments from "./pdf/PdfAttachments";
import PdfLayers from "./pdf/PdfLayers";
import PdfPages from "./pdf/PdfPages";
import RightPanelWidget from "./RightPanelWidget";
import TableOfContents from "./TableOfContents";
@ -57,13 +60,27 @@ export default function RightPanelContainer({ widgetsByParent }: { widgetsByPare
function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent) {
const { note } = useActiveNoteContext();
const noteType = useNoteProperty(note, "type");
const noteMime = useNoteProperty(note, "mime");
const [ highlightsList ] = useTriliumOptionJson<string[]>("highlightsList");
const isPdf = noteType === "file" && noteMime === "application/pdf";
if (!rightPaneVisible) return [];
const definitions: RightPanelWidgetDefinition[] = [
{
el: <TableOfContents />,
enabled: (noteType === "text" || noteType === "doc"),
enabled: (noteType === "text" || noteType === "doc" || isPdf),
},
{
el: <PdfPages />,
enabled: isPdf,
},
{
el: <PdfAttachments />,
enabled: isPdf,
},
{
el: <PdfLayers />,
enabled: isPdf,
},
{
el: <HighlightsList />,

View File

@ -29,6 +29,11 @@
hyphens: auto;
}
.toc li.active > .item-content {
font-weight: bold;
color: var(--main-text-color);
}
.toc > ol {
--toc-depth-level: 1;
}

View File

@ -6,7 +6,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { t } from "../../services/i18n";
import { randomString } from "../../services/utils";
import { useActiveNoteContext, useContentElement, useIsNoteReadOnly, useNoteProperty, useTextEditor } from "../react/hooks";
import { useActiveNoteContext, useContentElement, useGetContextData, useIsNoteReadOnly, useNoteProperty, useTextEditor } from "../react/hooks";
import Icon from "../react/Icon";
import RightPanelWidget from "./RightPanelWidget";
@ -21,29 +21,50 @@ interface HeadingsWithNesting extends RawHeading {
children: HeadingsWithNesting[];
}
export interface HeadingContext {
scrollToHeading(heading: RawHeading): void;
headings: RawHeading[];
activeHeadingId?: string | null;
}
export default function TableOfContents() {
const { note, noteContext } = useActiveNoteContext();
const noteType = useNoteProperty(note, "type");
const noteMime = useNoteProperty(note, "mime");
const { isReadOnly } = useIsNoteReadOnly(note, noteContext);
return (
<RightPanelWidget id="toc" title={t("toc.table_of_contents")} grow>
{((noteType === "text" && isReadOnly) || (noteType === "doc")) && <ReadOnlyTextTableOfContents />}
{noteType === "text" && !isReadOnly && <EditableTextTableOfContents />}
{noteType === "file" && noteMime === "application/pdf" && <PdfTableOfContents />}
</RightPanelWidget>
);
}
function AbstractTableOfContents<T extends RawHeading>({ headings, scrollToHeading }: {
function PdfTableOfContents() {
const data = useGetContextData("toc");
return (
<AbstractTableOfContents
headings={data?.headings || []}
scrollToHeading={data?.scrollToHeading || (() => {})}
activeHeadingId={data?.activeHeadingId}
/>
);
}
function AbstractTableOfContents<T extends RawHeading>({ headings, scrollToHeading, activeHeadingId }: {
headings: T[];
scrollToHeading(heading: T): void;
activeHeadingId?: string | null;
}) {
const nestedHeadings = buildHeadingTree(headings);
return (
<span className="toc">
{nestedHeadings.length > 0 ? (
<ol>
{nestedHeadings.map(heading => <TableOfContentsHeading key={heading.id} heading={heading} scrollToHeading={scrollToHeading} />)}
{nestedHeadings.map(heading => <TableOfContentsHeading key={heading.id} heading={heading} scrollToHeading={scrollToHeading} activeHeadingId={activeHeadingId} />)}
</ol>
) : (
<div className="no-headings">{t("toc.no_headings")}</div>
@ -52,14 +73,16 @@ function AbstractTableOfContents<T extends RawHeading>({ headings, scrollToHeadi
);
}
function TableOfContentsHeading({ heading, scrollToHeading }: {
function TableOfContentsHeading({ heading, scrollToHeading, activeHeadingId }: {
heading: HeadingsWithNesting;
scrollToHeading(heading: RawHeading): void;
activeHeadingId?: string | null;
}) {
const [ collapsed, setCollapsed ] = useState(false);
const isActive = heading.id === activeHeadingId;
return (
<>
<li className={clsx(collapsed && "collapsed")}>
<li className={clsx(collapsed && "collapsed", isActive && "active")}>
{heading.children.length > 0 && (
<Icon
className="collapse-button"
@ -74,7 +97,7 @@ function TableOfContentsHeading({ heading, scrollToHeading }: {
</li>
{heading.children && (
<ol>
{heading.children.map(heading => <TableOfContentsHeading key={heading.id} heading={heading} scrollToHeading={scrollToHeading} />)}
{heading.children.map(heading => <TableOfContentsHeading key={heading.id} heading={heading} scrollToHeading={scrollToHeading} activeHeadingId={activeHeadingId} />)}
</ol>
)}
</>

View File

@ -0,0 +1,57 @@
.pdf-attachments-list {
width: 100%;
}
.pdf-attachment-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
cursor: pointer;
border-bottom: 1px solid var(--main-border-color);
transition: background-color 0.2s;
}
.pdf-attachment-item:hover {
background-color: var(--hover-item-background-color);
}
.pdf-attachment-item:last-child {
border-bottom: none;
}
.pdf-attachment-info {
flex: 1;
min-width: 0;
}
.pdf-attachment-filename {
font-size: 13px;
font-weight: 500;
color: var(--main-text-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pdf-attachment-size {
font-size: 11px;
color: var(--muted-text-color);
margin-top: 2px;
}
.no-attachments {
padding: 16px;
text-align: center;
color: var(--muted-text-color);
}
.pdf-attachment-item .bx {
flex-shrink: 0;
font-size: 18px;
color: var(--muted-text-color);
}
.pdf-attachment-item:hover .bx {
color: var(--main-text-color);
}

View File

@ -0,0 +1,62 @@
import "./PdfAttachments.css";
import { t } from "../../../services/i18n";
import { formatSize } from "../../../services/utils";
import { useActiveNoteContext, useGetContextData, useNoteProperty } from "../../react/hooks";
import Icon from "../../react/Icon";
import RightPanelWidget from "../RightPanelWidget";
interface AttachmentInfo {
filename: string;
size: number;
}
export default function PdfAttachments() {
const { note } = useActiveNoteContext();
const noteType = useNoteProperty(note, "type");
const noteMime = useNoteProperty(note, "mime");
const attachmentsData = useGetContextData("pdfAttachments");
if (noteType !== "file" || noteMime !== "application/pdf") {
return null;
}
if (!attachmentsData || attachmentsData.attachments.length === 0) {
return null;
}
return (
<RightPanelWidget id="pdf-attachments" title={t("pdf.attachments", { count: attachmentsData.attachments.length })}>
<div className="pdf-attachments-list">
{attachmentsData.attachments.map((attachment) => (
<PdfAttachmentItem
key={attachment.filename}
attachment={attachment}
onDownload={attachmentsData.downloadAttachment}
/>
))}
</div>
</RightPanelWidget>
);
}
function PdfAttachmentItem({
attachment,
onDownload
}: {
attachment: AttachmentInfo;
onDownload: (filename: string) => void;
}) {
const sizeText = formatSize(attachment.size);
return (
<div className="pdf-attachment-item" onClick={() => onDownload(attachment.filename)}>
<Icon icon="bx bx-paperclip" />
<div className="pdf-attachment-info">
<div className="pdf-attachment-filename">{attachment.filename}</div>
<div className="pdf-attachment-size">{sizeText}</div>
</div>
<Icon icon="bx bx-download" />
</div>
);
}

View File

@ -0,0 +1,54 @@
.pdf-layers-list {
width: 100%;
}
.pdf-layer-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
cursor: pointer;
border-bottom: 1px solid var(--main-border-color);
transition: background-color 0.2s;
}
.pdf-layer-item:hover {
background-color: var(--hover-item-background-color);
}
.pdf-layer-item:last-child {
border-bottom: none;
}
.pdf-layer-item.hidden {
opacity: 0.5;
}
.pdf-layer-name {
flex: 1;
font-size: 13px;
color: var(--main-text-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.no-layers {
padding: 16px;
text-align: center;
color: var(--muted-text-color);
}
.pdf-layer-item .bx {
flex-shrink: 0;
font-size: 18px;
color: var(--muted-text-color);
}
.pdf-layer-item:hover .bx {
color: var(--main-text-color);
}
.pdf-layer-item.visible .bx {
color: var(--main-text-color);
}

View File

@ -0,0 +1,55 @@
import "./PdfLayers.css";
import { t } from "../../../services/i18n";
import { useActiveNoteContext, useGetContextData, useNoteProperty } from "../../react/hooks";
import Icon from "../../react/Icon";
import RightPanelWidget from "../RightPanelWidget";
interface LayerInfo {
id: string;
name: string;
visible: boolean;
}
export default function PdfLayers() {
const { note } = useActiveNoteContext();
const noteType = useNoteProperty(note, "type");
const noteMime = useNoteProperty(note, "mime");
const layersData = useGetContextData("pdfLayers");
if (noteType !== "file" || noteMime !== "application/pdf") {
return null;
}
return (layersData?.layers && layersData.layers.length > 0 &&
<RightPanelWidget id="pdf-layers" title={t("pdf.layers", { count: layersData.layers.length })}>
<div className="pdf-layers-list">
{layersData.layers.map((layer) => (
<PdfLayerItem
key={layer.id}
layer={layer}
onToggle={layersData.toggleLayer}
/>
))}
</div>
</RightPanelWidget>
);
}
function PdfLayerItem({
layer,
onToggle
}: {
layer: LayerInfo;
onToggle: (layerId: string, visible: boolean) => void;
}) {
return (
<div
className={`pdf-layer-item ${layer.visible ? 'visible' : 'hidden'}`}
onClick={() => onToggle(layer.id, !layer.visible)}
>
<Icon icon={layer.visible ? "bx bx-show" : "bx bx-hide"} />
<div className="pdf-layer-name">{layer.name}</div>
</div>
);
}

View File

@ -0,0 +1,67 @@
.pdf-pages-list {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 8px;
padding: 8px;
align-content: flex-start;
}
.pdf-page-item {
display: flex;
flex-direction: column;
align-items: center;
padding: 8px;
cursor: pointer;
border: 2px solid transparent;
transition: border-color 0.2s;
box-sizing: border-box;
position: relative;
.pdf-page-number {
font-size: 12px;
margin-bottom: 4px;
color: var(--main-text-color);
position: absolute;
bottom: 1em;
left: 50%;
transform: translateX(-50%);
background-color: var(--accented-background-color);
padding: 0.2em 0.5em;
border-radius: 4px;
}
}
.pdf-page-item:hover {
background-color: var(--hover-item-background-color);
}
.pdf-page-item.active {
border-color: var(--main-border-color);
background-color: var(--active-item-background-color);
}
.pdf-page-thumbnail {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.pdf-page-thumbnail img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.pdf-page-loading {
color: var(--muted-text-color);
font-size: 11px;
}
.no-pages {
padding: 16px;
text-align: center;
color: var(--muted-text-color);
}

View File

@ -0,0 +1,111 @@
import "./PdfPages.css";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { NoteContextDataMap } from "../../../components/note_context";
import { t } from "../../../services/i18n";
import { useActiveNoteContext, useGetContextData, useNoteProperty } from "../../react/hooks";
import RightPanelWidget from "../RightPanelWidget";
export default function PdfPages() {
const { note } = useActiveNoteContext();
const noteType = useNoteProperty(note, "type");
const noteMime = useNoteProperty(note, "mime");
const pagesData = useGetContextData("pdfPages");
if (noteType !== "file" || noteMime !== "application/pdf") {
return null;
}
return (pagesData &&
<RightPanelWidget id="pdf-pages" title={t("pdf.pages", { count: pagesData?.totalPages || 0 })} grow>
<PdfPagesList key={note?.noteId} pagesData={pagesData} />
</RightPanelWidget>
);
}
function PdfPagesList({ pagesData }: { pagesData: NoteContextDataMap["pdfPages"] }) {
const [thumbnails, setThumbnails] = useState<Map<number, string>>(new Map());
const requestedThumbnails = useRef<Set<number>>(new Set());
useEffect(() => {
// Listen for thumbnail responses via custom event
function handleThumbnail(event: CustomEvent) {
const { pageNumber, dataUrl } = event.detail;
setThumbnails(prev => new Map(prev).set(pageNumber, dataUrl));
}
window.addEventListener("pdf-thumbnail", handleThumbnail as EventListener);
return () => {
window.removeEventListener("pdf-thumbnail", handleThumbnail as EventListener);
};
}, []);
const requestThumbnail = useCallback((pageNumber: number) => {
// Only request if we haven't already requested it and don't have it
if (!requestedThumbnails.current.has(pageNumber) && !thumbnails.has(pageNumber) && pagesData) {
requestedThumbnails.current.add(pageNumber);
pagesData.requestThumbnail(pageNumber);
}
}, [pagesData, thumbnails]);
if (!pagesData || pagesData.totalPages === 0) {
return <div className="no-pages">No pages available</div>;
}
const pages = Array.from({ length: pagesData.totalPages }, (_, i) => i + 1);
return (
<div className="pdf-pages-list">
{pages.map(pageNumber => (
<PdfPageItem
key={pageNumber}
pageNumber={pageNumber}
isActive={pageNumber === pagesData.currentPage}
thumbnail={thumbnails.get(pageNumber)}
onRequestThumbnail={requestThumbnail}
onPageClick={() => pagesData.scrollToPage(pageNumber)}
/>
))}
</div>
);
}
function PdfPageItem({
pageNumber,
isActive,
thumbnail,
onRequestThumbnail,
onPageClick
}: {
pageNumber: number;
isActive: boolean;
thumbnail?: string;
onRequestThumbnail(page: number): void;
onPageClick(): void;
}) {
const hasRequested = useRef(false);
useEffect(() => {
if (!thumbnail && !hasRequested.current) {
hasRequested.current = true;
onRequestThumbnail(pageNumber);
}
}, [pageNumber, thumbnail, onRequestThumbnail]);
return (
<div
className={`pdf-page-item ${isActive ? 'active' : ''}`}
onClick={onPageClick}
>
<div className="pdf-page-number">{pageNumber}</div>
<div className="pdf-page-thumbnail">
{thumbnail ? (
<img src={thumbnail} alt={t("pdf.pages_alt", { pageNumber })} />
) : (
<div className="pdf-page-loading">{t("pdf.pages_loading")}</div>
)}
</div>
</div>
);
}

View File

@ -16,7 +16,7 @@ export default function FileTypeWidget({ note, parentComponent, noteContext }: T
if (blob?.content) {
return <TextPreview content={blob.content} />;
} else if (note.mime === "application/pdf") {
return <PdfPreview blob={blob} note={note} ntxId={noteContext?.ntxId} componentId={parentComponent?.componentId} />;
return noteContext && <PdfPreview blob={blob} note={note} componentId={parentComponent?.componentId} noteContext={noteContext} />;
} else if (note.mime.startsWith("video/")) {
return <VideoPreview note={note} />;
} else if (note.mime.startsWith("audio/")) {

View File

@ -2,11 +2,12 @@ import { RefObject } from "preact";
import { useCallback, useEffect, useRef } from "preact/hooks";
import appContext from "../../../components/app_context";
import type NoteContext from "../../../components/note_context";
import FBlob from "../../../entities/fblob";
import FNote from "../../../entities/fnote";
import server from "../../../services/server";
import { useViewModeConfig } from "../../collections/NoteList";
import { useTriliumOption } from "../../react/hooks";
import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
const VARIABLE_WHITELIST = new Set([
"root-background",
@ -15,16 +16,17 @@ const VARIABLE_WHITELIST = new Set([
"main-text-color"
]);
export default function PdfPreview({ note, blob, componentId, ntxId }: {
note: FNote,
blob: FBlob | null | undefined,
export default function PdfPreview({ note, blob, componentId, noteContext }: {
note: FNote;
noteContext: NoteContext;
blob: FBlob | null | undefined;
componentId: string | undefined;
ntxId: string | null | undefined;
}) {
const iframeRef = useRef<HTMLIFrameElement>(null);
const { onLoad } = useStyleInjection(iframeRef);
const historyConfig = useViewModeConfig(note, "pdfHistory");
const [ locale ] = useTriliumOption("locale");
const [ newLayout ] = useTriliumOptionBool("newLayout");
useEffect(() => {
function handleMessage(event: MessageEvent) {
@ -36,13 +38,111 @@ export default function PdfPreview({ note, blob, componentId, ntxId }: {
if (event.data.type === "pdfjs-viewer-save-view-history" && event.data?.data) {
historyConfig?.storeFn(JSON.parse(event.data.data));
}
if (event.data.type === "pdfjs-viewer-toc") {
if (event.data.data) {
// Convert PDF outline to HeadingContext format
const headings = convertPdfOutlineToHeadings(event.data.data);
noteContext.setContextData("toc", {
headings,
activeHeadingId: null,
scrollToHeading: (heading) => {
iframeRef.current?.contentWindow?.postMessage({
type: "trilium-scroll-to-heading",
headingId: heading.id
}, window.location.origin);
}
});
} else {
// No ToC available, use empty headings
noteContext.setContextData("toc", {
headings: [],
activeHeadingId: null,
scrollToHeading: () => {}
});
}
}
if (event.data.type === "pdfjs-viewer-active-heading") {
const currentToc = noteContext.getContextData("toc");
if (currentToc) {
noteContext.setContextData("toc", {
...currentToc,
activeHeadingId: event.data.headingId
});
}
}
if (event.data.type === "pdfjs-viewer-page-info") {
noteContext.setContextData("pdfPages", {
totalPages: event.data.totalPages,
currentPage: event.data.currentPage,
scrollToPage: (page: number) => {
iframeRef.current?.contentWindow?.postMessage({
type: "trilium-scroll-to-page",
pageNumber: page
}, window.location.origin);
},
requestThumbnail: (page: number) => {
iframeRef.current?.contentWindow?.postMessage({
type: "trilium-request-thumbnail",
pageNumber: page
}, window.location.origin);
}
});
}
if (event.data.type === "pdfjs-viewer-current-page") {
const currentPages = noteContext.getContextData("pdfPages");
if (currentPages) {
noteContext.setContextData("pdfPages", {
...currentPages,
currentPage: event.data.currentPage
});
}
}
if (event.data.type === "pdfjs-viewer-thumbnail") {
// Forward thumbnail to any listeners
window.dispatchEvent(new CustomEvent("pdf-thumbnail", {
detail: {
pageNumber: event.data.pageNumber,
dataUrl: event.data.dataUrl
}
}));
}
if (event.data.type === "pdfjs-viewer-attachments") {
noteContext.setContextData("pdfAttachments", {
attachments: event.data.attachments,
downloadAttachment: (filename: string) => {
iframeRef.current?.contentWindow?.postMessage({
type: "trilium-download-attachment",
filename
}, window.location.origin);
}
});
}
if (event.data.type === "pdfjs-viewer-layers") {
noteContext.setContextData("pdfLayers", {
layers: event.data.layers,
toggleLayer: (layerId: string, visible: boolean) => {
iframeRef.current?.contentWindow?.postMessage({
type: "trilium-toggle-layer",
layerId,
visible
}, window.location.origin);
}
});
}
}
window.addEventListener("message", handleMessage);
return () => {
window.removeEventListener("message", handleMessage);
};
}, [ note, historyConfig, componentId, blob ]);
}, [ note, historyConfig, componentId, blob, noteContext ]);
// Refresh when blob changes.
useEffect(() => {
@ -57,8 +157,8 @@ export default function PdfPreview({ note, blob, componentId, ntxId }: {
if (!iframe) return;
const handleIframeClick = () => {
if (ntxId) {
appContext.tabManager.activateNoteContext(ntxId);
if (noteContext.ntxId) {
appContext.tabManager.activateNoteContext(noteContext.ntxId);
}
};
@ -68,14 +168,14 @@ export default function PdfPreview({ note, blob, componentId, ntxId }: {
iframeDoc.addEventListener('click', handleIframeClick);
return () => iframeDoc.removeEventListener('click', handleIframeClick);
}
}, [ iframeRef.current?.contentWindow, ntxId ]);
}, [ iframeRef.current?.contentWindow, noteContext ]);
return (historyConfig &&
<iframe
tabIndex={300}
ref={iframeRef}
class="pdf-preview"
src={`pdfjs/web/viewer.html?file=../../api/notes/${note.noteId}/open&lang=${locale}`}
src={`pdfjs/web/viewer.html?file=../../api/notes/${note.noteId}/open&lang=${locale}&sidebar=${newLayout ? "0" : "1"}`}
onLoad={() => {
const win = iframeRef.current?.contentWindow;
if (win) {
@ -138,3 +238,40 @@ function cssVarsToString(vars: Record<string, string>) {
.map(([k, v]) => ` ${k}: ${v};`)
.join('\n')}\n}`;
}
interface PdfOutlineItem {
title: string;
level: number;
dest: unknown;
id: string;
items: PdfOutlineItem[];
}
interface PdfHeading {
level: number;
text: string;
id: string;
element: null;
}
function convertPdfOutlineToHeadings(outline: PdfOutlineItem[]): PdfHeading[] {
const headings: PdfHeading[] = [];
function flatten(items: PdfOutlineItem[]) {
for (const item of items) {
headings.push({
level: item.level + 1,
text: item.title,
id: item.id,
element: null // PDFs don't have DOM elements
});
if (item.items && item.items.length > 0) {
flatten(item.items);
}
}
}
flatten(outline);
return headings;
}

View File

@ -0,0 +1,117 @@
import { describe } from "node:test";
import test, { BrowserContext, expect, Page } from "@playwright/test";
import App from "../support/app";
test.beforeEach(async ({ page, context }) => {
const app = await setLayout({ page, context }, true);
await app.setOption("rightPaneCollapsedItems", "[]");
});
test.afterEach(async ({ page, context }) => await setLayout({ page, context }, false));
describe("PDF sidebar", () => {
test("Table of contents works", async ({ page, context }) => {
const app = new App(page, context);
await app.goto();
await app.goToNoteInNewTab("Dacia Logan.pdf");
const toc = app.sidebar.locator(".toc");
await expect(toc.locator("li")).toHaveCount(48);
await expect(toc.locator("li", { hasText: "Logan Van" })).toHaveCount(1);
const pdfHelper = new PdfHelper(app);
await toc.locator("li", { hasText: "Logan Pick-Up" }).click();
await pdfHelper.expectPageToBe(13);
await app.clickNoteOnNoteTreeByTitle("Layers test.pdf");
await expect(toc.locator("li")).toHaveCount(0);
});
test("Page navigation works", async ({ page, context }) => {
const app = new App(page, context);
await app.goto();
await app.goToNoteInNewTab("Dacia Logan.pdf");
const pagesList = app.sidebar.locator(".pdf-pages-list");
// Check count is correct.
await expect(app.sidebar).toContainText("28 pages");
expect(await pagesList.locator(".pdf-page-item").count()).toBe(28);
// Go to page 3.
await pagesList.locator(".pdf-page-item").nth(2).click();
const pdfHelper = new PdfHelper(app);
await pdfHelper.expectPageToBe(3);
await app.clickNoteOnNoteTreeByTitle("Layers test.pdf");
await expect(pagesList.locator(".pdf-page-item")).toHaveCount(1);
});
test("Attachments listing works", async ({ page, context }) => {
const app = new App(page, context);
await app.goto();
await app.goToNoteInNewTab("Dacia Logan.pdf");
const attachmentsList = app.sidebar.locator(".pdf-attachments-list");
await expect(app.sidebar).toContainText("2 attachments");
await expect(attachmentsList.locator(".pdf-attachment-item")).toHaveCount(2);
const attachmentInfo = attachmentsList.locator(".pdf-attachment-item", { hasText: "Note.trilium" });
await expect(attachmentInfo).toContainText("3.36 MiB");
// Download the attachment and check its size.
const [ download ] = await Promise.all([
page.waitForEvent("download"),
attachmentInfo.locator(".bx-download").click()
]);
expect(download).toBeDefined();
await app.clickNoteOnNoteTreeByTitle("Layers test.pdf");
await expect(attachmentsList.locator(".pdf-attachment-item")).toHaveCount(0);
});
test("Layers listing works", async ({ page, context }) => {
const app = new App(page, context);
await app.goto();
await app.goToNoteInNewTab("Layers test.pdf");
// Check count is correct.
await expect(app.sidebar).toContainText("2 layers");
const layersList = app.sidebar.locator(".pdf-layers-list");
await expect(layersList.locator(".pdf-layer-item")).toHaveCount(2);
// Toggle visibility of the first layer.
const firstLayer = layersList.locator(".pdf-layer-item").first();
await expect(firstLayer).toContainText("Tongue out");
await expect(firstLayer).toContainClass("hidden");
await firstLayer.click();
await expect(firstLayer).not.toContainClass("visible");
await app.clickNoteOnNoteTreeByTitle("Dacia Logan.pdf");
await expect(layersList.locator(".pdf-layer-item")).toHaveCount(0);
});
});
async function setLayout({ page, context}: { page: Page; context: BrowserContext }, newLayout: boolean) {
const app = new App(page, context);
await app.goto();
await app.setOption("newLayout", newLayout ? "true" : "false");
return app;
}
class PdfHelper {
private contentFrame: ReturnType<Page["frameLocator"]>;
constructor(app: App) {
this.contentFrame = app.currentNoteSplit.frameLocator("iframe");
}
async expectPageToBe(expectedPageNumber: number) {
await expect(this.contentFrame.locator("#pageNumber")).toHaveValue(`${expectedPageNumber}`);
}
}

Binary file not shown.

View File

@ -0,0 +1,80 @@
export async function setupPdfAttachments() {
// Extract immediately since we're called after documentloaded
await extractAndSendAttachments();
// Listen for download requests
window.addEventListener("message", async (event) => {
// Only accept messages from the same origin to prevent malicious iframes
if (event.origin !== window.location.origin) return;
if (event.data?.type === "trilium-download-attachment") {
const filename = event.data.filename;
await downloadAttachment(filename);
}
});
}
async function extractAndSendAttachments() {
const app = window.PDFViewerApplication;
try {
const attachments = await app.pdfDocument.getAttachments();
if (!attachments) {
window.parent.postMessage({
type: "pdfjs-viewer-attachments",
attachments: []
}, window.location.origin);
return;
}
// Convert attachments object to array
const attachmentList = Object.entries(attachments).map(([filename, data]: [string, any]) => ({
filename,
content: data.content, // Uint8Array
size: data.content?.length || 0
}));
// Send metadata only (not the full content)
window.parent.postMessage({
type: "pdfjs-viewer-attachments",
attachments: attachmentList.map(att => ({
filename: att.filename,
size: att.size
}))
}, window.location.origin);
} catch (error) {
console.error("Error extracting attachments:", error);
window.parent.postMessage({
type: "pdfjs-viewer-attachments",
attachments: []
}, window.location.origin);
}
}
async function downloadAttachment(filename: string) {
const app = window.PDFViewerApplication;
try {
const attachments = await app.pdfDocument.getAttachments();
const attachment = attachments?.[filename];
if (!attachment) {
console.error("Attachment not found:", filename);
return;
}
// Create blob and download
const blob = new Blob([attachment.content], { type: "application/octet-stream" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
} catch (error) {
console.error("Error downloading attachment:", error);
}
}

View File

@ -1,7 +1,16 @@
import interceptPersistence from "./persistence";
import { extractAndSendToc, setupScrollToHeading, setupActiveHeadingTracking } from "./toc";
import { setupPdfPages } from "./pages";
import { setupPdfAttachments } from "./attachments";
import { setupPdfLayers } from "./layers";
async function main() {
interceptPersistence(getCustomAppOptions());
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("sidebar") === "0") {
hideSidebar();
}
interceptPersistence(getCustomAppOptions(urlParams));
// Wait for the PDF viewer application to be available.
while (!window.PDFViewerApplication) {
@ -11,13 +20,29 @@ async function main() {
app.eventBus.on("documentloaded", () => {
manageSave();
extractAndSendToc();
setupScrollToHeading();
setupActiveHeadingTracking();
setupPdfPages();
setupPdfAttachments();
setupPdfLayers();
});
await app.initializedPromise;
};
function getCustomAppOptions() {
const urlParams = new URLSearchParams(window.location.search);
function hideSidebar() {
window.TRILIUM_HIDE_SIDEBAR = true;
const toggleButtonEl = document.getElementById("viewsManagerToggleButton");
if (toggleButtonEl) {
const spacer = toggleButtonEl.nextElementSibling.nextElementSibling;
if (spacer instanceof HTMLElement && spacer.classList.contains("toolbarButtonSpacer")) {
spacer.remove();
}
toggleButtonEl.remove();
}
}
function getCustomAppOptions(urlParams: URLSearchParams) {
return {
localeProperties: {
// Read from URL query

View File

@ -0,0 +1,119 @@
export async function setupPdfLayers() {
// Extract immediately since we're called after documentloaded
await extractAndSendLayers();
// Listen for layer visibility toggle requests
window.addEventListener("message", async (event) => {
// Only accept messages from the same origin to prevent malicious iframes
if (event.origin !== window.location.origin) return;
if (event.data?.type === "trilium-toggle-layer") {
const layerId = event.data.layerId;
const visible = event.data.visible;
await toggleLayer(layerId, visible);
}
});
}
async function extractAndSendLayers() {
const app = window.PDFViewerApplication;
try {
// Get the config from the viewer if available (has updated state), otherwise from document
const pdfViewer = app.pdfViewer;
const optionalContentConfig = pdfViewer?.optionalContentConfigPromise
? await pdfViewer.optionalContentConfigPromise
: await app.pdfDocument.getOptionalContentConfig();
if (!optionalContentConfig) {
window.parent.postMessage({
type: "pdfjs-viewer-layers",
layers: []
}, window.location.origin);
return;
}
// Get all layer group IDs from the order
const order = optionalContentConfig.getOrder();
if (!order || order.length === 0) {
window.parent.postMessage({
type: "pdfjs-viewer-layers",
layers: []
}, window.location.origin);
return;
}
// Flatten the order array (it can be nested) and extract group IDs
const groupIds: string[] = [];
const flattenOrder = (items: any[]) => {
for (const item of items) {
if (typeof item === 'string') {
groupIds.push(item);
} else if (Array.isArray(item)) {
flattenOrder(item);
} else if (item && typeof item === 'object' && item.id) {
groupIds.push(item.id);
}
}
};
flattenOrder(order);
// Get group details for each ID and only include valid, toggleable layers
const layers = groupIds.map(id => {
const group = optionalContentConfig.getGroup(id);
// Only include groups that have a name and usage property (actual layers)
if (!group || !group.name || !group.usage) {
return null;
}
// Use group.visible property like PDF.js viewer does
return {
id,
name: group.name,
visible: group.visible
};
}).filter(layer => layer !== null); // Filter out invalid layers
window.parent.postMessage({
type: "pdfjs-viewer-layers",
layers
}, window.location.origin);
} catch (error) {
console.error("Error extracting layers:", error);
window.parent.postMessage({
type: "pdfjs-viewer-layers",
layers: []
}, window.location.origin);
}
}
async function toggleLayer(layerId: string, visible: boolean) {
const app = window.PDFViewerApplication;
try {
const pdfViewer = app.pdfViewer;
if (!pdfViewer) {
return;
}
const optionalContentConfig = await pdfViewer.optionalContentConfigPromise;
if (!optionalContentConfig) {
return;
}
// Set visibility on the config (like PDF.js viewer does)
optionalContentConfig.setVisibility(layerId, visible);
// Dispatch optionalcontentconfig event with the existing config
app.eventBus.dispatch("optionalcontentconfig", {
source: app,
promise: Promise.resolve(optionalContentConfig)
});
// Send updated layer state back
await extractAndSendLayers();
} catch (error) {
console.error("Error toggling layer:", error);
}
}

View File

@ -0,0 +1,82 @@
export function setupPdfPages() {
const app = window.PDFViewerApplication;
// Send initial page info when pages are initialized
app.eventBus.on("pagesinit", () => {
sendPageInfo();
});
// Also send immediately if document is already loaded
if (app.pdfDocument && app.pdfViewer) {
sendPageInfo();
}
// Track current page changes
app.eventBus.on("pagechanging", (evt: any) => {
window.parent.postMessage({
type: "pdfjs-viewer-current-page",
currentPage: evt.pageNumber
}, window.location.origin);
});
window.addEventListener("message", async(event) => {
// Only accept messages from the same origin to prevent malicious iframes
if (event.origin !== window.location.origin) return;
if (event.data?.type === "trilium-scroll-to-page") {
const pageNumber = event.data.pageNumber;
app.pdfViewer.currentPageNumber = pageNumber;
}
if (event.data?.type === "trilium-request-thumbnail") {
const pageNumber = event.data.pageNumber;
await generateThumbnail(pageNumber);
}
});
}
function sendPageInfo() {
const app = window.PDFViewerApplication;
window.parent.postMessage({
type: "pdfjs-viewer-page-info",
totalPages: app.pdfDocument.numPages,
currentPage: app.pdfViewer.currentPageNumber
}, window.location.origin);
}
async function generateThumbnail(pageNumber: number) {
const app = window.PDFViewerApplication;
try {
const page = await app.pdfDocument.getPage(pageNumber);
// Create canvas for thumbnail
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
if (!context) return;
// Set thumbnail size (smaller than actual page)
const viewport = page.getViewport({ scale: 0.2 });
canvas.width = viewport.width;
canvas.height = viewport.height;
// Render page to canvas
await page.render({
canvas: canvas,
viewport: viewport
}).promise;
// Convert to data URL
const dataUrl = canvas.toDataURL('image/jpeg', 0.7);
// Send thumbnail to parent
window.parent.postMessage({
type: "pdfjs-viewer-thumbnail",
pageNumber,
dataUrl
}, window.location.origin);
} catch (error) {
console.error(`Error generating thumbnail for page %d:`, pageNumber, error);
}
}

View File

@ -0,0 +1,189 @@
let outlineMap: Map<string, any> | null = null;
let headingPositions: Array<{ id: string; pageIndex: number; y: number }> | null = null;
export async function extractAndSendToc() {
const app = window.PDFViewerApplication;
try {
const outline = await app.pdfDocument.getOutline();
if (!outline || outline.length === 0) {
window.parent.postMessage({
type: "pdfjs-viewer-toc",
data: null
}, window.location.origin);
return;
}
// Store outline items with their destinations for later scrolling
outlineMap = new Map();
headingPositions = [];
const toc = convertOutlineToToc(outline, 0, outlineMap);
// Build position mapping for active heading detection
await buildPositionMapping(outlineMap);
window.parent.postMessage({
type: "pdfjs-viewer-toc",
data: toc
}, window.location.origin);
} catch (error) {
window.parent.postMessage({
type: "pdfjs-viewer-toc",
data: null
}, window.location.origin);
}
}
function convertOutlineToToc(outline: any[], level = 0, outlineMap?: Map<string, any>, parentId = ""): any[] {
return outline.map((item, index) => {
const id = parentId ? `${parentId}-${index}` : `pdf-outline-${index}`;
if (outlineMap) {
outlineMap.set(id, item);
}
return {
title: item.title,
level: level,
dest: item.dest,
id: id,
items: item.items && item.items.length > 0 ? convertOutlineToToc(item.items, level + 1, outlineMap, id) : []
};
});
}
export function setupScrollToHeading() {
window.addEventListener("message", async (event) => {
// Only accept messages from the same origin to prevent malicious iframes
if (event.origin !== window.location.origin) return;
if (event.data?.type === "trilium-scroll-to-heading") {
const headingId = event.data.headingId;
if (!outlineMap) return;
const outlineItem = outlineMap.get(headingId);
if (!outlineItem || !outlineItem.dest) return;
const app = window.PDFViewerApplication;
// Navigate to the destination
try {
const dest = typeof outlineItem.dest === 'string'
? await app.pdfDocument.getDestination(outlineItem.dest)
: outlineItem.dest;
if (dest) {
app.pdfLinkService.goToDestination(dest);
}
} catch (error) {
console.error("Error navigating to heading:", error);
}
}
});
}
async function buildPositionMapping(outlineMap: Map<string, any>) {
const app = window.PDFViewerApplication;
for (const [id, item] of outlineMap.entries()) {
if (!item.dest) continue;
try {
const dest = typeof item.dest === 'string'
? await app.pdfDocument.getDestination(item.dest)
: item.dest;
if (dest && dest[0]) {
const pageRef = dest[0];
const pageIndex = await app.pdfDocument.getPageIndex(pageRef);
// Extract Y coordinate from destination (dest[3] is typically the y-coordinate)
const y = typeof dest[3] === 'number' ? dest[3] : 0;
headingPositions?.push({ id, pageIndex, y });
}
} catch (error) {
// Skip items with invalid destinations
}
}
// Sort by page and then by Y position (descending, since PDF coords are bottom-up)
headingPositions?.sort((a, b) => {
if (a.pageIndex !== b.pageIndex) {
return a.pageIndex - b.pageIndex;
}
return b.y - a.y; // Higher Y comes first (top of page)
});
}
export function setupActiveHeadingTracking() {
const app = window.PDFViewerApplication;
let lastActiveHeading: string | null = null;
// Offset from top of viewport to consider a heading "active"
// This makes the heading active when it's near the top, not when fully scrolled past
const ACTIVE_HEADING_OFFSET = 100;
function updateActiveHeading() {
if (!headingPositions || headingPositions.length === 0) return;
const viewer = app.pdfViewer;
const container = viewer.container;
const scrollTop = container.scrollTop;
// Find the heading closest to the top of the viewport
let activeHeadingId: string | null = null;
let bestDistance = Infinity;
for (const heading of headingPositions) {
// Get the page view to calculate actual position
const pageView = viewer.getPageView(heading.pageIndex);
if (!pageView || !pageView.div) {
continue;
}
const pageTop = pageView.div.offsetTop;
const pageHeight = pageView.div.clientHeight;
// Convert PDF Y coordinate (bottom-up) to screen position (top-down)
const headingScreenY = pageTop + (pageHeight - heading.y);
// Calculate distance from top of viewport
const distance = Math.abs(headingScreenY - scrollTop);
// If this heading is closer to the top of viewport, and it's not too far below
if (headingScreenY <= scrollTop + ACTIVE_HEADING_OFFSET && distance < bestDistance) {
activeHeadingId = heading.id;
bestDistance = distance;
}
}
if (activeHeadingId !== lastActiveHeading) {
lastActiveHeading = activeHeadingId;
window.parent.postMessage({
type: "pdfjs-viewer-active-heading",
headingId: activeHeadingId
}, window.location.origin);
}
}
// Debounced scroll handler
let scrollTimeout: number | null = null;
const debouncedUpdate = () => {
if (scrollTimeout) {
clearTimeout(scrollTimeout);
}
scrollTimeout = window.setTimeout(updateActiveHeading, 100);
};
app.eventBus.on("pagechanging", debouncedUpdate);
// Also listen to scroll events for more granular updates within a page
const container = app.pdfViewer.container;
container.addEventListener("scroll", debouncedUpdate);
// Initial update
updateActiveHeading();
}

View File

@ -14,10 +14,32 @@ declare global {
_readFromStorage: () => Promise<string>;
}
interface PdfJsDestination {
}
interface Window {
PDFViewerApplication?: {
initializedPromise: Promise<void>;
pdfDocument: PDFDocumentProxy;
pdfViewer: {
currentPageNumber: number;
optionalContentConfigPromise: {
setVisibility(groupId: string, visible: boolean);
getGroup(groupId: string): {
name: string;
usage: {};
};
getOrder(): {}[]
};
getPageView(pageIndex: number): {
div: HTMLDivElement;
};
container: HTMLElement;
};
pdfLinkService: {
goToDestination(dest: PdfJsDestination);
};
eventBus: {
on(event: string, listener: (...args: any[]) => void): void;
dispatch(event: string, data?: any): void;

View File

@ -18609,7 +18609,7 @@ function getViewerConfiguration() {
imageAltTextSettingsSeparator: document.getElementById("imageAltTextSettingsSeparator"),
documentPropertiesButton: document.getElementById("documentProperties")
},
viewsManager: {
viewsManager: window.TRILIUM_HIDE_SIDEBAR ? null : {
outerContainer: document.getElementById("outerContainer"),
toggleButton: document.getElementById("viewsManagerToggleButton"),
sidebarContainer: document.getElementById("viewsManager"),