An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support PDF navigation history https://github.com/siyuan-note/siyuan/issues/11750
Danield1cdb94e3772
diff --git a/app/src/asset/index.ts b/app/src/asset/index.tsindex 21cf725100..c514ccf976 100644--- a/app/src/asset/index.ts+++ b/app/src/asset/index.ts@@ -299,6 +299,12 @@ export class Asset extends Model {<input type="number" id="pageNumber" class="toolbarField pageNumber b3-text-field" value="1" size="4" min="1" autocomplete="off"><span id="numPages"></span><div class="fn__flex-1"></div>+ <button id="pdfHistoryBack" class="toolbarButton b3-tooltips b3-tooltips__sw" aria-label="${window.siyuan.languages.goBack}" disabled>+ <svg><use xlink:href="#iconBack"></use></svg>+ </button>+ <button id="pdfHistoryForward" class="toolbarButton b3-tooltips b3-tooltips__sw" aria-label="${window.siyuan.languages.goForward}" disabled>+ <svg><use xlink:href="#iconForward"></use></svg>+ </button><span id="scaleSelectContainer" class="dropdownToolbarButton"><select id="scaleSelect" class="b3-select"><option id="pageAutoOption" value="auto" selected="selected">${window.siyuan.languages.pageScaleAuto}</option>diff --git a/app/src/asset/pdf/app.js b/app/src/asset/pdf/app.jsindex 25a06043d1..d4ca710209 100644--- a/app/src/asset/pdf/app.js+++ b/app/src/asset/pdf/app.js@@ -75,6 +75,7 @@ import {PDFDocumentProperties} from "./pdf_document_properties";import {PDFFindBar} from "./pdf_find_bar";import {PDFFindController} from "./pdf_find_controller.js";import {PDFHistory} from "./pdf_history.js";+import {PDFNavigationHistory} from "./navigationHistory";import {PDFLayerViewer} from "./pdf_layer_viewer";import {PDFOutlineViewer} from "./pdf_outline_viewer";import {PDFPresentationMode} from "./pdf_presentation_mode";@@ -514,9 +515,15 @@ class PDFViewerApplication {pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);}- // The browsing history is only enabled when the viewer is standalone,- // i.e. not when it is embedded in a web page.- if (!this.isViewerEmbedded && !AppOptions.get("disableHistory")) {+ // 嵌入式阅读器使用实例级历史,避免多个 PDF 页签共享浏览器历史+ if (this.isViewerEmbedded && !AppOptions.get("disableHistory")) {+ this.pdfHistory = new PDFNavigationHistory({+ linkService: pdfLinkService,+ eventBus,+ limit: Constants.SIZE_UNDO,+ });+ pdfLinkService.setHistory(this.pdfHistory);+ } else if (!AppOptions.get("disableHistory")) {this.pdfHistory = new PDFHistory({linkService: pdfLinkService,eventBus,@@ -1329,6 +1336,9 @@ class PDFViewerApplication {let scrollMode = AppOptions.get("scrollModeOnLoad");let spreadMode = AppOptions.get("spreadModeOnLoad");// NOTE+ if (this.pdfId && stored.page) {+ this.pdfHistory?.seedPreviousPosition?.(stored);+ }stored.page = this.pdfId || stored.page;if (stored?.page && viewOnLoad !== ViewOnLoad.INITIAL) {hash =@@ -1946,6 +1956,9 @@ class PDFViewerApplication {eventBus._on("lastpage", () => (this.page = this.pagesCount), {signal});eventBus._on("nextpage", () => pdfViewer.nextPage(), {signal});eventBus._on("previouspage", () => pdfViewer.previousPage(), {signal});+ eventBus._on("pdfhistoryback", () => this.pdfHistory?.back(), {signal});+ eventBus._on("pdfhistoryforward", () => this.pdfHistory?.forward(), {signal});+ eventBus._on("pdfhistorystatechanged", onPDFHistoryStateChanged.bind(this), {signal});eventBus._on("zoomin", this.zoomIn.bind(this), {signal});eventBus._on("zoomout", this.zoomOut.bind(this), {signal});eventBus._on("zoomreset", this.zoomReset.bind(this), {signal});@@ -2487,6 +2500,10 @@ function onPageNumberChanged(evt) {}}+function onPDFHistoryStateChanged({canGoBack, canGoForward}) {+ this.toolbar?.setHistoryState(canGoBack, canGoForward);+}+function onImageAltTextSettings() {this.imageAltTextSettings?.open({enableGuessAltText: AppOptions.get("enableGuessAltText"),diff --git a/app/src/asset/pdf/navigationHistory.test.ts b/app/src/asset/pdf/navigationHistory.test.tsnew file mode 100644index 0000000000..51179a0e51--- /dev/null+++ b/app/src/asset/pdf/navigationHistory.test.ts@@ -0,0 +1,185 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {PDFNavigationHistory, PDFNavigationStack} from "./navigationHistory";++class TestEventBus {+ private listeners = new Map<string, Array<(event: any) => void>>();++ public _on(eventName: string, listener: (event: any) => void, options?: {signal?: AbortSignal}) {+ const listeners = this.listeners.get(eventName) || [];+ listeners.push(listener);+ this.listeners.set(eventName, listeners);+ options?.signal?.addEventListener("abort", () => {+ this.listeners.set(eventName, (this.listeners.get(eventName) || []).filter((item) => item !== listener));+ }, {once: true});+ }++ public dispatch(eventName: string, data: unknown) {+ (this.listeners.get(eventName) || []).forEach((listener) => listener(data));+ }++ public update(page: number, top = 0) {+ this.dispatch("updateviewarea", {+ location: {+ pageNumber: page,+ pdfOpenParams: `#page=${page}&zoom=100,0,${top}`,+ rotation: 0,+ },+ });+ }+}++class TestLinkService {+ public page = 1;+ public pagesCount = 20;+ public rotation = 0;+ public lastHash = "";+ private readonly eventBus: TestEventBus;++ constructor(eventBus: TestEventBus) {+ this.eventBus = eventBus;+ }++ public async goToDestination() {+ this.eventBus.update(this.page);+ }++ public setHash(hash: string) {+ this.lastHash = hash;+ const page = Number.parseInt(new URLSearchParams(hash).get("page"), 10);+ if (Number.isInteger(page)) {+ this.page = page;+ }+ this.eventBus.update(this.page);+ }+}++const createHistory = () => {+ const eventBus = new TestEventBus();+ const linkService = new TestLinkService(eventBus);+ const history = new PDFNavigationHistory({eventBus, linkService, limit: 64});+ history.initialize();+ return {eventBus, history, linkService};+};++describe("PDFNavigationStack", () => {+ it("navigates backward and forward", () => {+ const stack = new PDFNavigationStack(64);+ stack.seed({hash: "page=1"});+ stack.push({hash: "page=8"});++ assert.equal(stack.canGoBack, true);+ assert.equal(stack.canGoForward, false);+ assert.equal(stack.back()?.hash, "page=1");+ assert.equal(stack.canGoForward, true);+ assert.equal(stack.forward()?.hash, "page=8");+ });++ it("drops forward entries after a new jump", () => {+ const stack = new PDFNavigationStack(64);+ stack.seed({hash: "page=1"});+ stack.push({hash: "page=2"});+ stack.push({hash: "page=3"});+ stack.back();+ stack.push({hash: "page=4"});++ assert.equal(stack.current?.hash, "page=4");+ assert.equal(stack.canGoForward, false);+ assert.equal(stack.length, 3);+ });++ it("replaces duplicate positions", () => {+ const stack = new PDFNavigationStack(64);+ stack.seed({hash: "page=1", rotation: 0});++ assert.equal(stack.push({hash: "page=1", rotation: 0}), false);+ assert.equal(stack.length, 1);+ });++ it("limits the number of retained entries", () => {+ const stack = new PDFNavigationStack(3);+ stack.seed({hash: "page=1"});+ stack.push({hash: "page=2"});+ stack.push({hash: "page=3"});+ stack.push({hash: "page=4"});++ assert.equal(stack.length, 3);+ assert.equal(stack.back()?.hash, "page=3");+ assert.equal(stack.back()?.hash, "page=2");+ assert.equal(stack.canGoBack, false);+ });+});++describe("PDFNavigationHistory", () => {+ it("uses a stored position as the previous entry for an initial reference", async () => {+ const {eventBus, history, linkService} = createHistory();+ history.seedPreviousPosition({+ page: 2,+ rotation: 0,+ scrollLeft: 10,+ scrollTop: 200,+ zoom: 125,+ });+ linkService.page = 8;+ eventBus.update(8);++ await history.back();+ assert.equal(linkService.page, 2);+ assert.equal(linkService.lastHash, "page=2&zoom=125,10,200");++ await history.forward();+ assert.equal(linkService.page, 8);+ history.reset();+ });++ it("does not add the same page twice without moving", async () => {+ const {eventBus, history, linkService} = createHistory();+ eventBus.update(1);+ history.pushCurrentPosition();+ history.pushPage(8);+ linkService.page = 8;+ eventBus.update(8);++ history.pushCurrentPosition();+ history.pushPage(8);+ await history.back();+ assert.equal(linkService.page, 1);++ await history.back();+ assert.equal(linkService.page, 1);+ history.reset();+ });++ it("records a same-page jump only after the view position changes", async () => {+ const {eventBus, history, linkService} = createHistory();+ linkService.page = 8;+ eventBus.update(8);+ eventBus.update(8, 400);+ history.pushCurrentPosition();+ history.pushPage(8);+ eventBus.update(8);++ await history.back();+ assert.equal(linkService.lastHash, "page=8&zoom=100,0,400");+ history.reset();+ });++ it("keeps histories isolated between PDF instances", async () => {+ const first = createHistory();+ const second = createHistory();+ first.eventBus.update(1);+ second.linkService.page = 4;+ second.eventBus.update(4);+ first.history.pushCurrentPosition();+ first.history.pushPage(10);+ first.linkService.page = 10;+ first.eventBus.update(10);++ await second.history.back();+ assert.equal(second.linkService.page, 4);+ await first.history.back();+ assert.equal(first.linkService.page, 1);+ first.history.reset();+ second.history.reset();+ });+});diff --git a/app/src/asset/pdf/navigationHistory.ts b/app/src/asset/pdf/navigationHistory.tsnew file mode 100644index 0000000000..848c821334--- /dev/null+++ b/app/src/asset/pdf/navigationHistory.ts@@ -0,0 +1,377 @@+export interface PDFNavigationEntry {+ dest?: string | unknown[];+ hash?: string;+ key?: string;+ landingHash?: string;+ page?: number;+ rotation?: number;+}++interface PDFNavigationLocation {+ pageNumber: number;+ pdfOpenParams: string;+ rotation: number;+}++interface PDFNavigationEventBus {+ _on(eventName: string, listener: (event: {location: PDFNavigationLocation}) => void,+ options?: {signal?: AbortSignal}): void;+ dispatch(eventName: string, data: unknown): void;+}++interface PDFNavigationLinkService {+ goToDestination(destination: string | unknown[]): Promise<void> | void;+ page: number;+ pagesCount: number;+ rotation: number;+ setHash(hash: string): void;+}++interface PDFStoredPosition {+ page?: number | string;+ rotation?: number | string;+ scrollLeft?: number | string;+ scrollTop?: number | string;+ zoom?: number | string;+}++const entriesEqual = (first: PDFNavigationEntry, second: PDFNavigationEntry) => {+ return first.hash === second.hash && (first.rotation ?? 0) === (second.rotation ?? 0);+};++export class PDFNavigationStack {+ private entries: PDFNavigationEntry[] = [];+ private index = -1;+ private readonly limit: number;++ constructor(limit: number) {+ this.limit = Math.max(1, limit);+ }++ public get canGoBack() {+ return this.index > 0;+ }++ public get canGoForward() {+ return this.index >= 0 && this.index < this.entries.length - 1;+ }++ public get current() {+ return this.index >= 0 ? this.entries[this.index] : undefined;+ }++ public get length() {+ return this.entries.length;+ }++ public reset() {+ this.entries = [];+ this.index = -1;+ }++ public seed(entry: PDFNavigationEntry) {+ this.entries = [entry];+ this.index = 0;+ }++ public replace(entry: PDFNavigationEntry) {+ if (this.index < 0) {+ this.seed(entry);+ return;+ }+ this.entries[this.index] = entry;+ }++ public push(entry: PDFNavigationEntry, equals = entriesEqual) {+ if (this.current && equals(this.current, entry)) {+ this.replace(entry);+ return false;+ }+ this.entries.splice(this.index + 1);+ this.entries.push(entry);+ if (this.entries.length > this.limit) {+ this.entries.shift();+ }+ this.index = this.entries.length - 1;+ return true;+ }++ public back() {+ if (!this.canGoBack) {+ return;+ }+ this.index--;+ return this.current;+ }++ public forward() {+ if (!this.canGoForward) {+ return;+ }+ this.index++;+ return this.current;+ }+}++export class PDFNavigationHistory {+ private readonly eventBus: PDFNavigationEventBus;+ private readonly linkService: PDFNavigationLinkService;+ private readonly stack: PDFNavigationStack;+ private eventAbortController: AbortController;+ private initialized = false;+ private appendInitialPosition = false;+ private awaitingLanding = false;+ private navigationStartHash: string;+ private navigationTimeout: ReturnType<typeof setTimeout>;+ private position: PDFNavigationEntry;+ private restoring = false;++ constructor(options: {+ eventBus: PDFNavigationEventBus,+ linkService: PDFNavigationLinkService,+ limit: number,+ }) {+ this.eventBus = options.eventBus;+ this.linkService = options.linkService;+ this.stack = new PDFNavigationStack(options.limit);+ }++ public get initialBookmark(): string | null {+ return null;+ }++ public get initialRotation(): number | null {+ return null;+ }++ public get popStateInProgress() {+ return this.restoring || this.awaitingLanding;+ }++ public initialize() {+ this.reset();+ this.initialized = true;+ this.eventAbortController = new AbortController();+ this.eventBus._on("updateviewarea", this.updateViewarea.bind(this), {+ signal: this.eventAbortController.signal,+ });+ this.dispatchState();+ }++ public reset() {+ this.initialized = false;+ this.eventAbortController?.abort();+ this.eventAbortController = undefined;+ this.clearNavigationTimeout();+ this.stack.reset();+ this.position = undefined;+ this.appendInitialPosition = false;+ this.awaitingLanding = false;+ this.navigationStartHash = undefined;+ this.restoring = false;+ this.dispatchState();+ }++ public seedPreviousPosition(stored: PDFStoredPosition) {+ if (!this.initialized) {+ return;+ }+ const page = Number.parseInt(stored.page?.toString(), 10);+ if (!Number.isInteger(page) || page < 1 || page > this.linkService.pagesCount) {+ return;+ }+ const zoom = stored.zoom || "auto";+ const scrollLeft = stored.scrollLeft ?? 0;+ const scrollTop = stored.scrollTop ?? 0;+ const rotation = Number.parseInt(stored.rotation?.toString(), 10);+ this.stack.seed({+ hash: `page=${page}&zoom=${zoom},${scrollLeft},${scrollTop}`,+ landingHash: `page=${page}&zoom=${zoom},${scrollLeft},${scrollTop}`,+ page,+ rotation: Number.isInteger(rotation) ? rotation : undefined,+ });+ this.appendInitialPosition = true;+ this.dispatchState();+ }++ public pushCurrentPosition() {+ if (!this.initialized || this.popStateInProgress || !this.position) {+ return;+ }+ const current = this.stack.current;+ this.stack.replace({+ ...this.position,+ key: current?.key,+ landingHash: current?.landingHash,+ });+ }++ public push(options: {namedDest?: string, explicitDest: unknown[], pageNumber: number}) {+ if (!this.initialized || this.popStateInProgress) {+ return;+ }+ const hash = options.namedDest || JSON.stringify(options.explicitDest);+ this.pushTarget({+ dest: options.explicitDest,+ hash,+ key: `dest:${hash}`,+ page: options.pageNumber,+ rotation: this.linkService.rotation,+ });+ }++ public pushPage(pageNumber: number) {+ if (!this.initialized || this.popStateInProgress || !Number.isInteger(pageNumber) ||+ pageNumber < 1 || pageNumber > this.linkService.pagesCount) {+ return;+ }+ const hash = `page=${pageNumber}`;+ this.pushTarget({+ hash,+ key: hash,+ page: pageNumber,+ rotation: this.linkService.rotation,+ });+ }++ public async back() {+ if (!this.initialized || this.popStateInProgress || !this.stack.canGoBack) {+ return;+ }+ this.snapshotCurrentPosition();+ const entry = this.stack.back();+ if (entry) {+ await this.restore(entry);+ }+ }++ public async forward() {+ if (!this.initialized || this.popStateInProgress || !this.stack.canGoForward) {+ return;+ }+ this.snapshotCurrentPosition();+ const entry = this.stack.forward();+ if (entry) {+ await this.restore(entry);+ }+ }++ private pushTarget(entry: PDFNavigationEntry) {+ const current = this.stack.current;+ if (current?.key === entry.key && current.landingHash === this.position?.hash) {+ return;+ }+ this.appendInitialPosition = false;+ this.stack.push(entry, () => false);+ this.awaitingLanding = true;+ this.navigationStartHash = this.position?.hash;+ this.startNavigationTimeout();+ this.dispatchState();+ }++ private snapshotCurrentPosition() {+ if (!this.position) {+ return;+ }+ const current = this.stack.current;+ this.stack.replace({+ ...this.position,+ key: current?.key,+ landingHash: current?.landingHash,+ });+ }++ private async restore(entry: PDFNavigationEntry) {+ this.restoring = true;+ this.navigationStartHash = this.position?.hash;+ this.dispatchState();+ try {+ if (entry.dest) {+ await this.linkService.goToDestination(entry.dest);+ } else if (entry.hash) {+ this.linkService.setHash(entry.hash);+ } else if (entry.page) {+ this.linkService.page = entry.page;+ }+ if (Number.isInteger(entry.rotation)) {+ this.linkService.rotation = entry.rotation;+ }+ } finally {+ if (this.restoring) {+ this.startNavigationTimeout();+ }+ }+ }++ private updateViewarea(event: {location: PDFNavigationLocation}) {+ const hash = event.location?.pdfOpenParams?.substring(1);+ if (!hash) {+ return;+ }+ this.position = {+ hash,+ page: this.linkService.page || event.location.pageNumber,+ rotation: event.location.rotation,+ };+ if (!this.initialized) {+ return;+ }++ const current = this.stack.current;+ if (!current) {+ this.stack.seed({...this.position, landingHash: hash});+ } else if (this.appendInitialPosition) {+ this.stack.push({...this.position, landingHash: hash});+ this.appendInitialPosition = false;+ } else if (this.awaitingLanding || this.restoring) {+ this.stack.replace({+ ...this.position,+ key: current.key,+ landingHash: this.awaitingLanding ? hash : current.landingHash,+ });+ }++ if (this.awaitingLanding || this.restoring) {+ this.awaitingLanding = false;+ this.restoring = false;+ this.navigationStartHash = undefined;+ this.clearNavigationTimeout();+ }+ this.dispatchState();+ }++ private startNavigationTimeout() {+ this.clearNavigationTimeout();+ this.navigationTimeout = setTimeout(() => {+ if (this.position && this.position.hash !== this.navigationStartHash &&+ (this.awaitingLanding || this.restoring)) {+ const current = this.stack.current;+ this.stack.replace({+ ...this.position,+ key: current?.key,+ landingHash: this.awaitingLanding ? this.position.hash : current?.landingHash,+ });+ }+ this.awaitingLanding = false;+ this.restoring = false;+ this.navigationStartHash = undefined;+ this.navigationTimeout = undefined;+ this.dispatchState();+ }, 1000);+ }++ private clearNavigationTimeout() {+ if (this.navigationTimeout) {+ clearTimeout(this.navigationTimeout);+ this.navigationTimeout = undefined;+ }+ }++ private dispatchState() {+ this.eventBus.dispatch("pdfhistorystatechanged", {+ canGoBack: !this.popStateInProgress && this.stack.canGoBack,+ canGoForward: !this.popStateInProgress && this.stack.canGoForward,+ source: this,+ });+ }+}diff --git a/app/src/asset/pdf/toolbar.js b/app/src/asset/pdf/toolbar.jsindex 7c6a50112b..baf986e478 100644--- a/app/src/asset/pdf/toolbar.js+++ b/app/src/asset/pdf/toolbar.js@@ -30,6 +30,8 @@ import {* @property {HTMLSpanElement} numPages - Label that contains number of pages.* @property {HTMLInputElement} pageNumber - Control for display and user input* of the current page number.+ * @property {HTMLButtonElement} historyBack - PDF 历史后退按钮。+ * @property {HTMLButtonElement} historyForward - PDF 历史前进按钮。* @property {HTMLSelectElement} scaleSelect - Scale selection control.* Its width is adjusted, when necessary, on UI localization.* @property {HTMLOptionElement} customScaleOption - The item used to display@@ -59,6 +61,8 @@ class Toolbar {this.#opts = options;this.eventBus = eventBus;const buttons = [+ { element: options.historyBack, eventName: "pdfhistoryback" },+ { element: options.historyForward, eventName: "pdfhistoryforward" },{ element: options.previous, eventName: "previouspage" },{ element: options.next, eventName: "nextpage" },{ element: options.zoomIn, eventName: "zoomin" },@@ -163,6 +167,11 @@ class Toolbar {this.#updateUIState(false);}+ setHistoryState(canGoBack, canGoForward) {+ this.#opts.historyBack.disabled = !canGoBack;+ this.#opts.historyForward.disabled = !canGoForward;+ }+reset() {this.pageNumber = 0;this.pageLabel = null;@@ -170,6 +179,7 @@ class Toolbar {this.pagesCount = 0;this.pageScaleValue = DEFAULT_SCALE_VALUE;this.pageScale = DEFAULT_SCALE;+ this.setHistoryState(false, false);this.#updateUIState(true);this.updateLoadingIndicatorState();diff --git a/app/src/asset/pdf/viewer.js b/app/src/asset/pdf/viewer.jsindex c263666801..dc90be10c3 100644--- a/app/src/asset/pdf/viewer.js+++ b/app/src/asset/pdf/viewer.js@@ -50,6 +50,8 @@ function getViewerConfiguration(element) {container: element.querySelector("#toolbarContainer"),numPages: element.querySelector("#numPages"),pageNumber: element.querySelector("#pageNumber"),+ historyBack: element.querySelector("#pdfHistoryBack"),+ historyForward: element.querySelector("#pdfHistoryForward"),scaleSelect: element.querySelector("#scaleSelect"),customScaleOption: element.querySelector("#customScaleOption"),previous: element.querySelector("#previous"),